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                                      const TemplateParameterList *Params) {
981   SmallString<128> SS;
982   llvm::raw_svector_ostream OS(SS);
983   bool First = true;
984   unsigned I = 0;
985   for (auto &Arg : Args.arguments()) {
986     if (!First)
987       OS << ", ";
988     Arg.getArgument().print(
989         PrintingPolicy, OS,
990         TemplateParameterList::shouldIncludeTypeForArgument(Params, I));
991     First = false;
992     I++;
993   }
994   return std::string(OS.str());
995 }
996 
997 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
998                                      SourceLocation Loc, StringRef Trait,
999                                      TemplateArgumentListInfo &Args,
1000                                      unsigned DiagID) {
1001   auto DiagnoseMissing = [&] {
1002     if (DiagID)
1003       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1004                                                Args, /*Params*/ nullptr);
1005     return true;
1006   };
1007 
1008   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1009   NamespaceDecl *Std = S.getStdNamespace();
1010   if (!Std)
1011     return DiagnoseMissing();
1012 
1013   // Look up the trait itself, within namespace std. We can diagnose various
1014   // problems with this lookup even if we've been asked to not diagnose a
1015   // missing specialization, because this can only fail if the user has been
1016   // declaring their own names in namespace std or we don't support the
1017   // standard library implementation in use.
1018   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1019                       Loc, Sema::LookupOrdinaryName);
1020   if (!S.LookupQualifiedName(Result, Std))
1021     return DiagnoseMissing();
1022   if (Result.isAmbiguous())
1023     return true;
1024 
1025   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1026   if (!TraitTD) {
1027     Result.suppressDiagnostics();
1028     NamedDecl *Found = *Result.begin();
1029     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1030     S.Diag(Found->getLocation(), diag::note_declared_at);
1031     return true;
1032   }
1033 
1034   // Build the template-id.
1035   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1036   if (TraitTy.isNull())
1037     return true;
1038   if (!S.isCompleteType(Loc, TraitTy)) {
1039     if (DiagID)
1040       S.RequireCompleteType(
1041           Loc, TraitTy, DiagID,
1042           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1043                             TraitTD->getTemplateParameters()));
1044     return true;
1045   }
1046 
1047   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1048   assert(RD && "specialization of class template is not a class?");
1049 
1050   // Look up the member of the trait type.
1051   S.LookupQualifiedName(TraitMemberLookup, RD);
1052   return TraitMemberLookup.isAmbiguous();
1053 }
1054 
1055 static TemplateArgumentLoc
1056 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1057                                    uint64_t I) {
1058   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1059   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1060 }
1061 
1062 static TemplateArgumentLoc
1063 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1064   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1065 }
1066 
1067 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1068 
1069 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1070                                llvm::APSInt &Size) {
1071   EnterExpressionEvaluationContext ContextRAII(
1072       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1073 
1074   DeclarationName Value = S.PP.getIdentifierInfo("value");
1075   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1076 
1077   // Form template argument list for tuple_size<T>.
1078   TemplateArgumentListInfo Args(Loc, Loc);
1079   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1080 
1081   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1082   // it's not tuple-like.
1083   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1084       R.empty())
1085     return IsTupleLike::NotTupleLike;
1086 
1087   // If we get this far, we've committed to the tuple interpretation, but
1088   // we can still fail if there actually isn't a usable ::value.
1089 
1090   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1091     LookupResult &R;
1092     TemplateArgumentListInfo &Args;
1093     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1094         : R(R), Args(Args) {}
1095     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1096                                                SourceLocation Loc) override {
1097       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1098              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1099                                   /*Params*/ nullptr);
1100     }
1101   } Diagnoser(R, Args);
1102 
1103   ExprResult E =
1104       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1105   if (E.isInvalid())
1106     return IsTupleLike::Error;
1107 
1108   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1109   if (E.isInvalid())
1110     return IsTupleLike::Error;
1111 
1112   return IsTupleLike::TupleLike;
1113 }
1114 
1115 /// \return std::tuple_element<I, T>::type.
1116 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1117                                         unsigned I, QualType T) {
1118   // Form template argument list for tuple_element<I, T>.
1119   TemplateArgumentListInfo Args(Loc, Loc);
1120   Args.addArgument(
1121       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1122   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1123 
1124   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1125   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1126   if (lookupStdTypeTraitMember(
1127           S, R, Loc, "tuple_element", Args,
1128           diag::err_decomp_decl_std_tuple_element_not_specialized))
1129     return QualType();
1130 
1131   auto *TD = R.getAsSingle<TypeDecl>();
1132   if (!TD) {
1133     R.suppressDiagnostics();
1134     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1135         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1136                              /*Params*/ nullptr);
1137     if (!R.empty())
1138       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1139     return QualType();
1140   }
1141 
1142   return S.Context.getTypeDeclType(TD);
1143 }
1144 
1145 namespace {
1146 struct InitializingBinding {
1147   Sema &S;
1148   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1149     Sema::CodeSynthesisContext Ctx;
1150     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1151     Ctx.PointOfInstantiation = BD->getLocation();
1152     Ctx.Entity = BD;
1153     S.pushCodeSynthesisContext(Ctx);
1154   }
1155   ~InitializingBinding() {
1156     S.popCodeSynthesisContext();
1157   }
1158 };
1159 }
1160 
1161 static bool checkTupleLikeDecomposition(Sema &S,
1162                                         ArrayRef<BindingDecl *> Bindings,
1163                                         VarDecl *Src, QualType DecompType,
1164                                         const llvm::APSInt &TupleSize) {
1165   if ((int64_t)Bindings.size() != TupleSize) {
1166     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1167         << DecompType << (unsigned)Bindings.size()
1168         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1169         << TupleSize.toString(10) << (TupleSize < Bindings.size());
1170     return true;
1171   }
1172 
1173   if (Bindings.empty())
1174     return false;
1175 
1176   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1177 
1178   // [dcl.decomp]p3:
1179   //   The unqualified-id get is looked up in the scope of E by class member
1180   //   access lookup ...
1181   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1182   bool UseMemberGet = false;
1183   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1184     if (auto *RD = DecompType->getAsCXXRecordDecl())
1185       S.LookupQualifiedName(MemberGet, RD);
1186     if (MemberGet.isAmbiguous())
1187       return true;
1188     //   ... and if that finds at least one declaration that is a function
1189     //   template whose first template parameter is a non-type parameter ...
1190     for (NamedDecl *D : MemberGet) {
1191       if (FunctionTemplateDecl *FTD =
1192               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1193         TemplateParameterList *TPL = FTD->getTemplateParameters();
1194         if (TPL->size() != 0 &&
1195             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1196           //   ... the initializer is e.get<i>().
1197           UseMemberGet = true;
1198           break;
1199         }
1200       }
1201     }
1202   }
1203 
1204   unsigned I = 0;
1205   for (auto *B : Bindings) {
1206     InitializingBinding InitContext(S, B);
1207     SourceLocation Loc = B->getLocation();
1208 
1209     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1210     if (E.isInvalid())
1211       return true;
1212 
1213     //   e is an lvalue if the type of the entity is an lvalue reference and
1214     //   an xvalue otherwise
1215     if (!Src->getType()->isLValueReferenceType())
1216       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1217                                    E.get(), nullptr, VK_XValue,
1218                                    FPOptionsOverride());
1219 
1220     TemplateArgumentListInfo Args(Loc, Loc);
1221     Args.addArgument(
1222         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1223 
1224     if (UseMemberGet) {
1225       //   if [lookup of member get] finds at least one declaration, the
1226       //   initializer is e.get<i-1>().
1227       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1228                                      CXXScopeSpec(), SourceLocation(), nullptr,
1229                                      MemberGet, &Args, nullptr);
1230       if (E.isInvalid())
1231         return true;
1232 
1233       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1234     } else {
1235       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1236       //   in the associated namespaces.
1237       Expr *Get = UnresolvedLookupExpr::Create(
1238           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1239           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1240           UnresolvedSetIterator(), UnresolvedSetIterator());
1241 
1242       Expr *Arg = E.get();
1243       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1244     }
1245     if (E.isInvalid())
1246       return true;
1247     Expr *Init = E.get();
1248 
1249     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1250     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1251     if (T.isNull())
1252       return true;
1253 
1254     //   each vi is a variable of type "reference to T" initialized with the
1255     //   initializer, where the reference is an lvalue reference if the
1256     //   initializer is an lvalue and an rvalue reference otherwise
1257     QualType RefType =
1258         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1259     if (RefType.isNull())
1260       return true;
1261     auto *RefVD = VarDecl::Create(
1262         S.Context, Src->getDeclContext(), Loc, Loc,
1263         B->getDeclName().getAsIdentifierInfo(), RefType,
1264         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1265     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1266     RefVD->setTSCSpec(Src->getTSCSpec());
1267     RefVD->setImplicit();
1268     if (Src->isInlineSpecified())
1269       RefVD->setInlineSpecified();
1270     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1271 
1272     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1273     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1274     InitializationSequence Seq(S, Entity, Kind, Init);
1275     E = Seq.Perform(S, Entity, Kind, Init);
1276     if (E.isInvalid())
1277       return true;
1278     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1279     if (E.isInvalid())
1280       return true;
1281     RefVD->setInit(E.get());
1282     S.CheckCompleteVariableDeclaration(RefVD);
1283 
1284     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1285                                    DeclarationNameInfo(B->getDeclName(), Loc),
1286                                    RefVD);
1287     if (E.isInvalid())
1288       return true;
1289 
1290     B->setBinding(T, E.get());
1291     I++;
1292   }
1293 
1294   return false;
1295 }
1296 
1297 /// Find the base class to decompose in a built-in decomposition of a class type.
1298 /// This base class search is, unfortunately, not quite like any other that we
1299 /// perform anywhere else in C++.
1300 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1301                                                 const CXXRecordDecl *RD,
1302                                                 CXXCastPath &BasePath) {
1303   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1304                           CXXBasePath &Path) {
1305     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1306   };
1307 
1308   const CXXRecordDecl *ClassWithFields = nullptr;
1309   AccessSpecifier AS = AS_public;
1310   if (RD->hasDirectFields())
1311     // [dcl.decomp]p4:
1312     //   Otherwise, all of E's non-static data members shall be public direct
1313     //   members of E ...
1314     ClassWithFields = RD;
1315   else {
1316     //   ... or of ...
1317     CXXBasePaths Paths;
1318     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1319     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1320       // If no classes have fields, just decompose RD itself. (This will work
1321       // if and only if zero bindings were provided.)
1322       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1323     }
1324 
1325     CXXBasePath *BestPath = nullptr;
1326     for (auto &P : Paths) {
1327       if (!BestPath)
1328         BestPath = &P;
1329       else if (!S.Context.hasSameType(P.back().Base->getType(),
1330                                       BestPath->back().Base->getType())) {
1331         //   ... the same ...
1332         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1333           << false << RD << BestPath->back().Base->getType()
1334           << P.back().Base->getType();
1335         return DeclAccessPair();
1336       } else if (P.Access < BestPath->Access) {
1337         BestPath = &P;
1338       }
1339     }
1340 
1341     //   ... unambiguous ...
1342     QualType BaseType = BestPath->back().Base->getType();
1343     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1344       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1345         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1346       return DeclAccessPair();
1347     }
1348 
1349     //   ... [accessible, implied by other rules] base class of E.
1350     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1351                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1352     AS = BestPath->Access;
1353 
1354     ClassWithFields = BaseType->getAsCXXRecordDecl();
1355     S.BuildBasePathArray(Paths, BasePath);
1356   }
1357 
1358   // The above search did not check whether the selected class itself has base
1359   // classes with fields, so check that now.
1360   CXXBasePaths Paths;
1361   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1362     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1363       << (ClassWithFields == RD) << RD << ClassWithFields
1364       << Paths.front().back().Base->getType();
1365     return DeclAccessPair();
1366   }
1367 
1368   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1369 }
1370 
1371 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1372                                      ValueDecl *Src, QualType DecompType,
1373                                      const CXXRecordDecl *OrigRD) {
1374   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1375                             diag::err_incomplete_type))
1376     return true;
1377 
1378   CXXCastPath BasePath;
1379   DeclAccessPair BasePair =
1380       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1381   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1382   if (!RD)
1383     return true;
1384   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1385                                                  DecompType.getQualifiers());
1386 
1387   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1388     unsigned NumFields =
1389         std::count_if(RD->field_begin(), RD->field_end(),
1390                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1391     assert(Bindings.size() != NumFields);
1392     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1393         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1394         << (NumFields < Bindings.size());
1395     return true;
1396   };
1397 
1398   //   all of E's non-static data members shall be [...] well-formed
1399   //   when named as e.name in the context of the structured binding,
1400   //   E shall not have an anonymous union member, ...
1401   unsigned I = 0;
1402   for (auto *FD : RD->fields()) {
1403     if (FD->isUnnamedBitfield())
1404       continue;
1405 
1406     // All the non-static data members are required to be nameable, so they
1407     // must all have names.
1408     if (!FD->getDeclName()) {
1409       if (RD->isLambda()) {
1410         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1411         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1412         return true;
1413       }
1414 
1415       if (FD->isAnonymousStructOrUnion()) {
1416         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1417           << DecompType << FD->getType()->isUnionType();
1418         S.Diag(FD->getLocation(), diag::note_declared_at);
1419         return true;
1420       }
1421 
1422       // FIXME: Are there any other ways we could have an anonymous member?
1423     }
1424 
1425     // We have a real field to bind.
1426     if (I >= Bindings.size())
1427       return DiagnoseBadNumberOfBindings();
1428     auto *B = Bindings[I++];
1429     SourceLocation Loc = B->getLocation();
1430 
1431     // The field must be accessible in the context of the structured binding.
1432     // We already checked that the base class is accessible.
1433     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1434     // const_cast here.
1435     S.CheckStructuredBindingMemberAccess(
1436         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1437         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1438                                      BasePair.getAccess(), FD->getAccess())));
1439 
1440     // Initialize the binding to Src.FD.
1441     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1442     if (E.isInvalid())
1443       return true;
1444     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1445                             VK_LValue, &BasePath);
1446     if (E.isInvalid())
1447       return true;
1448     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1449                                   CXXScopeSpec(), FD,
1450                                   DeclAccessPair::make(FD, FD->getAccess()),
1451                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1452     if (E.isInvalid())
1453       return true;
1454 
1455     // If the type of the member is T, the referenced type is cv T, where cv is
1456     // the cv-qualification of the decomposition expression.
1457     //
1458     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1459     // 'const' to the type of the field.
1460     Qualifiers Q = DecompType.getQualifiers();
1461     if (FD->isMutable())
1462       Q.removeConst();
1463     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1464   }
1465 
1466   if (I != Bindings.size())
1467     return DiagnoseBadNumberOfBindings();
1468 
1469   return false;
1470 }
1471 
1472 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1473   QualType DecompType = DD->getType();
1474 
1475   // If the type of the decomposition is dependent, then so is the type of
1476   // each binding.
1477   if (DecompType->isDependentType()) {
1478     for (auto *B : DD->bindings())
1479       B->setType(Context.DependentTy);
1480     return;
1481   }
1482 
1483   DecompType = DecompType.getNonReferenceType();
1484   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1485 
1486   // C++1z [dcl.decomp]/2:
1487   //   If E is an array type [...]
1488   // As an extension, we also support decomposition of built-in complex and
1489   // vector types.
1490   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1491     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1492       DD->setInvalidDecl();
1493     return;
1494   }
1495   if (auto *VT = DecompType->getAs<VectorType>()) {
1496     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1497       DD->setInvalidDecl();
1498     return;
1499   }
1500   if (auto *CT = DecompType->getAs<ComplexType>()) {
1501     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1502       DD->setInvalidDecl();
1503     return;
1504   }
1505 
1506   // C++1z [dcl.decomp]/3:
1507   //   if the expression std::tuple_size<E>::value is a well-formed integral
1508   //   constant expression, [...]
1509   llvm::APSInt TupleSize(32);
1510   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1511   case IsTupleLike::Error:
1512     DD->setInvalidDecl();
1513     return;
1514 
1515   case IsTupleLike::TupleLike:
1516     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1517       DD->setInvalidDecl();
1518     return;
1519 
1520   case IsTupleLike::NotTupleLike:
1521     break;
1522   }
1523 
1524   // C++1z [dcl.dcl]/8:
1525   //   [E shall be of array or non-union class type]
1526   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1527   if (!RD || RD->isUnion()) {
1528     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1529         << DD << !RD << DecompType;
1530     DD->setInvalidDecl();
1531     return;
1532   }
1533 
1534   // C++1z [dcl.decomp]/4:
1535   //   all of E's non-static data members shall be [...] direct members of
1536   //   E or of the same unambiguous public base class of E, ...
1537   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1538     DD->setInvalidDecl();
1539 }
1540 
1541 /// Merge the exception specifications of two variable declarations.
1542 ///
1543 /// This is called when there's a redeclaration of a VarDecl. The function
1544 /// checks if the redeclaration might have an exception specification and
1545 /// validates compatibility and merges the specs if necessary.
1546 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1547   // Shortcut if exceptions are disabled.
1548   if (!getLangOpts().CXXExceptions)
1549     return;
1550 
1551   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1552          "Should only be called if types are otherwise the same.");
1553 
1554   QualType NewType = New->getType();
1555   QualType OldType = Old->getType();
1556 
1557   // We're only interested in pointers and references to functions, as well
1558   // as pointers to member functions.
1559   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1560     NewType = R->getPointeeType();
1561     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1562   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1563     NewType = P->getPointeeType();
1564     OldType = OldType->castAs<PointerType>()->getPointeeType();
1565   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1566     NewType = M->getPointeeType();
1567     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1568   }
1569 
1570   if (!NewType->isFunctionProtoType())
1571     return;
1572 
1573   // There's lots of special cases for functions. For function pointers, system
1574   // libraries are hopefully not as broken so that we don't need these
1575   // workarounds.
1576   if (CheckEquivalentExceptionSpec(
1577         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1578         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1579     New->setInvalidDecl();
1580   }
1581 }
1582 
1583 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1584 /// function declaration are well-formed according to C++
1585 /// [dcl.fct.default].
1586 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1587   unsigned NumParams = FD->getNumParams();
1588   unsigned ParamIdx = 0;
1589 
1590   // This checking doesn't make sense for explicit specializations; their
1591   // default arguments are determined by the declaration we're specializing,
1592   // not by FD.
1593   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1594     return;
1595   if (auto *FTD = FD->getDescribedFunctionTemplate())
1596     if (FTD->isMemberSpecialization())
1597       return;
1598 
1599   // Find first parameter with a default argument
1600   for (; ParamIdx < NumParams; ++ParamIdx) {
1601     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1602     if (Param->hasDefaultArg())
1603       break;
1604   }
1605 
1606   // C++20 [dcl.fct.default]p4:
1607   //   In a given function declaration, each parameter subsequent to a parameter
1608   //   with a default argument shall have a default argument supplied in this or
1609   //   a previous declaration, unless the parameter was expanded from a
1610   //   parameter pack, or shall be a function parameter pack.
1611   for (; ParamIdx < NumParams; ++ParamIdx) {
1612     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1613     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1614         !(CurrentInstantiationScope &&
1615           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1616       if (Param->isInvalidDecl())
1617         /* We already complained about this parameter. */;
1618       else if (Param->getIdentifier())
1619         Diag(Param->getLocation(),
1620              diag::err_param_default_argument_missing_name)
1621           << Param->getIdentifier();
1622       else
1623         Diag(Param->getLocation(),
1624              diag::err_param_default_argument_missing);
1625     }
1626   }
1627 }
1628 
1629 /// Check that the given type is a literal type. Issue a diagnostic if not,
1630 /// if Kind is Diagnose.
1631 /// \return \c true if a problem has been found (and optionally diagnosed).
1632 template <typename... Ts>
1633 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1634                              SourceLocation Loc, QualType T, unsigned DiagID,
1635                              Ts &&...DiagArgs) {
1636   if (T->isDependentType())
1637     return false;
1638 
1639   switch (Kind) {
1640   case Sema::CheckConstexprKind::Diagnose:
1641     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1642                                       std::forward<Ts>(DiagArgs)...);
1643 
1644   case Sema::CheckConstexprKind::CheckValid:
1645     return !T->isLiteralType(SemaRef.Context);
1646   }
1647 
1648   llvm_unreachable("unknown CheckConstexprKind");
1649 }
1650 
1651 /// Determine whether a destructor cannot be constexpr due to
1652 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1653                                                const CXXDestructorDecl *DD,
1654                                                Sema::CheckConstexprKind Kind) {
1655   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1656     const CXXRecordDecl *RD =
1657         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1658     if (!RD || RD->hasConstexprDestructor())
1659       return true;
1660 
1661     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1662       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1663           << static_cast<int>(DD->getConstexprKind()) << !FD
1664           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1666           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1667     }
1668     return false;
1669   };
1670 
1671   const CXXRecordDecl *RD = DD->getParent();
1672   for (const CXXBaseSpecifier &B : RD->bases())
1673     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1674       return false;
1675   for (const FieldDecl *FD : RD->fields())
1676     if (!Check(FD->getLocation(), FD->getType(), FD))
1677       return false;
1678   return true;
1679 }
1680 
1681 /// Check whether a function's parameter types are all literal types. If so,
1682 /// return true. If not, produce a suitable diagnostic and return false.
1683 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1684                                          const FunctionDecl *FD,
1685                                          Sema::CheckConstexprKind Kind) {
1686   unsigned ArgIndex = 0;
1687   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1688   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1689                                               e = FT->param_type_end();
1690        i != e; ++i, ++ArgIndex) {
1691     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1692     SourceLocation ParamLoc = PD->getLocation();
1693     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1694                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1695                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1696                          FD->isConsteval()))
1697       return false;
1698   }
1699   return true;
1700 }
1701 
1702 /// Check whether a function's return type is a literal type. If so, return
1703 /// true. If not, produce a suitable diagnostic and return false.
1704 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1705                                      Sema::CheckConstexprKind Kind) {
1706   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1707                        diag::err_constexpr_non_literal_return,
1708                        FD->isConsteval()))
1709     return false;
1710   return true;
1711 }
1712 
1713 /// Get diagnostic %select index for tag kind for
1714 /// record diagnostic message.
1715 /// WARNING: Indexes apply to particular diagnostics only!
1716 ///
1717 /// \returns diagnostic %select index.
1718 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1719   switch (Tag) {
1720   case TTK_Struct: return 0;
1721   case TTK_Interface: return 1;
1722   case TTK_Class:  return 2;
1723   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1724   }
1725 }
1726 
1727 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1728                                        Stmt *Body,
1729                                        Sema::CheckConstexprKind Kind);
1730 
1731 // Check whether a function declaration satisfies the requirements of a
1732 // constexpr function definition or a constexpr constructor definition. If so,
1733 // return true. If not, produce appropriate diagnostics (unless asked not to by
1734 // Kind) and return false.
1735 //
1736 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1737 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1738                                             CheckConstexprKind Kind) {
1739   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1740   if (MD && MD->isInstance()) {
1741     // C++11 [dcl.constexpr]p4:
1742     //  The definition of a constexpr constructor shall satisfy the following
1743     //  constraints:
1744     //  - the class shall not have any virtual base classes;
1745     //
1746     // FIXME: This only applies to constructors and destructors, not arbitrary
1747     // member functions.
1748     const CXXRecordDecl *RD = MD->getParent();
1749     if (RD->getNumVBases()) {
1750       if (Kind == CheckConstexprKind::CheckValid)
1751         return false;
1752 
1753       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1754         << isa<CXXConstructorDecl>(NewFD)
1755         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1756       for (const auto &I : RD->vbases())
1757         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1758             << I.getSourceRange();
1759       return false;
1760     }
1761   }
1762 
1763   if (!isa<CXXConstructorDecl>(NewFD)) {
1764     // C++11 [dcl.constexpr]p3:
1765     //  The definition of a constexpr function shall satisfy the following
1766     //  constraints:
1767     // - it shall not be virtual; (removed in C++20)
1768     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1769     if (Method && Method->isVirtual()) {
1770       if (getLangOpts().CPlusPlus20) {
1771         if (Kind == CheckConstexprKind::Diagnose)
1772           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1773       } else {
1774         if (Kind == CheckConstexprKind::CheckValid)
1775           return false;
1776 
1777         Method = Method->getCanonicalDecl();
1778         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1779 
1780         // If it's not obvious why this function is virtual, find an overridden
1781         // function which uses the 'virtual' keyword.
1782         const CXXMethodDecl *WrittenVirtual = Method;
1783         while (!WrittenVirtual->isVirtualAsWritten())
1784           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1785         if (WrittenVirtual != Method)
1786           Diag(WrittenVirtual->getLocation(),
1787                diag::note_overridden_virtual_function);
1788         return false;
1789       }
1790     }
1791 
1792     // - its return type shall be a literal type;
1793     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1794       return false;
1795   }
1796 
1797   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1798     // A destructor can be constexpr only if the defaulted destructor could be;
1799     // we don't need to check the members and bases if we already know they all
1800     // have constexpr destructors.
1801     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1802       if (Kind == CheckConstexprKind::CheckValid)
1803         return false;
1804       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1805         return false;
1806     }
1807   }
1808 
1809   // - each of its parameter types shall be a literal type;
1810   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1811     return false;
1812 
1813   Stmt *Body = NewFD->getBody();
1814   assert(Body &&
1815          "CheckConstexprFunctionDefinition called on function with no body");
1816   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1817 }
1818 
1819 /// Check the given declaration statement is legal within a constexpr function
1820 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1821 ///
1822 /// \return true if the body is OK (maybe only as an extension), false if we
1823 ///         have diagnosed a problem.
1824 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1825                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1826                                    Sema::CheckConstexprKind Kind) {
1827   // C++11 [dcl.constexpr]p3 and p4:
1828   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1829   //  contain only
1830   for (const auto *DclIt : DS->decls()) {
1831     switch (DclIt->getKind()) {
1832     case Decl::StaticAssert:
1833     case Decl::Using:
1834     case Decl::UsingShadow:
1835     case Decl::UsingDirective:
1836     case Decl::UnresolvedUsingTypename:
1837     case Decl::UnresolvedUsingValue:
1838       //   - static_assert-declarations
1839       //   - using-declarations,
1840       //   - using-directives,
1841       continue;
1842 
1843     case Decl::Typedef:
1844     case Decl::TypeAlias: {
1845       //   - typedef declarations and alias-declarations that do not define
1846       //     classes or enumerations,
1847       const auto *TN = cast<TypedefNameDecl>(DclIt);
1848       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849         // Don't allow variably-modified types in constexpr functions.
1850         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853             << TL.getSourceRange() << TL.getType()
1854             << isa<CXXConstructorDecl>(Dcl);
1855         }
1856         return false;
1857       }
1858       continue;
1859     }
1860 
1861     case Decl::Enum:
1862     case Decl::CXXRecord:
1863       // C++1y allows types to be defined, not just declared.
1864       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866           SemaRef.Diag(DS->getBeginLoc(),
1867                        SemaRef.getLangOpts().CPlusPlus14
1868                            ? diag::warn_cxx11_compat_constexpr_type_definition
1869                            : diag::ext_constexpr_type_definition)
1870               << isa<CXXConstructorDecl>(Dcl);
1871         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872           return false;
1873         }
1874       }
1875       continue;
1876 
1877     case Decl::EnumConstant:
1878     case Decl::IndirectField:
1879     case Decl::ParmVar:
1880       // These can only appear with other declarations which are banned in
1881       // C++11 and permitted in C++1y, so ignore them.
1882       continue;
1883 
1884     case Decl::Var:
1885     case Decl::Decomposition: {
1886       // C++1y [dcl.constexpr]p3 allows anything except:
1887       //   a definition of a variable of non-literal type or of static or
1888       //   thread storage duration or [before C++2a] for which no
1889       //   initialization is performed.
1890       const auto *VD = cast<VarDecl>(DclIt);
1891       if (VD->isThisDeclarationADefinition()) {
1892         if (VD->isStaticLocal()) {
1893           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894             SemaRef.Diag(VD->getLocation(),
1895                          diag::err_constexpr_local_var_static)
1896               << isa<CXXConstructorDecl>(Dcl)
1897               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1898           }
1899           return false;
1900         }
1901         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1902                              diag::err_constexpr_local_var_non_literal_type,
1903                              isa<CXXConstructorDecl>(Dcl)))
1904           return false;
1905         if (!VD->getType()->isDependentType() &&
1906             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1907           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1908             SemaRef.Diag(
1909                 VD->getLocation(),
1910                 SemaRef.getLangOpts().CPlusPlus20
1911                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1912                     : diag::ext_constexpr_local_var_no_init)
1913                 << isa<CXXConstructorDecl>(Dcl);
1914           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1915             return false;
1916           }
1917           continue;
1918         }
1919       }
1920       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1921         SemaRef.Diag(VD->getLocation(),
1922                      SemaRef.getLangOpts().CPlusPlus14
1923                       ? diag::warn_cxx11_compat_constexpr_local_var
1924                       : diag::ext_constexpr_local_var)
1925           << isa<CXXConstructorDecl>(Dcl);
1926       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1927         return false;
1928       }
1929       continue;
1930     }
1931 
1932     case Decl::NamespaceAlias:
1933     case Decl::Function:
1934       // These are disallowed in C++11 and permitted in C++1y. Allow them
1935       // everywhere as an extension.
1936       if (!Cxx1yLoc.isValid())
1937         Cxx1yLoc = DS->getBeginLoc();
1938       continue;
1939 
1940     default:
1941       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1942         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1943             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1944       }
1945       return false;
1946     }
1947   }
1948 
1949   return true;
1950 }
1951 
1952 /// Check that the given field is initialized within a constexpr constructor.
1953 ///
1954 /// \param Dcl The constexpr constructor being checked.
1955 /// \param Field The field being checked. This may be a member of an anonymous
1956 ///        struct or union nested within the class being checked.
1957 /// \param Inits All declarations, including anonymous struct/union members and
1958 ///        indirect members, for which any initialization was provided.
1959 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1960 ///        multiple notes for different members to the same error.
1961 /// \param Kind Whether we're diagnosing a constructor as written or determining
1962 ///        whether the formal requirements are satisfied.
1963 /// \return \c false if we're checking for validity and the constructor does
1964 ///         not satisfy the requirements on a constexpr constructor.
1965 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1966                                           const FunctionDecl *Dcl,
1967                                           FieldDecl *Field,
1968                                           llvm::SmallSet<Decl*, 16> &Inits,
1969                                           bool &Diagnosed,
1970                                           Sema::CheckConstexprKind Kind) {
1971   // In C++20 onwards, there's nothing to check for validity.
1972   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1973       SemaRef.getLangOpts().CPlusPlus20)
1974     return true;
1975 
1976   if (Field->isInvalidDecl())
1977     return true;
1978 
1979   if (Field->isUnnamedBitfield())
1980     return true;
1981 
1982   // Anonymous unions with no variant members and empty anonymous structs do not
1983   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1984   // indirect fields don't need initializing.
1985   if (Field->isAnonymousStructOrUnion() &&
1986       (Field->getType()->isUnionType()
1987            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1988            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1989     return true;
1990 
1991   if (!Inits.count(Field)) {
1992     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1993       if (!Diagnosed) {
1994         SemaRef.Diag(Dcl->getLocation(),
1995                      SemaRef.getLangOpts().CPlusPlus20
1996                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1997                          : diag::ext_constexpr_ctor_missing_init);
1998         Diagnosed = true;
1999       }
2000       SemaRef.Diag(Field->getLocation(),
2001                    diag::note_constexpr_ctor_missing_init);
2002     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2003       return false;
2004     }
2005   } else if (Field->isAnonymousStructOrUnion()) {
2006     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2007     for (auto *I : RD->fields())
2008       // If an anonymous union contains an anonymous struct of which any member
2009       // is initialized, all members must be initialized.
2010       if (!RD->isUnion() || Inits.count(I))
2011         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2012                                            Kind))
2013           return false;
2014   }
2015   return true;
2016 }
2017 
2018 /// Check the provided statement is allowed in a constexpr function
2019 /// definition.
2020 static bool
2021 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2022                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2023                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2024                            Sema::CheckConstexprKind Kind) {
2025   // - its function-body shall be [...] a compound-statement that contains only
2026   switch (S->getStmtClass()) {
2027   case Stmt::NullStmtClass:
2028     //   - null statements,
2029     return true;
2030 
2031   case Stmt::DeclStmtClass:
2032     //   - static_assert-declarations
2033     //   - using-declarations,
2034     //   - using-directives,
2035     //   - typedef declarations and alias-declarations that do not define
2036     //     classes or enumerations,
2037     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2038       return false;
2039     return true;
2040 
2041   case Stmt::ReturnStmtClass:
2042     //   - and exactly one return statement;
2043     if (isa<CXXConstructorDecl>(Dcl)) {
2044       // C++1y allows return statements in constexpr constructors.
2045       if (!Cxx1yLoc.isValid())
2046         Cxx1yLoc = S->getBeginLoc();
2047       return true;
2048     }
2049 
2050     ReturnStmts.push_back(S->getBeginLoc());
2051     return true;
2052 
2053   case Stmt::CompoundStmtClass: {
2054     // C++1y allows compound-statements.
2055     if (!Cxx1yLoc.isValid())
2056       Cxx1yLoc = S->getBeginLoc();
2057 
2058     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2059     for (auto *BodyIt : CompStmt->body()) {
2060       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2061                                       Cxx1yLoc, Cxx2aLoc, Kind))
2062         return false;
2063     }
2064     return true;
2065   }
2066 
2067   case Stmt::AttributedStmtClass:
2068     if (!Cxx1yLoc.isValid())
2069       Cxx1yLoc = S->getBeginLoc();
2070     return true;
2071 
2072   case Stmt::IfStmtClass: {
2073     // C++1y allows if-statements.
2074     if (!Cxx1yLoc.isValid())
2075       Cxx1yLoc = S->getBeginLoc();
2076 
2077     IfStmt *If = cast<IfStmt>(S);
2078     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2079                                     Cxx1yLoc, Cxx2aLoc, Kind))
2080       return false;
2081     if (If->getElse() &&
2082         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2083                                     Cxx1yLoc, Cxx2aLoc, Kind))
2084       return false;
2085     return true;
2086   }
2087 
2088   case Stmt::WhileStmtClass:
2089   case Stmt::DoStmtClass:
2090   case Stmt::ForStmtClass:
2091   case Stmt::CXXForRangeStmtClass:
2092   case Stmt::ContinueStmtClass:
2093     // C++1y allows all of these. We don't allow them as extensions in C++11,
2094     // because they don't make sense without variable mutation.
2095     if (!SemaRef.getLangOpts().CPlusPlus14)
2096       break;
2097     if (!Cxx1yLoc.isValid())
2098       Cxx1yLoc = S->getBeginLoc();
2099     for (Stmt *SubStmt : S->children())
2100       if (SubStmt &&
2101           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2102                                       Cxx1yLoc, Cxx2aLoc, Kind))
2103         return false;
2104     return true;
2105 
2106   case Stmt::SwitchStmtClass:
2107   case Stmt::CaseStmtClass:
2108   case Stmt::DefaultStmtClass:
2109   case Stmt::BreakStmtClass:
2110     // C++1y allows switch-statements, and since they don't need variable
2111     // mutation, we can reasonably allow them in C++11 as an extension.
2112     if (!Cxx1yLoc.isValid())
2113       Cxx1yLoc = S->getBeginLoc();
2114     for (Stmt *SubStmt : S->children())
2115       if (SubStmt &&
2116           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2117                                       Cxx1yLoc, Cxx2aLoc, Kind))
2118         return false;
2119     return true;
2120 
2121   case Stmt::GCCAsmStmtClass:
2122   case Stmt::MSAsmStmtClass:
2123     // C++2a allows inline assembly statements.
2124   case Stmt::CXXTryStmtClass:
2125     if (Cxx2aLoc.isInvalid())
2126       Cxx2aLoc = S->getBeginLoc();
2127     for (Stmt *SubStmt : S->children()) {
2128       if (SubStmt &&
2129           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2130                                       Cxx1yLoc, Cxx2aLoc, Kind))
2131         return false;
2132     }
2133     return true;
2134 
2135   case Stmt::CXXCatchStmtClass:
2136     // Do not bother checking the language mode (already covered by the
2137     // try block check).
2138     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2139                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2140                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2141       return false;
2142     return true;
2143 
2144   default:
2145     if (!isa<Expr>(S))
2146       break;
2147 
2148     // C++1y allows expression-statements.
2149     if (!Cxx1yLoc.isValid())
2150       Cxx1yLoc = S->getBeginLoc();
2151     return true;
2152   }
2153 
2154   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2155     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2156         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2157   }
2158   return false;
2159 }
2160 
2161 /// Check the body for the given constexpr function declaration only contains
2162 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2163 ///
2164 /// \return true if the body is OK, false if we have found or diagnosed a
2165 /// problem.
2166 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2167                                        Stmt *Body,
2168                                        Sema::CheckConstexprKind Kind) {
2169   SmallVector<SourceLocation, 4> ReturnStmts;
2170 
2171   if (isa<CXXTryStmt>(Body)) {
2172     // C++11 [dcl.constexpr]p3:
2173     //  The definition of a constexpr function shall satisfy the following
2174     //  constraints: [...]
2175     // - its function-body shall be = delete, = default, or a
2176     //   compound-statement
2177     //
2178     // C++11 [dcl.constexpr]p4:
2179     //  In the definition of a constexpr constructor, [...]
2180     // - its function-body shall not be a function-try-block;
2181     //
2182     // This restriction is lifted in C++2a, as long as inner statements also
2183     // apply the general constexpr rules.
2184     switch (Kind) {
2185     case Sema::CheckConstexprKind::CheckValid:
2186       if (!SemaRef.getLangOpts().CPlusPlus20)
2187         return false;
2188       break;
2189 
2190     case Sema::CheckConstexprKind::Diagnose:
2191       SemaRef.Diag(Body->getBeginLoc(),
2192            !SemaRef.getLangOpts().CPlusPlus20
2193                ? diag::ext_constexpr_function_try_block_cxx20
2194                : diag::warn_cxx17_compat_constexpr_function_try_block)
2195           << isa<CXXConstructorDecl>(Dcl);
2196       break;
2197     }
2198   }
2199 
2200   // - its function-body shall be [...] a compound-statement that contains only
2201   //   [... list of cases ...]
2202   //
2203   // Note that walking the children here is enough to properly check for
2204   // CompoundStmt and CXXTryStmt body.
2205   SourceLocation Cxx1yLoc, Cxx2aLoc;
2206   for (Stmt *SubStmt : Body->children()) {
2207     if (SubStmt &&
2208         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2209                                     Cxx1yLoc, Cxx2aLoc, Kind))
2210       return false;
2211   }
2212 
2213   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2214     // If this is only valid as an extension, report that we don't satisfy the
2215     // constraints of the current language.
2216     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2217         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2218       return false;
2219   } else if (Cxx2aLoc.isValid()) {
2220     SemaRef.Diag(Cxx2aLoc,
2221          SemaRef.getLangOpts().CPlusPlus20
2222            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2223            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2224       << isa<CXXConstructorDecl>(Dcl);
2225   } else if (Cxx1yLoc.isValid()) {
2226     SemaRef.Diag(Cxx1yLoc,
2227          SemaRef.getLangOpts().CPlusPlus14
2228            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2229            : diag::ext_constexpr_body_invalid_stmt)
2230       << isa<CXXConstructorDecl>(Dcl);
2231   }
2232 
2233   if (const CXXConstructorDecl *Constructor
2234         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2235     const CXXRecordDecl *RD = Constructor->getParent();
2236     // DR1359:
2237     // - every non-variant non-static data member and base class sub-object
2238     //   shall be initialized;
2239     // DR1460:
2240     // - if the class is a union having variant members, exactly one of them
2241     //   shall be initialized;
2242     if (RD->isUnion()) {
2243       if (Constructor->getNumCtorInitializers() == 0 &&
2244           RD->hasVariantMembers()) {
2245         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2246           SemaRef.Diag(
2247               Dcl->getLocation(),
2248               SemaRef.getLangOpts().CPlusPlus20
2249                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2250                   : diag::ext_constexpr_union_ctor_no_init);
2251         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2252           return false;
2253         }
2254       }
2255     } else if (!Constructor->isDependentContext() &&
2256                !Constructor->isDelegatingConstructor()) {
2257       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2258 
2259       // Skip detailed checking if we have enough initializers, and we would
2260       // allow at most one initializer per member.
2261       bool AnyAnonStructUnionMembers = false;
2262       unsigned Fields = 0;
2263       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2264            E = RD->field_end(); I != E; ++I, ++Fields) {
2265         if (I->isAnonymousStructOrUnion()) {
2266           AnyAnonStructUnionMembers = true;
2267           break;
2268         }
2269       }
2270       // DR1460:
2271       // - if the class is a union-like class, but is not a union, for each of
2272       //   its anonymous union members having variant members, exactly one of
2273       //   them shall be initialized;
2274       if (AnyAnonStructUnionMembers ||
2275           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2276         // Check initialization of non-static data members. Base classes are
2277         // always initialized so do not need to be checked. Dependent bases
2278         // might not have initializers in the member initializer list.
2279         llvm::SmallSet<Decl*, 16> Inits;
2280         for (const auto *I: Constructor->inits()) {
2281           if (FieldDecl *FD = I->getMember())
2282             Inits.insert(FD);
2283           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2284             Inits.insert(ID->chain_begin(), ID->chain_end());
2285         }
2286 
2287         bool Diagnosed = false;
2288         for (auto *I : RD->fields())
2289           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2290                                              Kind))
2291             return false;
2292       }
2293     }
2294   } else {
2295     if (ReturnStmts.empty()) {
2296       // C++1y doesn't require constexpr functions to contain a 'return'
2297       // statement. We still do, unless the return type might be void, because
2298       // otherwise if there's no return statement, the function cannot
2299       // be used in a core constant expression.
2300       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2301                 (Dcl->getReturnType()->isVoidType() ||
2302                  Dcl->getReturnType()->isDependentType());
2303       switch (Kind) {
2304       case Sema::CheckConstexprKind::Diagnose:
2305         SemaRef.Diag(Dcl->getLocation(),
2306                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2307                         : diag::err_constexpr_body_no_return)
2308             << Dcl->isConsteval();
2309         if (!OK)
2310           return false;
2311         break;
2312 
2313       case Sema::CheckConstexprKind::CheckValid:
2314         // The formal requirements don't include this rule in C++14, even
2315         // though the "must be able to produce a constant expression" rules
2316         // still imply it in some cases.
2317         if (!SemaRef.getLangOpts().CPlusPlus14)
2318           return false;
2319         break;
2320       }
2321     } else if (ReturnStmts.size() > 1) {
2322       switch (Kind) {
2323       case Sema::CheckConstexprKind::Diagnose:
2324         SemaRef.Diag(
2325             ReturnStmts.back(),
2326             SemaRef.getLangOpts().CPlusPlus14
2327                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2328                 : diag::ext_constexpr_body_multiple_return);
2329         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2330           SemaRef.Diag(ReturnStmts[I],
2331                        diag::note_constexpr_body_previous_return);
2332         break;
2333 
2334       case Sema::CheckConstexprKind::CheckValid:
2335         if (!SemaRef.getLangOpts().CPlusPlus14)
2336           return false;
2337         break;
2338       }
2339     }
2340   }
2341 
2342   // C++11 [dcl.constexpr]p5:
2343   //   if no function argument values exist such that the function invocation
2344   //   substitution would produce a constant expression, the program is
2345   //   ill-formed; no diagnostic required.
2346   // C++11 [dcl.constexpr]p3:
2347   //   - every constructor call and implicit conversion used in initializing the
2348   //     return value shall be one of those allowed in a constant expression.
2349   // C++11 [dcl.constexpr]p4:
2350   //   - every constructor involved in initializing non-static data members and
2351   //     base class sub-objects shall be a constexpr constructor.
2352   //
2353   // Note that this rule is distinct from the "requirements for a constexpr
2354   // function", so is not checked in CheckValid mode.
2355   SmallVector<PartialDiagnosticAt, 8> Diags;
2356   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2357       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2358     SemaRef.Diag(Dcl->getLocation(),
2359                  diag::ext_constexpr_function_never_constant_expr)
2360         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2361     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2362       SemaRef.Diag(Diags[I].first, Diags[I].second);
2363     // Don't return false here: we allow this for compatibility in
2364     // system headers.
2365   }
2366 
2367   return true;
2368 }
2369 
2370 /// Get the class that is directly named by the current context. This is the
2371 /// class for which an unqualified-id in this scope could name a constructor
2372 /// or destructor.
2373 ///
2374 /// If the scope specifier denotes a class, this will be that class.
2375 /// If the scope specifier is empty, this will be the class whose
2376 /// member-specification we are currently within. Otherwise, there
2377 /// is no such class.
2378 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2379   assert(getLangOpts().CPlusPlus && "No class names in C!");
2380 
2381   if (SS && SS->isInvalid())
2382     return nullptr;
2383 
2384   if (SS && SS->isNotEmpty()) {
2385     DeclContext *DC = computeDeclContext(*SS, true);
2386     return dyn_cast_or_null<CXXRecordDecl>(DC);
2387   }
2388 
2389   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2390 }
2391 
2392 /// isCurrentClassName - Determine whether the identifier II is the
2393 /// name of the class type currently being defined. In the case of
2394 /// nested classes, this will only return true if II is the name of
2395 /// the innermost class.
2396 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2397                               const CXXScopeSpec *SS) {
2398   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2399   return CurDecl && &II == CurDecl->getIdentifier();
2400 }
2401 
2402 /// Determine whether the identifier II is a typo for the name of
2403 /// the class type currently being defined. If so, update it to the identifier
2404 /// that should have been used.
2405 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2406   assert(getLangOpts().CPlusPlus && "No class names in C!");
2407 
2408   if (!getLangOpts().SpellChecking)
2409     return false;
2410 
2411   CXXRecordDecl *CurDecl;
2412   if (SS && SS->isSet() && !SS->isInvalid()) {
2413     DeclContext *DC = computeDeclContext(*SS, true);
2414     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2415   } else
2416     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2417 
2418   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2419       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2420           < II->getLength()) {
2421     II = CurDecl->getIdentifier();
2422     return true;
2423   }
2424 
2425   return false;
2426 }
2427 
2428 /// Determine whether the given class is a base class of the given
2429 /// class, including looking at dependent bases.
2430 static bool findCircularInheritance(const CXXRecordDecl *Class,
2431                                     const CXXRecordDecl *Current) {
2432   SmallVector<const CXXRecordDecl*, 8> Queue;
2433 
2434   Class = Class->getCanonicalDecl();
2435   while (true) {
2436     for (const auto &I : Current->bases()) {
2437       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2438       if (!Base)
2439         continue;
2440 
2441       Base = Base->getDefinition();
2442       if (!Base)
2443         continue;
2444 
2445       if (Base->getCanonicalDecl() == Class)
2446         return true;
2447 
2448       Queue.push_back(Base);
2449     }
2450 
2451     if (Queue.empty())
2452       return false;
2453 
2454     Current = Queue.pop_back_val();
2455   }
2456 
2457   return false;
2458 }
2459 
2460 /// Check the validity of a C++ base class specifier.
2461 ///
2462 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2463 /// and returns NULL otherwise.
2464 CXXBaseSpecifier *
2465 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2466                          SourceRange SpecifierRange,
2467                          bool Virtual, AccessSpecifier Access,
2468                          TypeSourceInfo *TInfo,
2469                          SourceLocation EllipsisLoc) {
2470   QualType BaseType = TInfo->getType();
2471   if (BaseType->containsErrors()) {
2472     // Already emitted a diagnostic when parsing the error type.
2473     return nullptr;
2474   }
2475   // C++ [class.union]p1:
2476   //   A union shall not have base classes.
2477   if (Class->isUnion()) {
2478     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2479       << SpecifierRange;
2480     return nullptr;
2481   }
2482 
2483   if (EllipsisLoc.isValid() &&
2484       !TInfo->getType()->containsUnexpandedParameterPack()) {
2485     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2486       << TInfo->getTypeLoc().getSourceRange();
2487     EllipsisLoc = SourceLocation();
2488   }
2489 
2490   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2491 
2492   if (BaseType->isDependentType()) {
2493     // Make sure that we don't have circular inheritance among our dependent
2494     // bases. For non-dependent bases, the check for completeness below handles
2495     // this.
2496     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2497       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2498           ((BaseDecl = BaseDecl->getDefinition()) &&
2499            findCircularInheritance(Class, BaseDecl))) {
2500         Diag(BaseLoc, diag::err_circular_inheritance)
2501           << BaseType << Context.getTypeDeclType(Class);
2502 
2503         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2504           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2505             << BaseType;
2506 
2507         return nullptr;
2508       }
2509     }
2510 
2511     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2512                                           Class->getTagKind() == TTK_Class,
2513                                           Access, TInfo, EllipsisLoc);
2514   }
2515 
2516   // Base specifiers must be record types.
2517   if (!BaseType->isRecordType()) {
2518     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2519     return nullptr;
2520   }
2521 
2522   // C++ [class.union]p1:
2523   //   A union shall not be used as a base class.
2524   if (BaseType->isUnionType()) {
2525     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2526     return nullptr;
2527   }
2528 
2529   // For the MS ABI, propagate DLL attributes to base class templates.
2530   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2531     if (Attr *ClassAttr = getDLLAttr(Class)) {
2532       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2533               BaseType->getAsCXXRecordDecl())) {
2534         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2535                                             BaseLoc);
2536       }
2537     }
2538   }
2539 
2540   // C++ [class.derived]p2:
2541   //   The class-name in a base-specifier shall not be an incompletely
2542   //   defined class.
2543   if (RequireCompleteType(BaseLoc, BaseType,
2544                           diag::err_incomplete_base_class, SpecifierRange)) {
2545     Class->setInvalidDecl();
2546     return nullptr;
2547   }
2548 
2549   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2550   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2551   assert(BaseDecl && "Record type has no declaration");
2552   BaseDecl = BaseDecl->getDefinition();
2553   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2554   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2555   assert(CXXBaseDecl && "Base type is not a C++ type");
2556 
2557   // Microsoft docs say:
2558   // "If a base-class has a code_seg attribute, derived classes must have the
2559   // same attribute."
2560   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2561   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2562   if ((DerivedCSA || BaseCSA) &&
2563       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2564     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2565     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2566       << CXXBaseDecl;
2567     return nullptr;
2568   }
2569 
2570   // A class which contains a flexible array member is not suitable for use as a
2571   // base class:
2572   //   - If the layout determines that a base comes before another base,
2573   //     the flexible array member would index into the subsequent base.
2574   //   - If the layout determines that base comes before the derived class,
2575   //     the flexible array member would index into the derived class.
2576   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2577     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2578       << CXXBaseDecl->getDeclName();
2579     return nullptr;
2580   }
2581 
2582   // C++ [class]p3:
2583   //   If a class is marked final and it appears as a base-type-specifier in
2584   //   base-clause, the program is ill-formed.
2585   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2586     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2587       << CXXBaseDecl->getDeclName()
2588       << FA->isSpelledAsSealed();
2589     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2590         << CXXBaseDecl->getDeclName() << FA->getRange();
2591     return nullptr;
2592   }
2593 
2594   if (BaseDecl->isInvalidDecl())
2595     Class->setInvalidDecl();
2596 
2597   // Create the base specifier.
2598   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2599                                         Class->getTagKind() == TTK_Class,
2600                                         Access, TInfo, EllipsisLoc);
2601 }
2602 
2603 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2604 /// one entry in the base class list of a class specifier, for
2605 /// example:
2606 ///    class foo : public bar, virtual private baz {
2607 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2608 BaseResult
2609 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2610                          ParsedAttributes &Attributes,
2611                          bool Virtual, AccessSpecifier Access,
2612                          ParsedType basetype, SourceLocation BaseLoc,
2613                          SourceLocation EllipsisLoc) {
2614   if (!classdecl)
2615     return true;
2616 
2617   AdjustDeclIfTemplate(classdecl);
2618   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2619   if (!Class)
2620     return true;
2621 
2622   // We haven't yet attached the base specifiers.
2623   Class->setIsParsingBaseSpecifiers();
2624 
2625   // We do not support any C++11 attributes on base-specifiers yet.
2626   // Diagnose any attributes we see.
2627   for (const ParsedAttr &AL : Attributes) {
2628     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2629       continue;
2630     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2631                           ? (unsigned)diag::warn_unknown_attribute_ignored
2632                           : (unsigned)diag::err_base_specifier_attribute)
2633         << AL << AL.getRange();
2634   }
2635 
2636   TypeSourceInfo *TInfo = nullptr;
2637   GetTypeFromParser(basetype, &TInfo);
2638 
2639   if (EllipsisLoc.isInvalid() &&
2640       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2641                                       UPPC_BaseType))
2642     return true;
2643 
2644   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2645                                                       Virtual, Access, TInfo,
2646                                                       EllipsisLoc))
2647     return BaseSpec;
2648   else
2649     Class->setInvalidDecl();
2650 
2651   return true;
2652 }
2653 
2654 /// Use small set to collect indirect bases.  As this is only used
2655 /// locally, there's no need to abstract the small size parameter.
2656 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2657 
2658 /// Recursively add the bases of Type.  Don't add Type itself.
2659 static void
2660 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2661                   const QualType &Type)
2662 {
2663   // Even though the incoming type is a base, it might not be
2664   // a class -- it could be a template parm, for instance.
2665   if (auto Rec = Type->getAs<RecordType>()) {
2666     auto Decl = Rec->getAsCXXRecordDecl();
2667 
2668     // Iterate over its bases.
2669     for (const auto &BaseSpec : Decl->bases()) {
2670       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2671         .getUnqualifiedType();
2672       if (Set.insert(Base).second)
2673         // If we've not already seen it, recurse.
2674         NoteIndirectBases(Context, Set, Base);
2675     }
2676   }
2677 }
2678 
2679 /// Performs the actual work of attaching the given base class
2680 /// specifiers to a C++ class.
2681 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2682                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2683  if (Bases.empty())
2684     return false;
2685 
2686   // Used to keep track of which base types we have already seen, so
2687   // that we can properly diagnose redundant direct base types. Note
2688   // that the key is always the unqualified canonical type of the base
2689   // class.
2690   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2691 
2692   // Used to track indirect bases so we can see if a direct base is
2693   // ambiguous.
2694   IndirectBaseSet IndirectBaseTypes;
2695 
2696   // Copy non-redundant base specifiers into permanent storage.
2697   unsigned NumGoodBases = 0;
2698   bool Invalid = false;
2699   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2700     QualType NewBaseType
2701       = Context.getCanonicalType(Bases[idx]->getType());
2702     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2703 
2704     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2705     if (KnownBase) {
2706       // C++ [class.mi]p3:
2707       //   A class shall not be specified as a direct base class of a
2708       //   derived class more than once.
2709       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2710           << KnownBase->getType() << Bases[idx]->getSourceRange();
2711 
2712       // Delete the duplicate base class specifier; we're going to
2713       // overwrite its pointer later.
2714       Context.Deallocate(Bases[idx]);
2715 
2716       Invalid = true;
2717     } else {
2718       // Okay, add this new base class.
2719       KnownBase = Bases[idx];
2720       Bases[NumGoodBases++] = Bases[idx];
2721 
2722       // Note this base's direct & indirect bases, if there could be ambiguity.
2723       if (Bases.size() > 1)
2724         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2725 
2726       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2727         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2728         if (Class->isInterface() &&
2729               (!RD->isInterfaceLike() ||
2730                KnownBase->getAccessSpecifier() != AS_public)) {
2731           // The Microsoft extension __interface does not permit bases that
2732           // are not themselves public interfaces.
2733           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2734               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2735               << RD->getSourceRange();
2736           Invalid = true;
2737         }
2738         if (RD->hasAttr<WeakAttr>())
2739           Class->addAttr(WeakAttr::CreateImplicit(Context));
2740       }
2741     }
2742   }
2743 
2744   // Attach the remaining base class specifiers to the derived class.
2745   Class->setBases(Bases.data(), NumGoodBases);
2746 
2747   // Check that the only base classes that are duplicate are virtual.
2748   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2749     // Check whether this direct base is inaccessible due to ambiguity.
2750     QualType BaseType = Bases[idx]->getType();
2751 
2752     // Skip all dependent types in templates being used as base specifiers.
2753     // Checks below assume that the base specifier is a CXXRecord.
2754     if (BaseType->isDependentType())
2755       continue;
2756 
2757     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2758       .getUnqualifiedType();
2759 
2760     if (IndirectBaseTypes.count(CanonicalBase)) {
2761       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2762                          /*DetectVirtual=*/true);
2763       bool found
2764         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2765       assert(found);
2766       (void)found;
2767 
2768       if (Paths.isAmbiguous(CanonicalBase))
2769         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2770             << BaseType << getAmbiguousPathsDisplayString(Paths)
2771             << Bases[idx]->getSourceRange();
2772       else
2773         assert(Bases[idx]->isVirtual());
2774     }
2775 
2776     // Delete the base class specifier, since its data has been copied
2777     // into the CXXRecordDecl.
2778     Context.Deallocate(Bases[idx]);
2779   }
2780 
2781   return Invalid;
2782 }
2783 
2784 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2785 /// class, after checking whether there are any duplicate base
2786 /// classes.
2787 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2788                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2789   if (!ClassDecl || Bases.empty())
2790     return;
2791 
2792   AdjustDeclIfTemplate(ClassDecl);
2793   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2794 }
2795 
2796 /// Determine whether the type \p Derived is a C++ class that is
2797 /// derived from the type \p Base.
2798 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2799   if (!getLangOpts().CPlusPlus)
2800     return false;
2801 
2802   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2803   if (!DerivedRD)
2804     return false;
2805 
2806   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2807   if (!BaseRD)
2808     return false;
2809 
2810   // If either the base or the derived type is invalid, don't try to
2811   // check whether one is derived from the other.
2812   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2813     return false;
2814 
2815   // FIXME: In a modules build, do we need the entire path to be visible for us
2816   // to be able to use the inheritance relationship?
2817   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2818     return false;
2819 
2820   return DerivedRD->isDerivedFrom(BaseRD);
2821 }
2822 
2823 /// Determine whether the type \p Derived is a C++ class that is
2824 /// derived from the type \p Base.
2825 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2826                          CXXBasePaths &Paths) {
2827   if (!getLangOpts().CPlusPlus)
2828     return false;
2829 
2830   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2831   if (!DerivedRD)
2832     return false;
2833 
2834   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2835   if (!BaseRD)
2836     return false;
2837 
2838   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2839     return false;
2840 
2841   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2842 }
2843 
2844 static void BuildBasePathArray(const CXXBasePath &Path,
2845                                CXXCastPath &BasePathArray) {
2846   // We first go backward and check if we have a virtual base.
2847   // FIXME: It would be better if CXXBasePath had the base specifier for
2848   // the nearest virtual base.
2849   unsigned Start = 0;
2850   for (unsigned I = Path.size(); I != 0; --I) {
2851     if (Path[I - 1].Base->isVirtual()) {
2852       Start = I - 1;
2853       break;
2854     }
2855   }
2856 
2857   // Now add all bases.
2858   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2859     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2860 }
2861 
2862 
2863 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2864                               CXXCastPath &BasePathArray) {
2865   assert(BasePathArray.empty() && "Base path array must be empty!");
2866   assert(Paths.isRecordingPaths() && "Must record paths!");
2867   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2868 }
2869 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2870 /// conversion (where Derived and Base are class types) is
2871 /// well-formed, meaning that the conversion is unambiguous (and
2872 /// that all of the base classes are accessible). Returns true
2873 /// and emits a diagnostic if the code is ill-formed, returns false
2874 /// otherwise. Loc is the location where this routine should point to
2875 /// if there is an error, and Range is the source range to highlight
2876 /// if there is an error.
2877 ///
2878 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2879 /// diagnostic for the respective type of error will be suppressed, but the
2880 /// check for ill-formed code will still be performed.
2881 bool
2882 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2883                                    unsigned InaccessibleBaseID,
2884                                    unsigned AmbiguousBaseConvID,
2885                                    SourceLocation Loc, SourceRange Range,
2886                                    DeclarationName Name,
2887                                    CXXCastPath *BasePath,
2888                                    bool IgnoreAccess) {
2889   // First, determine whether the path from Derived to Base is
2890   // ambiguous. This is slightly more expensive than checking whether
2891   // the Derived to Base conversion exists, because here we need to
2892   // explore multiple paths to determine if there is an ambiguity.
2893   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2894                      /*DetectVirtual=*/false);
2895   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2896   if (!DerivationOkay)
2897     return true;
2898 
2899   const CXXBasePath *Path = nullptr;
2900   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2901     Path = &Paths.front();
2902 
2903   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2904   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2905   // user to access such bases.
2906   if (!Path && getLangOpts().MSVCCompat) {
2907     for (const CXXBasePath &PossiblePath : Paths) {
2908       if (PossiblePath.size() == 1) {
2909         Path = &PossiblePath;
2910         if (AmbiguousBaseConvID)
2911           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2912               << Base << Derived << Range;
2913         break;
2914       }
2915     }
2916   }
2917 
2918   if (Path) {
2919     if (!IgnoreAccess) {
2920       // Check that the base class can be accessed.
2921       switch (
2922           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2923       case AR_inaccessible:
2924         return true;
2925       case AR_accessible:
2926       case AR_dependent:
2927       case AR_delayed:
2928         break;
2929       }
2930     }
2931 
2932     // Build a base path if necessary.
2933     if (BasePath)
2934       ::BuildBasePathArray(*Path, *BasePath);
2935     return false;
2936   }
2937 
2938   if (AmbiguousBaseConvID) {
2939     // We know that the derived-to-base conversion is ambiguous, and
2940     // we're going to produce a diagnostic. Perform the derived-to-base
2941     // search just one more time to compute all of the possible paths so
2942     // that we can print them out. This is more expensive than any of
2943     // the previous derived-to-base checks we've done, but at this point
2944     // performance isn't as much of an issue.
2945     Paths.clear();
2946     Paths.setRecordingPaths(true);
2947     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2948     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2949     (void)StillOkay;
2950 
2951     // Build up a textual representation of the ambiguous paths, e.g.,
2952     // D -> B -> A, that will be used to illustrate the ambiguous
2953     // conversions in the diagnostic. We only print one of the paths
2954     // to each base class subobject.
2955     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2956 
2957     Diag(Loc, AmbiguousBaseConvID)
2958     << Derived << Base << PathDisplayStr << Range << Name;
2959   }
2960   return true;
2961 }
2962 
2963 bool
2964 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2965                                    SourceLocation Loc, SourceRange Range,
2966                                    CXXCastPath *BasePath,
2967                                    bool IgnoreAccess) {
2968   return CheckDerivedToBaseConversion(
2969       Derived, Base, diag::err_upcast_to_inaccessible_base,
2970       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2971       BasePath, IgnoreAccess);
2972 }
2973 
2974 
2975 /// Builds a string representing ambiguous paths from a
2976 /// specific derived class to different subobjects of the same base
2977 /// class.
2978 ///
2979 /// This function builds a string that can be used in error messages
2980 /// to show the different paths that one can take through the
2981 /// inheritance hierarchy to go from the derived class to different
2982 /// subobjects of a base class. The result looks something like this:
2983 /// @code
2984 /// struct D -> struct B -> struct A
2985 /// struct D -> struct C -> struct A
2986 /// @endcode
2987 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2988   std::string PathDisplayStr;
2989   std::set<unsigned> DisplayedPaths;
2990   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2991        Path != Paths.end(); ++Path) {
2992     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2993       // We haven't displayed a path to this particular base
2994       // class subobject yet.
2995       PathDisplayStr += "\n    ";
2996       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2997       for (CXXBasePath::const_iterator Element = Path->begin();
2998            Element != Path->end(); ++Element)
2999         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3000     }
3001   }
3002 
3003   return PathDisplayStr;
3004 }
3005 
3006 //===----------------------------------------------------------------------===//
3007 // C++ class member Handling
3008 //===----------------------------------------------------------------------===//
3009 
3010 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3011 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3012                                 SourceLocation ColonLoc,
3013                                 const ParsedAttributesView &Attrs) {
3014   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3015   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3016                                                   ASLoc, ColonLoc);
3017   CurContext->addHiddenDecl(ASDecl);
3018   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3019 }
3020 
3021 /// CheckOverrideControl - Check C++11 override control semantics.
3022 void Sema::CheckOverrideControl(NamedDecl *D) {
3023   if (D->isInvalidDecl())
3024     return;
3025 
3026   // We only care about "override" and "final" declarations.
3027   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3028     return;
3029 
3030   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3031 
3032   // We can't check dependent instance methods.
3033   if (MD && MD->isInstance() &&
3034       (MD->getParent()->hasAnyDependentBases() ||
3035        MD->getType()->isDependentType()))
3036     return;
3037 
3038   if (MD && !MD->isVirtual()) {
3039     // If we have a non-virtual method, check if if hides a virtual method.
3040     // (In that case, it's most likely the method has the wrong type.)
3041     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3042     FindHiddenVirtualMethods(MD, OverloadedMethods);
3043 
3044     if (!OverloadedMethods.empty()) {
3045       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3046         Diag(OA->getLocation(),
3047              diag::override_keyword_hides_virtual_member_function)
3048           << "override" << (OverloadedMethods.size() > 1);
3049       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3050         Diag(FA->getLocation(),
3051              diag::override_keyword_hides_virtual_member_function)
3052           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3053           << (OverloadedMethods.size() > 1);
3054       }
3055       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3056       MD->setInvalidDecl();
3057       return;
3058     }
3059     // Fall through into the general case diagnostic.
3060     // FIXME: We might want to attempt typo correction here.
3061   }
3062 
3063   if (!MD || !MD->isVirtual()) {
3064     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3065       Diag(OA->getLocation(),
3066            diag::override_keyword_only_allowed_on_virtual_member_functions)
3067         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3068       D->dropAttr<OverrideAttr>();
3069     }
3070     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3071       Diag(FA->getLocation(),
3072            diag::override_keyword_only_allowed_on_virtual_member_functions)
3073         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3074         << FixItHint::CreateRemoval(FA->getLocation());
3075       D->dropAttr<FinalAttr>();
3076     }
3077     return;
3078   }
3079 
3080   // C++11 [class.virtual]p5:
3081   //   If a function is marked with the virt-specifier override and
3082   //   does not override a member function of a base class, the program is
3083   //   ill-formed.
3084   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3085   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3086     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3087       << MD->getDeclName();
3088 }
3089 
3090 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3091   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3092     return;
3093   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3094   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3095     return;
3096 
3097   SourceLocation Loc = MD->getLocation();
3098   SourceLocation SpellingLoc = Loc;
3099   if (getSourceManager().isMacroArgExpansion(Loc))
3100     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3101   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3102   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3103       return;
3104 
3105   if (MD->size_overridden_methods() > 0) {
3106     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3107       unsigned DiagID =
3108           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3109               ? DiagInconsistent
3110               : DiagSuggest;
3111       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3112       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3113       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3114     };
3115     if (isa<CXXDestructorDecl>(MD))
3116       EmitDiag(
3117           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3118           diag::warn_suggest_destructor_marked_not_override_overriding);
3119     else
3120       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3121                diag::warn_suggest_function_marked_not_override_overriding);
3122   }
3123 }
3124 
3125 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3126 /// function overrides a virtual member function marked 'final', according to
3127 /// C++11 [class.virtual]p4.
3128 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3129                                                   const CXXMethodDecl *Old) {
3130   FinalAttr *FA = Old->getAttr<FinalAttr>();
3131   if (!FA)
3132     return false;
3133 
3134   Diag(New->getLocation(), diag::err_final_function_overridden)
3135     << New->getDeclName()
3136     << FA->isSpelledAsSealed();
3137   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3138   return true;
3139 }
3140 
3141 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3142   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3143   // FIXME: Destruction of ObjC lifetime types has side-effects.
3144   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3145     return !RD->isCompleteDefinition() ||
3146            !RD->hasTrivialDefaultConstructor() ||
3147            !RD->hasTrivialDestructor();
3148   return false;
3149 }
3150 
3151 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3152   ParsedAttributesView::const_iterator Itr =
3153       llvm::find_if(list, [](const ParsedAttr &AL) {
3154         return AL.isDeclspecPropertyAttribute();
3155       });
3156   if (Itr != list.end())
3157     return &*Itr;
3158   return nullptr;
3159 }
3160 
3161 // Check if there is a field shadowing.
3162 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3163                                       DeclarationName FieldName,
3164                                       const CXXRecordDecl *RD,
3165                                       bool DeclIsField) {
3166   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3167     return;
3168 
3169   // To record a shadowed field in a base
3170   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3171   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3172                            CXXBasePath &Path) {
3173     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3174     // Record an ambiguous path directly
3175     if (Bases.find(Base) != Bases.end())
3176       return true;
3177     for (const auto Field : Base->lookup(FieldName)) {
3178       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3179           Field->getAccess() != AS_private) {
3180         assert(Field->getAccess() != AS_none);
3181         assert(Bases.find(Base) == Bases.end());
3182         Bases[Base] = Field;
3183         return true;
3184       }
3185     }
3186     return false;
3187   };
3188 
3189   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3190                      /*DetectVirtual=*/true);
3191   if (!RD->lookupInBases(FieldShadowed, Paths))
3192     return;
3193 
3194   for (const auto &P : Paths) {
3195     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3196     auto It = Bases.find(Base);
3197     // Skip duplicated bases
3198     if (It == Bases.end())
3199       continue;
3200     auto BaseField = It->second;
3201     assert(BaseField->getAccess() != AS_private);
3202     if (AS_none !=
3203         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3204       Diag(Loc, diag::warn_shadow_field)
3205         << FieldName << RD << Base << DeclIsField;
3206       Diag(BaseField->getLocation(), diag::note_shadow_field);
3207       Bases.erase(It);
3208     }
3209   }
3210 }
3211 
3212 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3213 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3214 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3215 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3216 /// present (but parsing it has been deferred).
3217 NamedDecl *
3218 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3219                                MultiTemplateParamsArg TemplateParameterLists,
3220                                Expr *BW, const VirtSpecifiers &VS,
3221                                InClassInitStyle InitStyle) {
3222   const DeclSpec &DS = D.getDeclSpec();
3223   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3224   DeclarationName Name = NameInfo.getName();
3225   SourceLocation Loc = NameInfo.getLoc();
3226 
3227   // For anonymous bitfields, the location should point to the type.
3228   if (Loc.isInvalid())
3229     Loc = D.getBeginLoc();
3230 
3231   Expr *BitWidth = static_cast<Expr*>(BW);
3232 
3233   assert(isa<CXXRecordDecl>(CurContext));
3234   assert(!DS.isFriendSpecified());
3235 
3236   bool isFunc = D.isDeclarationOfFunction();
3237   const ParsedAttr *MSPropertyAttr =
3238       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3239 
3240   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3241     // The Microsoft extension __interface only permits public member functions
3242     // and prohibits constructors, destructors, operators, non-public member
3243     // functions, static methods and data members.
3244     unsigned InvalidDecl;
3245     bool ShowDeclName = true;
3246     if (!isFunc &&
3247         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3248       InvalidDecl = 0;
3249     else if (!isFunc)
3250       InvalidDecl = 1;
3251     else if (AS != AS_public)
3252       InvalidDecl = 2;
3253     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3254       InvalidDecl = 3;
3255     else switch (Name.getNameKind()) {
3256       case DeclarationName::CXXConstructorName:
3257         InvalidDecl = 4;
3258         ShowDeclName = false;
3259         break;
3260 
3261       case DeclarationName::CXXDestructorName:
3262         InvalidDecl = 5;
3263         ShowDeclName = false;
3264         break;
3265 
3266       case DeclarationName::CXXOperatorName:
3267       case DeclarationName::CXXConversionFunctionName:
3268         InvalidDecl = 6;
3269         break;
3270 
3271       default:
3272         InvalidDecl = 0;
3273         break;
3274     }
3275 
3276     if (InvalidDecl) {
3277       if (ShowDeclName)
3278         Diag(Loc, diag::err_invalid_member_in_interface)
3279           << (InvalidDecl-1) << Name;
3280       else
3281         Diag(Loc, diag::err_invalid_member_in_interface)
3282           << (InvalidDecl-1) << "";
3283       return nullptr;
3284     }
3285   }
3286 
3287   // C++ 9.2p6: A member shall not be declared to have automatic storage
3288   // duration (auto, register) or with the extern storage-class-specifier.
3289   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3290   // data members and cannot be applied to names declared const or static,
3291   // and cannot be applied to reference members.
3292   switch (DS.getStorageClassSpec()) {
3293   case DeclSpec::SCS_unspecified:
3294   case DeclSpec::SCS_typedef:
3295   case DeclSpec::SCS_static:
3296     break;
3297   case DeclSpec::SCS_mutable:
3298     if (isFunc) {
3299       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3300 
3301       // FIXME: It would be nicer if the keyword was ignored only for this
3302       // declarator. Otherwise we could get follow-up errors.
3303       D.getMutableDeclSpec().ClearStorageClassSpecs();
3304     }
3305     break;
3306   default:
3307     Diag(DS.getStorageClassSpecLoc(),
3308          diag::err_storageclass_invalid_for_member);
3309     D.getMutableDeclSpec().ClearStorageClassSpecs();
3310     break;
3311   }
3312 
3313   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3314                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3315                       !isFunc);
3316 
3317   if (DS.hasConstexprSpecifier() && isInstField) {
3318     SemaDiagnosticBuilder B =
3319         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3320     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3321     if (InitStyle == ICIS_NoInit) {
3322       B << 0 << 0;
3323       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3324         B << FixItHint::CreateRemoval(ConstexprLoc);
3325       else {
3326         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3327         D.getMutableDeclSpec().ClearConstexprSpec();
3328         const char *PrevSpec;
3329         unsigned DiagID;
3330         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3331             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3332         (void)Failed;
3333         assert(!Failed && "Making a constexpr member const shouldn't fail");
3334       }
3335     } else {
3336       B << 1;
3337       const char *PrevSpec;
3338       unsigned DiagID;
3339       if (D.getMutableDeclSpec().SetStorageClassSpec(
3340           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3341           Context.getPrintingPolicy())) {
3342         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3343                "This is the only DeclSpec that should fail to be applied");
3344         B << 1;
3345       } else {
3346         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3347         isInstField = false;
3348       }
3349     }
3350   }
3351 
3352   NamedDecl *Member;
3353   if (isInstField) {
3354     CXXScopeSpec &SS = D.getCXXScopeSpec();
3355 
3356     // Data members must have identifiers for names.
3357     if (!Name.isIdentifier()) {
3358       Diag(Loc, diag::err_bad_variable_name)
3359         << Name;
3360       return nullptr;
3361     }
3362 
3363     IdentifierInfo *II = Name.getAsIdentifierInfo();
3364 
3365     // Member field could not be with "template" keyword.
3366     // So TemplateParameterLists should be empty in this case.
3367     if (TemplateParameterLists.size()) {
3368       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3369       if (TemplateParams->size()) {
3370         // There is no such thing as a member field template.
3371         Diag(D.getIdentifierLoc(), diag::err_template_member)
3372             << II
3373             << SourceRange(TemplateParams->getTemplateLoc(),
3374                 TemplateParams->getRAngleLoc());
3375       } else {
3376         // There is an extraneous 'template<>' for this member.
3377         Diag(TemplateParams->getTemplateLoc(),
3378             diag::err_template_member_noparams)
3379             << II
3380             << SourceRange(TemplateParams->getTemplateLoc(),
3381                 TemplateParams->getRAngleLoc());
3382       }
3383       return nullptr;
3384     }
3385 
3386     if (SS.isSet() && !SS.isInvalid()) {
3387       // The user provided a superfluous scope specifier inside a class
3388       // definition:
3389       //
3390       // class X {
3391       //   int X::member;
3392       // };
3393       if (DeclContext *DC = computeDeclContext(SS, false))
3394         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3395                                      D.getName().getKind() ==
3396                                          UnqualifiedIdKind::IK_TemplateId);
3397       else
3398         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3399           << Name << SS.getRange();
3400 
3401       SS.clear();
3402     }
3403 
3404     if (MSPropertyAttr) {
3405       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3406                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3407       if (!Member)
3408         return nullptr;
3409       isInstField = false;
3410     } else {
3411       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3412                                 BitWidth, InitStyle, AS);
3413       if (!Member)
3414         return nullptr;
3415     }
3416 
3417     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3418   } else {
3419     Member = HandleDeclarator(S, D, TemplateParameterLists);
3420     if (!Member)
3421       return nullptr;
3422 
3423     // Non-instance-fields can't have a bitfield.
3424     if (BitWidth) {
3425       if (Member->isInvalidDecl()) {
3426         // don't emit another diagnostic.
3427       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3428         // C++ 9.6p3: A bit-field shall not be a static member.
3429         // "static member 'A' cannot be a bit-field"
3430         Diag(Loc, diag::err_static_not_bitfield)
3431           << Name << BitWidth->getSourceRange();
3432       } else if (isa<TypedefDecl>(Member)) {
3433         // "typedef member 'x' cannot be a bit-field"
3434         Diag(Loc, diag::err_typedef_not_bitfield)
3435           << Name << BitWidth->getSourceRange();
3436       } else {
3437         // A function typedef ("typedef int f(); f a;").
3438         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3439         Diag(Loc, diag::err_not_integral_type_bitfield)
3440           << Name << cast<ValueDecl>(Member)->getType()
3441           << BitWidth->getSourceRange();
3442       }
3443 
3444       BitWidth = nullptr;
3445       Member->setInvalidDecl();
3446     }
3447 
3448     NamedDecl *NonTemplateMember = Member;
3449     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3450       NonTemplateMember = FunTmpl->getTemplatedDecl();
3451     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3452       NonTemplateMember = VarTmpl->getTemplatedDecl();
3453 
3454     Member->setAccess(AS);
3455 
3456     // If we have declared a member function template or static data member
3457     // template, set the access of the templated declaration as well.
3458     if (NonTemplateMember != Member)
3459       NonTemplateMember->setAccess(AS);
3460 
3461     // C++ [temp.deduct.guide]p3:
3462     //   A deduction guide [...] for a member class template [shall be
3463     //   declared] with the same access [as the template].
3464     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3465       auto *TD = DG->getDeducedTemplate();
3466       // Access specifiers are only meaningful if both the template and the
3467       // deduction guide are from the same scope.
3468       if (AS != TD->getAccess() &&
3469           TD->getDeclContext()->getRedeclContext()->Equals(
3470               DG->getDeclContext()->getRedeclContext())) {
3471         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3472         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3473             << TD->getAccess();
3474         const AccessSpecDecl *LastAccessSpec = nullptr;
3475         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3476           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3477             LastAccessSpec = AccessSpec;
3478         }
3479         assert(LastAccessSpec && "differing access with no access specifier");
3480         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3481             << AS;
3482       }
3483     }
3484   }
3485 
3486   if (VS.isOverrideSpecified())
3487     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3488                                          AttributeCommonInfo::AS_Keyword));
3489   if (VS.isFinalSpecified())
3490     Member->addAttr(FinalAttr::Create(
3491         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3492         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3493 
3494   if (VS.getLastLocation().isValid()) {
3495     // Update the end location of a method that has a virt-specifiers.
3496     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3497       MD->setRangeEnd(VS.getLastLocation());
3498   }
3499 
3500   CheckOverrideControl(Member);
3501 
3502   assert((Name || isInstField) && "No identifier for non-field ?");
3503 
3504   if (isInstField) {
3505     FieldDecl *FD = cast<FieldDecl>(Member);
3506     FieldCollector->Add(FD);
3507 
3508     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3509       // Remember all explicit private FieldDecls that have a name, no side
3510       // effects and are not part of a dependent type declaration.
3511       if (!FD->isImplicit() && FD->getDeclName() &&
3512           FD->getAccess() == AS_private &&
3513           !FD->hasAttr<UnusedAttr>() &&
3514           !FD->getParent()->isDependentContext() &&
3515           !InitializationHasSideEffects(*FD))
3516         UnusedPrivateFields.insert(FD);
3517     }
3518   }
3519 
3520   return Member;
3521 }
3522 
3523 namespace {
3524   class UninitializedFieldVisitor
3525       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3526     Sema &S;
3527     // List of Decls to generate a warning on.  Also remove Decls that become
3528     // initialized.
3529     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3530     // List of base classes of the record.  Classes are removed after their
3531     // initializers.
3532     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3533     // Vector of decls to be removed from the Decl set prior to visiting the
3534     // nodes.  These Decls may have been initialized in the prior initializer.
3535     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3536     // If non-null, add a note to the warning pointing back to the constructor.
3537     const CXXConstructorDecl *Constructor;
3538     // Variables to hold state when processing an initializer list.  When
3539     // InitList is true, special case initialization of FieldDecls matching
3540     // InitListFieldDecl.
3541     bool InitList;
3542     FieldDecl *InitListFieldDecl;
3543     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3544 
3545   public:
3546     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3547     UninitializedFieldVisitor(Sema &S,
3548                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3549                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3550       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3551         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3552 
3553     // Returns true if the use of ME is not an uninitialized use.
3554     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3555                                          bool CheckReferenceOnly) {
3556       llvm::SmallVector<FieldDecl*, 4> Fields;
3557       bool ReferenceField = false;
3558       while (ME) {
3559         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3560         if (!FD)
3561           return false;
3562         Fields.push_back(FD);
3563         if (FD->getType()->isReferenceType())
3564           ReferenceField = true;
3565         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3566       }
3567 
3568       // Binding a reference to an uninitialized field is not an
3569       // uninitialized use.
3570       if (CheckReferenceOnly && !ReferenceField)
3571         return true;
3572 
3573       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3574       // Discard the first field since it is the field decl that is being
3575       // initialized.
3576       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3577         UsedFieldIndex.push_back((*I)->getFieldIndex());
3578       }
3579 
3580       for (auto UsedIter = UsedFieldIndex.begin(),
3581                 UsedEnd = UsedFieldIndex.end(),
3582                 OrigIter = InitFieldIndex.begin(),
3583                 OrigEnd = InitFieldIndex.end();
3584            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3585         if (*UsedIter < *OrigIter)
3586           return true;
3587         if (*UsedIter > *OrigIter)
3588           break;
3589       }
3590 
3591       return false;
3592     }
3593 
3594     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3595                           bool AddressOf) {
3596       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3597         return;
3598 
3599       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3600       // or union.
3601       MemberExpr *FieldME = ME;
3602 
3603       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3604 
3605       Expr *Base = ME;
3606       while (MemberExpr *SubME =
3607                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3608 
3609         if (isa<VarDecl>(SubME->getMemberDecl()))
3610           return;
3611 
3612         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3613           if (!FD->isAnonymousStructOrUnion())
3614             FieldME = SubME;
3615 
3616         if (!FieldME->getType().isPODType(S.Context))
3617           AllPODFields = false;
3618 
3619         Base = SubME->getBase();
3620       }
3621 
3622       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3623         Visit(Base);
3624         return;
3625       }
3626 
3627       if (AddressOf && AllPODFields)
3628         return;
3629 
3630       ValueDecl* FoundVD = FieldME->getMemberDecl();
3631 
3632       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3633         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3634           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3635         }
3636 
3637         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3638           QualType T = BaseCast->getType();
3639           if (T->isPointerType() &&
3640               BaseClasses.count(T->getPointeeType())) {
3641             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3642                 << T->getPointeeType() << FoundVD;
3643           }
3644         }
3645       }
3646 
3647       if (!Decls.count(FoundVD))
3648         return;
3649 
3650       const bool IsReference = FoundVD->getType()->isReferenceType();
3651 
3652       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3653         // Special checking for initializer lists.
3654         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3655           return;
3656         }
3657       } else {
3658         // Prevent double warnings on use of unbounded references.
3659         if (CheckReferenceOnly && !IsReference)
3660           return;
3661       }
3662 
3663       unsigned diag = IsReference
3664           ? diag::warn_reference_field_is_uninit
3665           : diag::warn_field_is_uninit;
3666       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3667       if (Constructor)
3668         S.Diag(Constructor->getLocation(),
3669                diag::note_uninit_in_this_constructor)
3670           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3671 
3672     }
3673 
3674     void HandleValue(Expr *E, bool AddressOf) {
3675       E = E->IgnoreParens();
3676 
3677       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3678         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3679                          AddressOf /*AddressOf*/);
3680         return;
3681       }
3682 
3683       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3684         Visit(CO->getCond());
3685         HandleValue(CO->getTrueExpr(), AddressOf);
3686         HandleValue(CO->getFalseExpr(), AddressOf);
3687         return;
3688       }
3689 
3690       if (BinaryConditionalOperator *BCO =
3691               dyn_cast<BinaryConditionalOperator>(E)) {
3692         Visit(BCO->getCond());
3693         HandleValue(BCO->getFalseExpr(), AddressOf);
3694         return;
3695       }
3696 
3697       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3698         HandleValue(OVE->getSourceExpr(), AddressOf);
3699         return;
3700       }
3701 
3702       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3703         switch (BO->getOpcode()) {
3704         default:
3705           break;
3706         case(BO_PtrMemD):
3707         case(BO_PtrMemI):
3708           HandleValue(BO->getLHS(), AddressOf);
3709           Visit(BO->getRHS());
3710           return;
3711         case(BO_Comma):
3712           Visit(BO->getLHS());
3713           HandleValue(BO->getRHS(), AddressOf);
3714           return;
3715         }
3716       }
3717 
3718       Visit(E);
3719     }
3720 
3721     void CheckInitListExpr(InitListExpr *ILE) {
3722       InitFieldIndex.push_back(0);
3723       for (auto Child : ILE->children()) {
3724         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3725           CheckInitListExpr(SubList);
3726         } else {
3727           Visit(Child);
3728         }
3729         ++InitFieldIndex.back();
3730       }
3731       InitFieldIndex.pop_back();
3732     }
3733 
3734     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3735                           FieldDecl *Field, const Type *BaseClass) {
3736       // Remove Decls that may have been initialized in the previous
3737       // initializer.
3738       for (ValueDecl* VD : DeclsToRemove)
3739         Decls.erase(VD);
3740       DeclsToRemove.clear();
3741 
3742       Constructor = FieldConstructor;
3743       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3744 
3745       if (ILE && Field) {
3746         InitList = true;
3747         InitListFieldDecl = Field;
3748         InitFieldIndex.clear();
3749         CheckInitListExpr(ILE);
3750       } else {
3751         InitList = false;
3752         Visit(E);
3753       }
3754 
3755       if (Field)
3756         Decls.erase(Field);
3757       if (BaseClass)
3758         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3759     }
3760 
3761     void VisitMemberExpr(MemberExpr *ME) {
3762       // All uses of unbounded reference fields will warn.
3763       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3764     }
3765 
3766     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3767       if (E->getCastKind() == CK_LValueToRValue) {
3768         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3769         return;
3770       }
3771 
3772       Inherited::VisitImplicitCastExpr(E);
3773     }
3774 
3775     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3776       if (E->getConstructor()->isCopyConstructor()) {
3777         Expr *ArgExpr = E->getArg(0);
3778         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3779           if (ILE->getNumInits() == 1)
3780             ArgExpr = ILE->getInit(0);
3781         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3782           if (ICE->getCastKind() == CK_NoOp)
3783             ArgExpr = ICE->getSubExpr();
3784         HandleValue(ArgExpr, false /*AddressOf*/);
3785         return;
3786       }
3787       Inherited::VisitCXXConstructExpr(E);
3788     }
3789 
3790     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3791       Expr *Callee = E->getCallee();
3792       if (isa<MemberExpr>(Callee)) {
3793         HandleValue(Callee, false /*AddressOf*/);
3794         for (auto Arg : E->arguments())
3795           Visit(Arg);
3796         return;
3797       }
3798 
3799       Inherited::VisitCXXMemberCallExpr(E);
3800     }
3801 
3802     void VisitCallExpr(CallExpr *E) {
3803       // Treat std::move as a use.
3804       if (E->isCallToStdMove()) {
3805         HandleValue(E->getArg(0), /*AddressOf=*/false);
3806         return;
3807       }
3808 
3809       Inherited::VisitCallExpr(E);
3810     }
3811 
3812     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3813       Expr *Callee = E->getCallee();
3814 
3815       if (isa<UnresolvedLookupExpr>(Callee))
3816         return Inherited::VisitCXXOperatorCallExpr(E);
3817 
3818       Visit(Callee);
3819       for (auto Arg : E->arguments())
3820         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3821     }
3822 
3823     void VisitBinaryOperator(BinaryOperator *E) {
3824       // If a field assignment is detected, remove the field from the
3825       // uninitiailized field set.
3826       if (E->getOpcode() == BO_Assign)
3827         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3828           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3829             if (!FD->getType()->isReferenceType())
3830               DeclsToRemove.push_back(FD);
3831 
3832       if (E->isCompoundAssignmentOp()) {
3833         HandleValue(E->getLHS(), false /*AddressOf*/);
3834         Visit(E->getRHS());
3835         return;
3836       }
3837 
3838       Inherited::VisitBinaryOperator(E);
3839     }
3840 
3841     void VisitUnaryOperator(UnaryOperator *E) {
3842       if (E->isIncrementDecrementOp()) {
3843         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3844         return;
3845       }
3846       if (E->getOpcode() == UO_AddrOf) {
3847         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3848           HandleValue(ME->getBase(), true /*AddressOf*/);
3849           return;
3850         }
3851       }
3852 
3853       Inherited::VisitUnaryOperator(E);
3854     }
3855   };
3856 
3857   // Diagnose value-uses of fields to initialize themselves, e.g.
3858   //   foo(foo)
3859   // where foo is not also a parameter to the constructor.
3860   // Also diagnose across field uninitialized use such as
3861   //   x(y), y(x)
3862   // TODO: implement -Wuninitialized and fold this into that framework.
3863   static void DiagnoseUninitializedFields(
3864       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3865 
3866     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3867                                            Constructor->getLocation())) {
3868       return;
3869     }
3870 
3871     if (Constructor->isInvalidDecl())
3872       return;
3873 
3874     const CXXRecordDecl *RD = Constructor->getParent();
3875 
3876     if (RD->isDependentContext())
3877       return;
3878 
3879     // Holds fields that are uninitialized.
3880     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3881 
3882     // At the beginning, all fields are uninitialized.
3883     for (auto *I : RD->decls()) {
3884       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3885         UninitializedFields.insert(FD);
3886       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3887         UninitializedFields.insert(IFD->getAnonField());
3888       }
3889     }
3890 
3891     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3892     for (auto I : RD->bases())
3893       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3894 
3895     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3896       return;
3897 
3898     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3899                                                    UninitializedFields,
3900                                                    UninitializedBaseClasses);
3901 
3902     for (const auto *FieldInit : Constructor->inits()) {
3903       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3904         break;
3905 
3906       Expr *InitExpr = FieldInit->getInit();
3907       if (!InitExpr)
3908         continue;
3909 
3910       if (CXXDefaultInitExpr *Default =
3911               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3912         InitExpr = Default->getExpr();
3913         if (!InitExpr)
3914           continue;
3915         // In class initializers will point to the constructor.
3916         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3917                                               FieldInit->getAnyMember(),
3918                                               FieldInit->getBaseClass());
3919       } else {
3920         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3921                                               FieldInit->getAnyMember(),
3922                                               FieldInit->getBaseClass());
3923       }
3924     }
3925   }
3926 } // namespace
3927 
3928 /// Enter a new C++ default initializer scope. After calling this, the
3929 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3930 /// parsing or instantiating the initializer failed.
3931 void Sema::ActOnStartCXXInClassMemberInitializer() {
3932   // Create a synthetic function scope to represent the call to the constructor
3933   // that notionally surrounds a use of this initializer.
3934   PushFunctionScope();
3935 }
3936 
3937 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3938   if (!D.isFunctionDeclarator())
3939     return;
3940   auto &FTI = D.getFunctionTypeInfo();
3941   if (!FTI.Params)
3942     return;
3943   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3944                                                           FTI.NumParams)) {
3945     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3946     if (ParamDecl->getDeclName())
3947       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3948   }
3949 }
3950 
3951 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3952   return ActOnRequiresClause(ConstraintExpr);
3953 }
3954 
3955 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3956   if (ConstraintExpr.isInvalid())
3957     return ExprError();
3958 
3959   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3960   if (ConstraintExpr.isInvalid())
3961     return ExprError();
3962 
3963   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3964                                       UPPC_RequiresClause))
3965     return ExprError();
3966 
3967   return ConstraintExpr;
3968 }
3969 
3970 /// This is invoked after parsing an in-class initializer for a
3971 /// non-static C++ class member, and after instantiating an in-class initializer
3972 /// in a class template. Such actions are deferred until the class is complete.
3973 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3974                                                   SourceLocation InitLoc,
3975                                                   Expr *InitExpr) {
3976   // Pop the notional constructor scope we created earlier.
3977   PopFunctionScopeInfo(nullptr, D);
3978 
3979   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3980   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3981          "must set init style when field is created");
3982 
3983   if (!InitExpr) {
3984     D->setInvalidDecl();
3985     if (FD)
3986       FD->removeInClassInitializer();
3987     return;
3988   }
3989 
3990   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3991     FD->setInvalidDecl();
3992     FD->removeInClassInitializer();
3993     return;
3994   }
3995 
3996   ExprResult Init = InitExpr;
3997   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3998     InitializedEntity Entity =
3999         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4000     InitializationKind Kind =
4001         FD->getInClassInitStyle() == ICIS_ListInit
4002             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4003                                                    InitExpr->getBeginLoc(),
4004                                                    InitExpr->getEndLoc())
4005             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4006     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4007     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4008     if (Init.isInvalid()) {
4009       FD->setInvalidDecl();
4010       return;
4011     }
4012   }
4013 
4014   // C++11 [class.base.init]p7:
4015   //   The initialization of each base and member constitutes a
4016   //   full-expression.
4017   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4018   if (Init.isInvalid()) {
4019     FD->setInvalidDecl();
4020     return;
4021   }
4022 
4023   InitExpr = Init.get();
4024 
4025   FD->setInClassInitializer(InitExpr);
4026 }
4027 
4028 /// Find the direct and/or virtual base specifiers that
4029 /// correspond to the given base type, for use in base initialization
4030 /// within a constructor.
4031 static bool FindBaseInitializer(Sema &SemaRef,
4032                                 CXXRecordDecl *ClassDecl,
4033                                 QualType BaseType,
4034                                 const CXXBaseSpecifier *&DirectBaseSpec,
4035                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4036   // First, check for a direct base class.
4037   DirectBaseSpec = nullptr;
4038   for (const auto &Base : ClassDecl->bases()) {
4039     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4040       // We found a direct base of this type. That's what we're
4041       // initializing.
4042       DirectBaseSpec = &Base;
4043       break;
4044     }
4045   }
4046 
4047   // Check for a virtual base class.
4048   // FIXME: We might be able to short-circuit this if we know in advance that
4049   // there are no virtual bases.
4050   VirtualBaseSpec = nullptr;
4051   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4052     // We haven't found a base yet; search the class hierarchy for a
4053     // virtual base class.
4054     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4055                        /*DetectVirtual=*/false);
4056     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4057                               SemaRef.Context.getTypeDeclType(ClassDecl),
4058                               BaseType, Paths)) {
4059       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4060            Path != Paths.end(); ++Path) {
4061         if (Path->back().Base->isVirtual()) {
4062           VirtualBaseSpec = Path->back().Base;
4063           break;
4064         }
4065       }
4066     }
4067   }
4068 
4069   return DirectBaseSpec || VirtualBaseSpec;
4070 }
4071 
4072 /// Handle a C++ member initializer using braced-init-list syntax.
4073 MemInitResult
4074 Sema::ActOnMemInitializer(Decl *ConstructorD,
4075                           Scope *S,
4076                           CXXScopeSpec &SS,
4077                           IdentifierInfo *MemberOrBase,
4078                           ParsedType TemplateTypeTy,
4079                           const DeclSpec &DS,
4080                           SourceLocation IdLoc,
4081                           Expr *InitList,
4082                           SourceLocation EllipsisLoc) {
4083   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4084                              DS, IdLoc, InitList,
4085                              EllipsisLoc);
4086 }
4087 
4088 /// Handle a C++ member initializer using parentheses syntax.
4089 MemInitResult
4090 Sema::ActOnMemInitializer(Decl *ConstructorD,
4091                           Scope *S,
4092                           CXXScopeSpec &SS,
4093                           IdentifierInfo *MemberOrBase,
4094                           ParsedType TemplateTypeTy,
4095                           const DeclSpec &DS,
4096                           SourceLocation IdLoc,
4097                           SourceLocation LParenLoc,
4098                           ArrayRef<Expr *> Args,
4099                           SourceLocation RParenLoc,
4100                           SourceLocation EllipsisLoc) {
4101   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4102   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4103                              DS, IdLoc, List, EllipsisLoc);
4104 }
4105 
4106 namespace {
4107 
4108 // Callback to only accept typo corrections that can be a valid C++ member
4109 // intializer: either a non-static field member or a base class.
4110 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4111 public:
4112   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4113       : ClassDecl(ClassDecl) {}
4114 
4115   bool ValidateCandidate(const TypoCorrection &candidate) override {
4116     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4117       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4118         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4119       return isa<TypeDecl>(ND);
4120     }
4121     return false;
4122   }
4123 
4124   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4125     return std::make_unique<MemInitializerValidatorCCC>(*this);
4126   }
4127 
4128 private:
4129   CXXRecordDecl *ClassDecl;
4130 };
4131 
4132 }
4133 
4134 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4135                                              CXXScopeSpec &SS,
4136                                              ParsedType TemplateTypeTy,
4137                                              IdentifierInfo *MemberOrBase) {
4138   if (SS.getScopeRep() || TemplateTypeTy)
4139     return nullptr;
4140   for (auto *D : ClassDecl->lookup(MemberOrBase))
4141     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4142       return cast<ValueDecl>(D);
4143   return nullptr;
4144 }
4145 
4146 /// Handle a C++ member initializer.
4147 MemInitResult
4148 Sema::BuildMemInitializer(Decl *ConstructorD,
4149                           Scope *S,
4150                           CXXScopeSpec &SS,
4151                           IdentifierInfo *MemberOrBase,
4152                           ParsedType TemplateTypeTy,
4153                           const DeclSpec &DS,
4154                           SourceLocation IdLoc,
4155                           Expr *Init,
4156                           SourceLocation EllipsisLoc) {
4157   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4158   if (!Res.isUsable())
4159     return true;
4160   Init = Res.get();
4161 
4162   if (!ConstructorD)
4163     return true;
4164 
4165   AdjustDeclIfTemplate(ConstructorD);
4166 
4167   CXXConstructorDecl *Constructor
4168     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4169   if (!Constructor) {
4170     // The user wrote a constructor initializer on a function that is
4171     // not a C++ constructor. Ignore the error for now, because we may
4172     // have more member initializers coming; we'll diagnose it just
4173     // once in ActOnMemInitializers.
4174     return true;
4175   }
4176 
4177   CXXRecordDecl *ClassDecl = Constructor->getParent();
4178 
4179   // C++ [class.base.init]p2:
4180   //   Names in a mem-initializer-id are looked up in the scope of the
4181   //   constructor's class and, if not found in that scope, are looked
4182   //   up in the scope containing the constructor's definition.
4183   //   [Note: if the constructor's class contains a member with the
4184   //   same name as a direct or virtual base class of the class, a
4185   //   mem-initializer-id naming the member or base class and composed
4186   //   of a single identifier refers to the class member. A
4187   //   mem-initializer-id for the hidden base class may be specified
4188   //   using a qualified name. ]
4189 
4190   // Look for a member, first.
4191   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4192           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4193     if (EllipsisLoc.isValid())
4194       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4195           << MemberOrBase
4196           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4197 
4198     return BuildMemberInitializer(Member, Init, IdLoc);
4199   }
4200   // It didn't name a member, so see if it names a class.
4201   QualType BaseType;
4202   TypeSourceInfo *TInfo = nullptr;
4203 
4204   if (TemplateTypeTy) {
4205     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4206     if (BaseType.isNull())
4207       return true;
4208   } else if (DS.getTypeSpecType() == TST_decltype) {
4209     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4210   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4211     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4212     return true;
4213   } else {
4214     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4215     LookupParsedName(R, S, &SS);
4216 
4217     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4218     if (!TyD) {
4219       if (R.isAmbiguous()) return true;
4220 
4221       // We don't want access-control diagnostics here.
4222       R.suppressDiagnostics();
4223 
4224       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4225         bool NotUnknownSpecialization = false;
4226         DeclContext *DC = computeDeclContext(SS, false);
4227         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4228           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4229 
4230         if (!NotUnknownSpecialization) {
4231           // When the scope specifier can refer to a member of an unknown
4232           // specialization, we take it as a type name.
4233           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4234                                        SS.getWithLocInContext(Context),
4235                                        *MemberOrBase, IdLoc);
4236           if (BaseType.isNull())
4237             return true;
4238 
4239           TInfo = Context.CreateTypeSourceInfo(BaseType);
4240           DependentNameTypeLoc TL =
4241               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4242           if (!TL.isNull()) {
4243             TL.setNameLoc(IdLoc);
4244             TL.setElaboratedKeywordLoc(SourceLocation());
4245             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4246           }
4247 
4248           R.clear();
4249           R.setLookupName(MemberOrBase);
4250         }
4251       }
4252 
4253       // If no results were found, try to correct typos.
4254       TypoCorrection Corr;
4255       MemInitializerValidatorCCC CCC(ClassDecl);
4256       if (R.empty() && BaseType.isNull() &&
4257           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4258                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4259         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4260           // We have found a non-static data member with a similar
4261           // name to what was typed; complain and initialize that
4262           // member.
4263           diagnoseTypo(Corr,
4264                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4265                          << MemberOrBase << true);
4266           return BuildMemberInitializer(Member, Init, IdLoc);
4267         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4268           const CXXBaseSpecifier *DirectBaseSpec;
4269           const CXXBaseSpecifier *VirtualBaseSpec;
4270           if (FindBaseInitializer(*this, ClassDecl,
4271                                   Context.getTypeDeclType(Type),
4272                                   DirectBaseSpec, VirtualBaseSpec)) {
4273             // We have found a direct or virtual base class with a
4274             // similar name to what was typed; complain and initialize
4275             // that base class.
4276             diagnoseTypo(Corr,
4277                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4278                            << MemberOrBase << false,
4279                          PDiag() /*Suppress note, we provide our own.*/);
4280 
4281             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4282                                                               : VirtualBaseSpec;
4283             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4284                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4285 
4286             TyD = Type;
4287           }
4288         }
4289       }
4290 
4291       if (!TyD && BaseType.isNull()) {
4292         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4293           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4294         return true;
4295       }
4296     }
4297 
4298     if (BaseType.isNull()) {
4299       BaseType = Context.getTypeDeclType(TyD);
4300       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4301       if (SS.isSet()) {
4302         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4303                                              BaseType);
4304         TInfo = Context.CreateTypeSourceInfo(BaseType);
4305         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4306         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4307         TL.setElaboratedKeywordLoc(SourceLocation());
4308         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4309       }
4310     }
4311   }
4312 
4313   if (!TInfo)
4314     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4315 
4316   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4317 }
4318 
4319 MemInitResult
4320 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4321                              SourceLocation IdLoc) {
4322   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4323   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4324   assert((DirectMember || IndirectMember) &&
4325          "Member must be a FieldDecl or IndirectFieldDecl");
4326 
4327   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4328     return true;
4329 
4330   if (Member->isInvalidDecl())
4331     return true;
4332 
4333   MultiExprArg Args;
4334   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4335     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4336   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4337     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4338   } else {
4339     // Template instantiation doesn't reconstruct ParenListExprs for us.
4340     Args = Init;
4341   }
4342 
4343   SourceRange InitRange = Init->getSourceRange();
4344 
4345   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4346     // Can't check initialization for a member of dependent type or when
4347     // any of the arguments are type-dependent expressions.
4348     DiscardCleanupsInEvaluationContext();
4349   } else {
4350     bool InitList = false;
4351     if (isa<InitListExpr>(Init)) {
4352       InitList = true;
4353       Args = Init;
4354     }
4355 
4356     // Initialize the member.
4357     InitializedEntity MemberEntity =
4358       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4359                    : InitializedEntity::InitializeMember(IndirectMember,
4360                                                          nullptr);
4361     InitializationKind Kind =
4362         InitList ? InitializationKind::CreateDirectList(
4363                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4364                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4365                                                     InitRange.getEnd());
4366 
4367     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4368     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4369                                             nullptr);
4370     if (MemberInit.isInvalid())
4371       return true;
4372 
4373     // C++11 [class.base.init]p7:
4374     //   The initialization of each base and member constitutes a
4375     //   full-expression.
4376     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4377                                      /*DiscardedValue*/ false);
4378     if (MemberInit.isInvalid())
4379       return true;
4380 
4381     Init = MemberInit.get();
4382   }
4383 
4384   if (DirectMember) {
4385     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4386                                             InitRange.getBegin(), Init,
4387                                             InitRange.getEnd());
4388   } else {
4389     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4390                                             InitRange.getBegin(), Init,
4391                                             InitRange.getEnd());
4392   }
4393 }
4394 
4395 MemInitResult
4396 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4397                                  CXXRecordDecl *ClassDecl) {
4398   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4399   if (!LangOpts.CPlusPlus11)
4400     return Diag(NameLoc, diag::err_delegating_ctor)
4401       << TInfo->getTypeLoc().getLocalSourceRange();
4402   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4403 
4404   bool InitList = true;
4405   MultiExprArg Args = Init;
4406   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4407     InitList = false;
4408     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4409   }
4410 
4411   SourceRange InitRange = Init->getSourceRange();
4412   // Initialize the object.
4413   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4414                                      QualType(ClassDecl->getTypeForDecl(), 0));
4415   InitializationKind Kind =
4416       InitList ? InitializationKind::CreateDirectList(
4417                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4418                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4419                                                   InitRange.getEnd());
4420   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4421   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4422                                               Args, nullptr);
4423   if (DelegationInit.isInvalid())
4424     return true;
4425 
4426   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4427          "Delegating constructor with no target?");
4428 
4429   // C++11 [class.base.init]p7:
4430   //   The initialization of each base and member constitutes a
4431   //   full-expression.
4432   DelegationInit = ActOnFinishFullExpr(
4433       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4434   if (DelegationInit.isInvalid())
4435     return true;
4436 
4437   // If we are in a dependent context, template instantiation will
4438   // perform this type-checking again. Just save the arguments that we
4439   // received in a ParenListExpr.
4440   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4441   // of the information that we have about the base
4442   // initializer. However, deconstructing the ASTs is a dicey process,
4443   // and this approach is far more likely to get the corner cases right.
4444   if (CurContext->isDependentContext())
4445     DelegationInit = Init;
4446 
4447   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4448                                           DelegationInit.getAs<Expr>(),
4449                                           InitRange.getEnd());
4450 }
4451 
4452 MemInitResult
4453 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4454                            Expr *Init, CXXRecordDecl *ClassDecl,
4455                            SourceLocation EllipsisLoc) {
4456   SourceLocation BaseLoc
4457     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4458 
4459   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4460     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4461              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4462 
4463   // C++ [class.base.init]p2:
4464   //   [...] Unless the mem-initializer-id names a nonstatic data
4465   //   member of the constructor's class or a direct or virtual base
4466   //   of that class, the mem-initializer is ill-formed. A
4467   //   mem-initializer-list can initialize a base class using any
4468   //   name that denotes that base class type.
4469   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4470 
4471   SourceRange InitRange = Init->getSourceRange();
4472   if (EllipsisLoc.isValid()) {
4473     // This is a pack expansion.
4474     if (!BaseType->containsUnexpandedParameterPack())  {
4475       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4476         << SourceRange(BaseLoc, InitRange.getEnd());
4477 
4478       EllipsisLoc = SourceLocation();
4479     }
4480   } else {
4481     // Check for any unexpanded parameter packs.
4482     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4483       return true;
4484 
4485     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4486       return true;
4487   }
4488 
4489   // Check for direct and virtual base classes.
4490   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4491   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4492   if (!Dependent) {
4493     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4494                                        BaseType))
4495       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4496 
4497     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4498                         VirtualBaseSpec);
4499 
4500     // C++ [base.class.init]p2:
4501     // Unless the mem-initializer-id names a nonstatic data member of the
4502     // constructor's class or a direct or virtual base of that class, the
4503     // mem-initializer is ill-formed.
4504     if (!DirectBaseSpec && !VirtualBaseSpec) {
4505       // If the class has any dependent bases, then it's possible that
4506       // one of those types will resolve to the same type as
4507       // BaseType. Therefore, just treat this as a dependent base
4508       // class initialization.  FIXME: Should we try to check the
4509       // initialization anyway? It seems odd.
4510       if (ClassDecl->hasAnyDependentBases())
4511         Dependent = true;
4512       else
4513         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4514           << BaseType << Context.getTypeDeclType(ClassDecl)
4515           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4516     }
4517   }
4518 
4519   if (Dependent) {
4520     DiscardCleanupsInEvaluationContext();
4521 
4522     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4523                                             /*IsVirtual=*/false,
4524                                             InitRange.getBegin(), Init,
4525                                             InitRange.getEnd(), EllipsisLoc);
4526   }
4527 
4528   // C++ [base.class.init]p2:
4529   //   If a mem-initializer-id is ambiguous because it designates both
4530   //   a direct non-virtual base class and an inherited virtual base
4531   //   class, the mem-initializer is ill-formed.
4532   if (DirectBaseSpec && VirtualBaseSpec)
4533     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4534       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4535 
4536   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4537   if (!BaseSpec)
4538     BaseSpec = VirtualBaseSpec;
4539 
4540   // Initialize the base.
4541   bool InitList = true;
4542   MultiExprArg Args = Init;
4543   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4544     InitList = false;
4545     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4546   }
4547 
4548   InitializedEntity BaseEntity =
4549     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4550   InitializationKind Kind =
4551       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4552                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4553                                                   InitRange.getEnd());
4554   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4555   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4556   if (BaseInit.isInvalid())
4557     return true;
4558 
4559   // C++11 [class.base.init]p7:
4560   //   The initialization of each base and member constitutes a
4561   //   full-expression.
4562   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4563                                  /*DiscardedValue*/ false);
4564   if (BaseInit.isInvalid())
4565     return true;
4566 
4567   // If we are in a dependent context, template instantiation will
4568   // perform this type-checking again. Just save the arguments that we
4569   // received in a ParenListExpr.
4570   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4571   // of the information that we have about the base
4572   // initializer. However, deconstructing the ASTs is a dicey process,
4573   // and this approach is far more likely to get the corner cases right.
4574   if (CurContext->isDependentContext())
4575     BaseInit = Init;
4576 
4577   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4578                                           BaseSpec->isVirtual(),
4579                                           InitRange.getBegin(),
4580                                           BaseInit.getAs<Expr>(),
4581                                           InitRange.getEnd(), EllipsisLoc);
4582 }
4583 
4584 // Create a static_cast\<T&&>(expr).
4585 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4586   if (T.isNull()) T = E->getType();
4587   QualType TargetType = SemaRef.BuildReferenceType(
4588       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4589   SourceLocation ExprLoc = E->getBeginLoc();
4590   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4591       TargetType, ExprLoc);
4592 
4593   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4594                                    SourceRange(ExprLoc, ExprLoc),
4595                                    E->getSourceRange()).get();
4596 }
4597 
4598 /// ImplicitInitializerKind - How an implicit base or member initializer should
4599 /// initialize its base or member.
4600 enum ImplicitInitializerKind {
4601   IIK_Default,
4602   IIK_Copy,
4603   IIK_Move,
4604   IIK_Inherit
4605 };
4606 
4607 static bool
4608 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4609                              ImplicitInitializerKind ImplicitInitKind,
4610                              CXXBaseSpecifier *BaseSpec,
4611                              bool IsInheritedVirtualBase,
4612                              CXXCtorInitializer *&CXXBaseInit) {
4613   InitializedEntity InitEntity
4614     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4615                                         IsInheritedVirtualBase);
4616 
4617   ExprResult BaseInit;
4618 
4619   switch (ImplicitInitKind) {
4620   case IIK_Inherit:
4621   case IIK_Default: {
4622     InitializationKind InitKind
4623       = InitializationKind::CreateDefault(Constructor->getLocation());
4624     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4625     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4626     break;
4627   }
4628 
4629   case IIK_Move:
4630   case IIK_Copy: {
4631     bool Moving = ImplicitInitKind == IIK_Move;
4632     ParmVarDecl *Param = Constructor->getParamDecl(0);
4633     QualType ParamType = Param->getType().getNonReferenceType();
4634 
4635     Expr *CopyCtorArg =
4636       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4637                           SourceLocation(), Param, false,
4638                           Constructor->getLocation(), ParamType,
4639                           VK_LValue, nullptr);
4640 
4641     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4642 
4643     // Cast to the base class to avoid ambiguities.
4644     QualType ArgTy =
4645       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4646                                        ParamType.getQualifiers());
4647 
4648     if (Moving) {
4649       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4650     }
4651 
4652     CXXCastPath BasePath;
4653     BasePath.push_back(BaseSpec);
4654     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4655                                             CK_UncheckedDerivedToBase,
4656                                             Moving ? VK_XValue : VK_LValue,
4657                                             &BasePath).get();
4658 
4659     InitializationKind InitKind
4660       = InitializationKind::CreateDirect(Constructor->getLocation(),
4661                                          SourceLocation(), SourceLocation());
4662     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4663     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4664     break;
4665   }
4666   }
4667 
4668   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4669   if (BaseInit.isInvalid())
4670     return true;
4671 
4672   CXXBaseInit =
4673     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4674                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4675                                                         SourceLocation()),
4676                                              BaseSpec->isVirtual(),
4677                                              SourceLocation(),
4678                                              BaseInit.getAs<Expr>(),
4679                                              SourceLocation(),
4680                                              SourceLocation());
4681 
4682   return false;
4683 }
4684 
4685 static bool RefersToRValueRef(Expr *MemRef) {
4686   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4687   return Referenced->getType()->isRValueReferenceType();
4688 }
4689 
4690 static bool
4691 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4692                                ImplicitInitializerKind ImplicitInitKind,
4693                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4694                                CXXCtorInitializer *&CXXMemberInit) {
4695   if (Field->isInvalidDecl())
4696     return true;
4697 
4698   SourceLocation Loc = Constructor->getLocation();
4699 
4700   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4701     bool Moving = ImplicitInitKind == IIK_Move;
4702     ParmVarDecl *Param = Constructor->getParamDecl(0);
4703     QualType ParamType = Param->getType().getNonReferenceType();
4704 
4705     // Suppress copying zero-width bitfields.
4706     if (Field->isZeroLengthBitField(SemaRef.Context))
4707       return false;
4708 
4709     Expr *MemberExprBase =
4710       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4711                           SourceLocation(), Param, false,
4712                           Loc, ParamType, VK_LValue, nullptr);
4713 
4714     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4715 
4716     if (Moving) {
4717       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4718     }
4719 
4720     // Build a reference to this field within the parameter.
4721     CXXScopeSpec SS;
4722     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4723                               Sema::LookupMemberName);
4724     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4725                                   : cast<ValueDecl>(Field), AS_public);
4726     MemberLookup.resolveKind();
4727     ExprResult CtorArg
4728       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4729                                          ParamType, Loc,
4730                                          /*IsArrow=*/false,
4731                                          SS,
4732                                          /*TemplateKWLoc=*/SourceLocation(),
4733                                          /*FirstQualifierInScope=*/nullptr,
4734                                          MemberLookup,
4735                                          /*TemplateArgs=*/nullptr,
4736                                          /*S*/nullptr);
4737     if (CtorArg.isInvalid())
4738       return true;
4739 
4740     // C++11 [class.copy]p15:
4741     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4742     //     with static_cast<T&&>(x.m);
4743     if (RefersToRValueRef(CtorArg.get())) {
4744       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4745     }
4746 
4747     InitializedEntity Entity =
4748         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4749                                                        /*Implicit*/ true)
4750                  : InitializedEntity::InitializeMember(Field, nullptr,
4751                                                        /*Implicit*/ true);
4752 
4753     // Direct-initialize to use the copy constructor.
4754     InitializationKind InitKind =
4755       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4756 
4757     Expr *CtorArgE = CtorArg.getAs<Expr>();
4758     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4759     ExprResult MemberInit =
4760         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4761     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4762     if (MemberInit.isInvalid())
4763       return true;
4764 
4765     if (Indirect)
4766       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4767           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4768     else
4769       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4770           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4771     return false;
4772   }
4773 
4774   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4775          "Unhandled implicit init kind!");
4776 
4777   QualType FieldBaseElementType =
4778     SemaRef.Context.getBaseElementType(Field->getType());
4779 
4780   if (FieldBaseElementType->isRecordType()) {
4781     InitializedEntity InitEntity =
4782         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4783                                                        /*Implicit*/ true)
4784                  : InitializedEntity::InitializeMember(Field, nullptr,
4785                                                        /*Implicit*/ true);
4786     InitializationKind InitKind =
4787       InitializationKind::CreateDefault(Loc);
4788 
4789     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4790     ExprResult MemberInit =
4791       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4792 
4793     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4794     if (MemberInit.isInvalid())
4795       return true;
4796 
4797     if (Indirect)
4798       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4799                                                                Indirect, Loc,
4800                                                                Loc,
4801                                                                MemberInit.get(),
4802                                                                Loc);
4803     else
4804       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4805                                                                Field, Loc, Loc,
4806                                                                MemberInit.get(),
4807                                                                Loc);
4808     return false;
4809   }
4810 
4811   if (!Field->getParent()->isUnion()) {
4812     if (FieldBaseElementType->isReferenceType()) {
4813       SemaRef.Diag(Constructor->getLocation(),
4814                    diag::err_uninitialized_member_in_ctor)
4815       << (int)Constructor->isImplicit()
4816       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4817       << 0 << Field->getDeclName();
4818       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4819       return true;
4820     }
4821 
4822     if (FieldBaseElementType.isConstQualified()) {
4823       SemaRef.Diag(Constructor->getLocation(),
4824                    diag::err_uninitialized_member_in_ctor)
4825       << (int)Constructor->isImplicit()
4826       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4827       << 1 << Field->getDeclName();
4828       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4829       return true;
4830     }
4831   }
4832 
4833   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4834     // ARC and Weak:
4835     //   Default-initialize Objective-C pointers to NULL.
4836     CXXMemberInit
4837       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4838                                                  Loc, Loc,
4839                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4840                                                  Loc);
4841     return false;
4842   }
4843 
4844   // Nothing to initialize.
4845   CXXMemberInit = nullptr;
4846   return false;
4847 }
4848 
4849 namespace {
4850 struct BaseAndFieldInfo {
4851   Sema &S;
4852   CXXConstructorDecl *Ctor;
4853   bool AnyErrorsInInits;
4854   ImplicitInitializerKind IIK;
4855   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4856   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4857   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4858 
4859   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4860     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4861     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4862     if (Ctor->getInheritedConstructor())
4863       IIK = IIK_Inherit;
4864     else if (Generated && Ctor->isCopyConstructor())
4865       IIK = IIK_Copy;
4866     else if (Generated && Ctor->isMoveConstructor())
4867       IIK = IIK_Move;
4868     else
4869       IIK = IIK_Default;
4870   }
4871 
4872   bool isImplicitCopyOrMove() const {
4873     switch (IIK) {
4874     case IIK_Copy:
4875     case IIK_Move:
4876       return true;
4877 
4878     case IIK_Default:
4879     case IIK_Inherit:
4880       return false;
4881     }
4882 
4883     llvm_unreachable("Invalid ImplicitInitializerKind!");
4884   }
4885 
4886   bool addFieldInitializer(CXXCtorInitializer *Init) {
4887     AllToInit.push_back(Init);
4888 
4889     // Check whether this initializer makes the field "used".
4890     if (Init->getInit()->HasSideEffects(S.Context))
4891       S.UnusedPrivateFields.remove(Init->getAnyMember());
4892 
4893     return false;
4894   }
4895 
4896   bool isInactiveUnionMember(FieldDecl *Field) {
4897     RecordDecl *Record = Field->getParent();
4898     if (!Record->isUnion())
4899       return false;
4900 
4901     if (FieldDecl *Active =
4902             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4903       return Active != Field->getCanonicalDecl();
4904 
4905     // In an implicit copy or move constructor, ignore any in-class initializer.
4906     if (isImplicitCopyOrMove())
4907       return true;
4908 
4909     // If there's no explicit initialization, the field is active only if it
4910     // has an in-class initializer...
4911     if (Field->hasInClassInitializer())
4912       return false;
4913     // ... or it's an anonymous struct or union whose class has an in-class
4914     // initializer.
4915     if (!Field->isAnonymousStructOrUnion())
4916       return true;
4917     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4918     return !FieldRD->hasInClassInitializer();
4919   }
4920 
4921   /// Determine whether the given field is, or is within, a union member
4922   /// that is inactive (because there was an initializer given for a different
4923   /// member of the union, or because the union was not initialized at all).
4924   bool isWithinInactiveUnionMember(FieldDecl *Field,
4925                                    IndirectFieldDecl *Indirect) {
4926     if (!Indirect)
4927       return isInactiveUnionMember(Field);
4928 
4929     for (auto *C : Indirect->chain()) {
4930       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4931       if (Field && isInactiveUnionMember(Field))
4932         return true;
4933     }
4934     return false;
4935   }
4936 };
4937 }
4938 
4939 /// Determine whether the given type is an incomplete or zero-lenfgth
4940 /// array type.
4941 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4942   if (T->isIncompleteArrayType())
4943     return true;
4944 
4945   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4946     if (!ArrayT->getSize())
4947       return true;
4948 
4949     T = ArrayT->getElementType();
4950   }
4951 
4952   return false;
4953 }
4954 
4955 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4956                                     FieldDecl *Field,
4957                                     IndirectFieldDecl *Indirect = nullptr) {
4958   if (Field->isInvalidDecl())
4959     return false;
4960 
4961   // Overwhelmingly common case: we have a direct initializer for this field.
4962   if (CXXCtorInitializer *Init =
4963           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4964     return Info.addFieldInitializer(Init);
4965 
4966   // C++11 [class.base.init]p8:
4967   //   if the entity is a non-static data member that has a
4968   //   brace-or-equal-initializer and either
4969   //   -- the constructor's class is a union and no other variant member of that
4970   //      union is designated by a mem-initializer-id or
4971   //   -- the constructor's class is not a union, and, if the entity is a member
4972   //      of an anonymous union, no other member of that union is designated by
4973   //      a mem-initializer-id,
4974   //   the entity is initialized as specified in [dcl.init].
4975   //
4976   // We also apply the same rules to handle anonymous structs within anonymous
4977   // unions.
4978   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4979     return false;
4980 
4981   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4982     ExprResult DIE =
4983         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4984     if (DIE.isInvalid())
4985       return true;
4986 
4987     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4988     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4989 
4990     CXXCtorInitializer *Init;
4991     if (Indirect)
4992       Init = new (SemaRef.Context)
4993           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4994                              SourceLocation(), DIE.get(), SourceLocation());
4995     else
4996       Init = new (SemaRef.Context)
4997           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4998                              SourceLocation(), DIE.get(), SourceLocation());
4999     return Info.addFieldInitializer(Init);
5000   }
5001 
5002   // Don't initialize incomplete or zero-length arrays.
5003   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5004     return false;
5005 
5006   // Don't try to build an implicit initializer if there were semantic
5007   // errors in any of the initializers (and therefore we might be
5008   // missing some that the user actually wrote).
5009   if (Info.AnyErrorsInInits)
5010     return false;
5011 
5012   CXXCtorInitializer *Init = nullptr;
5013   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5014                                      Indirect, Init))
5015     return true;
5016 
5017   if (!Init)
5018     return false;
5019 
5020   return Info.addFieldInitializer(Init);
5021 }
5022 
5023 bool
5024 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5025                                CXXCtorInitializer *Initializer) {
5026   assert(Initializer->isDelegatingInitializer());
5027   Constructor->setNumCtorInitializers(1);
5028   CXXCtorInitializer **initializer =
5029     new (Context) CXXCtorInitializer*[1];
5030   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5031   Constructor->setCtorInitializers(initializer);
5032 
5033   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5034     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5035     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5036   }
5037 
5038   DelegatingCtorDecls.push_back(Constructor);
5039 
5040   DiagnoseUninitializedFields(*this, Constructor);
5041 
5042   return false;
5043 }
5044 
5045 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5046                                ArrayRef<CXXCtorInitializer *> Initializers) {
5047   if (Constructor->isDependentContext()) {
5048     // Just store the initializers as written, they will be checked during
5049     // instantiation.
5050     if (!Initializers.empty()) {
5051       Constructor->setNumCtorInitializers(Initializers.size());
5052       CXXCtorInitializer **baseOrMemberInitializers =
5053         new (Context) CXXCtorInitializer*[Initializers.size()];
5054       memcpy(baseOrMemberInitializers, Initializers.data(),
5055              Initializers.size() * sizeof(CXXCtorInitializer*));
5056       Constructor->setCtorInitializers(baseOrMemberInitializers);
5057     }
5058 
5059     // Let template instantiation know whether we had errors.
5060     if (AnyErrors)
5061       Constructor->setInvalidDecl();
5062 
5063     return false;
5064   }
5065 
5066   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5067 
5068   // We need to build the initializer AST according to order of construction
5069   // and not what user specified in the Initializers list.
5070   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5071   if (!ClassDecl)
5072     return true;
5073 
5074   bool HadError = false;
5075 
5076   for (unsigned i = 0; i < Initializers.size(); i++) {
5077     CXXCtorInitializer *Member = Initializers[i];
5078 
5079     if (Member->isBaseInitializer())
5080       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5081     else {
5082       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5083 
5084       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5085         for (auto *C : F->chain()) {
5086           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5087           if (FD && FD->getParent()->isUnion())
5088             Info.ActiveUnionMember.insert(std::make_pair(
5089                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5090         }
5091       } else if (FieldDecl *FD = Member->getMember()) {
5092         if (FD->getParent()->isUnion())
5093           Info.ActiveUnionMember.insert(std::make_pair(
5094               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5095       }
5096     }
5097   }
5098 
5099   // Keep track of the direct virtual bases.
5100   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5101   for (auto &I : ClassDecl->bases()) {
5102     if (I.isVirtual())
5103       DirectVBases.insert(&I);
5104   }
5105 
5106   // Push virtual bases before others.
5107   for (auto &VBase : ClassDecl->vbases()) {
5108     if (CXXCtorInitializer *Value
5109         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5110       // [class.base.init]p7, per DR257:
5111       //   A mem-initializer where the mem-initializer-id names a virtual base
5112       //   class is ignored during execution of a constructor of any class that
5113       //   is not the most derived class.
5114       if (ClassDecl->isAbstract()) {
5115         // FIXME: Provide a fixit to remove the base specifier. This requires
5116         // tracking the location of the associated comma for a base specifier.
5117         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5118           << VBase.getType() << ClassDecl;
5119         DiagnoseAbstractType(ClassDecl);
5120       }
5121 
5122       Info.AllToInit.push_back(Value);
5123     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5124       // [class.base.init]p8, per DR257:
5125       //   If a given [...] base class is not named by a mem-initializer-id
5126       //   [...] and the entity is not a virtual base class of an abstract
5127       //   class, then [...] the entity is default-initialized.
5128       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5129       CXXCtorInitializer *CXXBaseInit;
5130       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5131                                        &VBase, IsInheritedVirtualBase,
5132                                        CXXBaseInit)) {
5133         HadError = true;
5134         continue;
5135       }
5136 
5137       Info.AllToInit.push_back(CXXBaseInit);
5138     }
5139   }
5140 
5141   // Non-virtual bases.
5142   for (auto &Base : ClassDecl->bases()) {
5143     // Virtuals are in the virtual base list and already constructed.
5144     if (Base.isVirtual())
5145       continue;
5146 
5147     if (CXXCtorInitializer *Value
5148           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5149       Info.AllToInit.push_back(Value);
5150     } else if (!AnyErrors) {
5151       CXXCtorInitializer *CXXBaseInit;
5152       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5153                                        &Base, /*IsInheritedVirtualBase=*/false,
5154                                        CXXBaseInit)) {
5155         HadError = true;
5156         continue;
5157       }
5158 
5159       Info.AllToInit.push_back(CXXBaseInit);
5160     }
5161   }
5162 
5163   // Fields.
5164   for (auto *Mem : ClassDecl->decls()) {
5165     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5166       // C++ [class.bit]p2:
5167       //   A declaration for a bit-field that omits the identifier declares an
5168       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5169       //   initialized.
5170       if (F->isUnnamedBitfield())
5171         continue;
5172 
5173       // If we're not generating the implicit copy/move constructor, then we'll
5174       // handle anonymous struct/union fields based on their individual
5175       // indirect fields.
5176       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5177         continue;
5178 
5179       if (CollectFieldInitializer(*this, Info, F))
5180         HadError = true;
5181       continue;
5182     }
5183 
5184     // Beyond this point, we only consider default initialization.
5185     if (Info.isImplicitCopyOrMove())
5186       continue;
5187 
5188     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5189       if (F->getType()->isIncompleteArrayType()) {
5190         assert(ClassDecl->hasFlexibleArrayMember() &&
5191                "Incomplete array type is not valid");
5192         continue;
5193       }
5194 
5195       // Initialize each field of an anonymous struct individually.
5196       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5197         HadError = true;
5198 
5199       continue;
5200     }
5201   }
5202 
5203   unsigned NumInitializers = Info.AllToInit.size();
5204   if (NumInitializers > 0) {
5205     Constructor->setNumCtorInitializers(NumInitializers);
5206     CXXCtorInitializer **baseOrMemberInitializers =
5207       new (Context) CXXCtorInitializer*[NumInitializers];
5208     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5209            NumInitializers * sizeof(CXXCtorInitializer*));
5210     Constructor->setCtorInitializers(baseOrMemberInitializers);
5211 
5212     // Constructors implicitly reference the base and member
5213     // destructors.
5214     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5215                                            Constructor->getParent());
5216   }
5217 
5218   return HadError;
5219 }
5220 
5221 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5222   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5223     const RecordDecl *RD = RT->getDecl();
5224     if (RD->isAnonymousStructOrUnion()) {
5225       for (auto *Field : RD->fields())
5226         PopulateKeysForFields(Field, IdealInits);
5227       return;
5228     }
5229   }
5230   IdealInits.push_back(Field->getCanonicalDecl());
5231 }
5232 
5233 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5234   return Context.getCanonicalType(BaseType).getTypePtr();
5235 }
5236 
5237 static const void *GetKeyForMember(ASTContext &Context,
5238                                    CXXCtorInitializer *Member) {
5239   if (!Member->isAnyMemberInitializer())
5240     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5241 
5242   return Member->getAnyMember()->getCanonicalDecl();
5243 }
5244 
5245 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5246                                  const CXXCtorInitializer *Previous,
5247                                  const CXXCtorInitializer *Current) {
5248   if (Previous->isAnyMemberInitializer())
5249     Diag << 0 << Previous->getAnyMember();
5250   else
5251     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5252 
5253   if (Current->isAnyMemberInitializer())
5254     Diag << 0 << Current->getAnyMember();
5255   else
5256     Diag << 1 << Current->getTypeSourceInfo()->getType();
5257 }
5258 
5259 static void DiagnoseBaseOrMemInitializerOrder(
5260     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5261     ArrayRef<CXXCtorInitializer *> Inits) {
5262   if (Constructor->getDeclContext()->isDependentContext())
5263     return;
5264 
5265   // Don't check initializers order unless the warning is enabled at the
5266   // location of at least one initializer.
5267   bool ShouldCheckOrder = false;
5268   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5269     CXXCtorInitializer *Init = Inits[InitIndex];
5270     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5271                                  Init->getSourceLocation())) {
5272       ShouldCheckOrder = true;
5273       break;
5274     }
5275   }
5276   if (!ShouldCheckOrder)
5277     return;
5278 
5279   // Build the list of bases and members in the order that they'll
5280   // actually be initialized.  The explicit initializers should be in
5281   // this same order but may be missing things.
5282   SmallVector<const void*, 32> IdealInitKeys;
5283 
5284   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5285 
5286   // 1. Virtual bases.
5287   for (const auto &VBase : ClassDecl->vbases())
5288     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5289 
5290   // 2. Non-virtual bases.
5291   for (const auto &Base : ClassDecl->bases()) {
5292     if (Base.isVirtual())
5293       continue;
5294     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5295   }
5296 
5297   // 3. Direct fields.
5298   for (auto *Field : ClassDecl->fields()) {
5299     if (Field->isUnnamedBitfield())
5300       continue;
5301 
5302     PopulateKeysForFields(Field, IdealInitKeys);
5303   }
5304 
5305   unsigned NumIdealInits = IdealInitKeys.size();
5306   unsigned IdealIndex = 0;
5307 
5308   // Track initializers that are in an incorrect order for either a warning or
5309   // note if multiple ones occur.
5310   SmallVector<unsigned> WarnIndexes;
5311   // Correlates the index of an initializer in the init-list to the index of
5312   // the field/base in the class.
5313   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5314 
5315   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5316     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5317 
5318     // Scan forward to try to find this initializer in the idealized
5319     // initializers list.
5320     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5321       if (InitKey == IdealInitKeys[IdealIndex])
5322         break;
5323 
5324     // If we didn't find this initializer, it must be because we
5325     // scanned past it on a previous iteration.  That can only
5326     // happen if we're out of order;  emit a warning.
5327     if (IdealIndex == NumIdealInits && InitIndex) {
5328       WarnIndexes.push_back(InitIndex);
5329 
5330       // Move back to the initializer's location in the ideal list.
5331       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5332         if (InitKey == IdealInitKeys[IdealIndex])
5333           break;
5334 
5335       assert(IdealIndex < NumIdealInits &&
5336              "initializer not found in initializer list");
5337     }
5338     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5339   }
5340 
5341   if (WarnIndexes.empty())
5342     return;
5343 
5344   // Sort based on the ideal order, first in the pair.
5345   llvm::sort(CorrelatedInitOrder,
5346              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5347 
5348   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5349   // emit the diagnostic before we can try adding notes.
5350   {
5351     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5352         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5353         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5354                                 : diag::warn_some_initializers_out_of_order);
5355 
5356     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5357       if (CorrelatedInitOrder[I].second == I)
5358         continue;
5359       // Ideally we would be using InsertFromRange here, but clang doesn't
5360       // appear to handle InsertFromRange correctly when the source range is
5361       // modified by another fix-it.
5362       D << FixItHint::CreateReplacement(
5363           Inits[I]->getSourceRange(),
5364           Lexer::getSourceText(
5365               CharSourceRange::getTokenRange(
5366                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5367               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5368     }
5369 
5370     // If there is only 1 item out of order, the warning expects the name and
5371     // type of each being added to it.
5372     if (WarnIndexes.size() == 1) {
5373       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5374                            Inits[WarnIndexes.front()]);
5375       return;
5376     }
5377   }
5378   // More than 1 item to warn, create notes letting the user know which ones
5379   // are bad.
5380   for (unsigned WarnIndex : WarnIndexes) {
5381     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5382     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5383                           diag::note_initializer_out_of_order);
5384     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5385     D << PrevInit->getSourceRange();
5386   }
5387 }
5388 
5389 namespace {
5390 bool CheckRedundantInit(Sema &S,
5391                         CXXCtorInitializer *Init,
5392                         CXXCtorInitializer *&PrevInit) {
5393   if (!PrevInit) {
5394     PrevInit = Init;
5395     return false;
5396   }
5397 
5398   if (FieldDecl *Field = Init->getAnyMember())
5399     S.Diag(Init->getSourceLocation(),
5400            diag::err_multiple_mem_initialization)
5401       << Field->getDeclName()
5402       << Init->getSourceRange();
5403   else {
5404     const Type *BaseClass = Init->getBaseClass();
5405     assert(BaseClass && "neither field nor base");
5406     S.Diag(Init->getSourceLocation(),
5407            diag::err_multiple_base_initialization)
5408       << QualType(BaseClass, 0)
5409       << Init->getSourceRange();
5410   }
5411   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5412     << 0 << PrevInit->getSourceRange();
5413 
5414   return true;
5415 }
5416 
5417 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5418 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5419 
5420 bool CheckRedundantUnionInit(Sema &S,
5421                              CXXCtorInitializer *Init,
5422                              RedundantUnionMap &Unions) {
5423   FieldDecl *Field = Init->getAnyMember();
5424   RecordDecl *Parent = Field->getParent();
5425   NamedDecl *Child = Field;
5426 
5427   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5428     if (Parent->isUnion()) {
5429       UnionEntry &En = Unions[Parent];
5430       if (En.first && En.first != Child) {
5431         S.Diag(Init->getSourceLocation(),
5432                diag::err_multiple_mem_union_initialization)
5433           << Field->getDeclName()
5434           << Init->getSourceRange();
5435         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5436           << 0 << En.second->getSourceRange();
5437         return true;
5438       }
5439       if (!En.first) {
5440         En.first = Child;
5441         En.second = Init;
5442       }
5443       if (!Parent->isAnonymousStructOrUnion())
5444         return false;
5445     }
5446 
5447     Child = Parent;
5448     Parent = cast<RecordDecl>(Parent->getDeclContext());
5449   }
5450 
5451   return false;
5452 }
5453 } // namespace
5454 
5455 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5456 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5457                                 SourceLocation ColonLoc,
5458                                 ArrayRef<CXXCtorInitializer*> MemInits,
5459                                 bool AnyErrors) {
5460   if (!ConstructorDecl)
5461     return;
5462 
5463   AdjustDeclIfTemplate(ConstructorDecl);
5464 
5465   CXXConstructorDecl *Constructor
5466     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5467 
5468   if (!Constructor) {
5469     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5470     return;
5471   }
5472 
5473   // Mapping for the duplicate initializers check.
5474   // For member initializers, this is keyed with a FieldDecl*.
5475   // For base initializers, this is keyed with a Type*.
5476   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5477 
5478   // Mapping for the inconsistent anonymous-union initializers check.
5479   RedundantUnionMap MemberUnions;
5480 
5481   bool HadError = false;
5482   for (unsigned i = 0; i < MemInits.size(); i++) {
5483     CXXCtorInitializer *Init = MemInits[i];
5484 
5485     // Set the source order index.
5486     Init->setSourceOrder(i);
5487 
5488     if (Init->isAnyMemberInitializer()) {
5489       const void *Key = GetKeyForMember(Context, Init);
5490       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5491           CheckRedundantUnionInit(*this, Init, MemberUnions))
5492         HadError = true;
5493     } else if (Init->isBaseInitializer()) {
5494       const void *Key = GetKeyForMember(Context, Init);
5495       if (CheckRedundantInit(*this, Init, Members[Key]))
5496         HadError = true;
5497     } else {
5498       assert(Init->isDelegatingInitializer());
5499       // This must be the only initializer
5500       if (MemInits.size() != 1) {
5501         Diag(Init->getSourceLocation(),
5502              diag::err_delegating_initializer_alone)
5503           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5504         // We will treat this as being the only initializer.
5505       }
5506       SetDelegatingInitializer(Constructor, MemInits[i]);
5507       // Return immediately as the initializer is set.
5508       return;
5509     }
5510   }
5511 
5512   if (HadError)
5513     return;
5514 
5515   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5516 
5517   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5518 
5519   DiagnoseUninitializedFields(*this, Constructor);
5520 }
5521 
5522 void
5523 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5524                                              CXXRecordDecl *ClassDecl) {
5525   // Ignore dependent contexts. Also ignore unions, since their members never
5526   // have destructors implicitly called.
5527   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5528     return;
5529 
5530   // FIXME: all the access-control diagnostics are positioned on the
5531   // field/base declaration.  That's probably good; that said, the
5532   // user might reasonably want to know why the destructor is being
5533   // emitted, and we currently don't say.
5534 
5535   // Non-static data members.
5536   for (auto *Field : ClassDecl->fields()) {
5537     if (Field->isInvalidDecl())
5538       continue;
5539 
5540     // Don't destroy incomplete or zero-length arrays.
5541     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5542       continue;
5543 
5544     QualType FieldType = Context.getBaseElementType(Field->getType());
5545 
5546     const RecordType* RT = FieldType->getAs<RecordType>();
5547     if (!RT)
5548       continue;
5549 
5550     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5551     if (FieldClassDecl->isInvalidDecl())
5552       continue;
5553     if (FieldClassDecl->hasIrrelevantDestructor())
5554       continue;
5555     // The destructor for an implicit anonymous union member is never invoked.
5556     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5557       continue;
5558 
5559     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5560     assert(Dtor && "No dtor found for FieldClassDecl!");
5561     CheckDestructorAccess(Field->getLocation(), Dtor,
5562                           PDiag(diag::err_access_dtor_field)
5563                             << Field->getDeclName()
5564                             << FieldType);
5565 
5566     MarkFunctionReferenced(Location, Dtor);
5567     DiagnoseUseOfDecl(Dtor, Location);
5568   }
5569 
5570   // We only potentially invoke the destructors of potentially constructed
5571   // subobjects.
5572   bool VisitVirtualBases = !ClassDecl->isAbstract();
5573 
5574   // If the destructor exists and has already been marked used in the MS ABI,
5575   // then virtual base destructors have already been checked and marked used.
5576   // Skip checking them again to avoid duplicate diagnostics.
5577   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5578     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5579     if (Dtor && Dtor->isUsed())
5580       VisitVirtualBases = false;
5581   }
5582 
5583   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5584 
5585   // Bases.
5586   for (const auto &Base : ClassDecl->bases()) {
5587     const RecordType *RT = Base.getType()->getAs<RecordType>();
5588     if (!RT)
5589       continue;
5590 
5591     // Remember direct virtual bases.
5592     if (Base.isVirtual()) {
5593       if (!VisitVirtualBases)
5594         continue;
5595       DirectVirtualBases.insert(RT);
5596     }
5597 
5598     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5599     // If our base class is invalid, we probably can't get its dtor anyway.
5600     if (BaseClassDecl->isInvalidDecl())
5601       continue;
5602     if (BaseClassDecl->hasIrrelevantDestructor())
5603       continue;
5604 
5605     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5606     assert(Dtor && "No dtor found for BaseClassDecl!");
5607 
5608     // FIXME: caret should be on the start of the class name
5609     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5610                           PDiag(diag::err_access_dtor_base)
5611                               << Base.getType() << Base.getSourceRange(),
5612                           Context.getTypeDeclType(ClassDecl));
5613 
5614     MarkFunctionReferenced(Location, Dtor);
5615     DiagnoseUseOfDecl(Dtor, Location);
5616   }
5617 
5618   if (VisitVirtualBases)
5619     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5620                                          &DirectVirtualBases);
5621 }
5622 
5623 void Sema::MarkVirtualBaseDestructorsReferenced(
5624     SourceLocation Location, CXXRecordDecl *ClassDecl,
5625     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5626   // Virtual bases.
5627   for (const auto &VBase : ClassDecl->vbases()) {
5628     // Bases are always records in a well-formed non-dependent class.
5629     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5630 
5631     // Ignore already visited direct virtual bases.
5632     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5633       continue;
5634 
5635     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5636     // If our base class is invalid, we probably can't get its dtor anyway.
5637     if (BaseClassDecl->isInvalidDecl())
5638       continue;
5639     if (BaseClassDecl->hasIrrelevantDestructor())
5640       continue;
5641 
5642     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5643     assert(Dtor && "No dtor found for BaseClassDecl!");
5644     if (CheckDestructorAccess(
5645             ClassDecl->getLocation(), Dtor,
5646             PDiag(diag::err_access_dtor_vbase)
5647                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5648             Context.getTypeDeclType(ClassDecl)) ==
5649         AR_accessible) {
5650       CheckDerivedToBaseConversion(
5651           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5652           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5653           SourceRange(), DeclarationName(), nullptr);
5654     }
5655 
5656     MarkFunctionReferenced(Location, Dtor);
5657     DiagnoseUseOfDecl(Dtor, Location);
5658   }
5659 }
5660 
5661 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5662   if (!CDtorDecl)
5663     return;
5664 
5665   if (CXXConstructorDecl *Constructor
5666       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5667     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5668     DiagnoseUninitializedFields(*this, Constructor);
5669   }
5670 }
5671 
5672 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5673   if (!getLangOpts().CPlusPlus)
5674     return false;
5675 
5676   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5677   if (!RD)
5678     return false;
5679 
5680   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5681   // class template specialization here, but doing so breaks a lot of code.
5682 
5683   // We can't answer whether something is abstract until it has a
5684   // definition. If it's currently being defined, we'll walk back
5685   // over all the declarations when we have a full definition.
5686   const CXXRecordDecl *Def = RD->getDefinition();
5687   if (!Def || Def->isBeingDefined())
5688     return false;
5689 
5690   return RD->isAbstract();
5691 }
5692 
5693 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5694                                   TypeDiagnoser &Diagnoser) {
5695   if (!isAbstractType(Loc, T))
5696     return false;
5697 
5698   T = Context.getBaseElementType(T);
5699   Diagnoser.diagnose(*this, Loc, T);
5700   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5701   return true;
5702 }
5703 
5704 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5705   // Check if we've already emitted the list of pure virtual functions
5706   // for this class.
5707   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5708     return;
5709 
5710   // If the diagnostic is suppressed, don't emit the notes. We're only
5711   // going to emit them once, so try to attach them to a diagnostic we're
5712   // actually going to show.
5713   if (Diags.isLastDiagnosticIgnored())
5714     return;
5715 
5716   CXXFinalOverriderMap FinalOverriders;
5717   RD->getFinalOverriders(FinalOverriders);
5718 
5719   // Keep a set of seen pure methods so we won't diagnose the same method
5720   // more than once.
5721   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5722 
5723   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5724                                    MEnd = FinalOverriders.end();
5725        M != MEnd;
5726        ++M) {
5727     for (OverridingMethods::iterator SO = M->second.begin(),
5728                                   SOEnd = M->second.end();
5729          SO != SOEnd; ++SO) {
5730       // C++ [class.abstract]p4:
5731       //   A class is abstract if it contains or inherits at least one
5732       //   pure virtual function for which the final overrider is pure
5733       //   virtual.
5734 
5735       //
5736       if (SO->second.size() != 1)
5737         continue;
5738 
5739       if (!SO->second.front().Method->isPure())
5740         continue;
5741 
5742       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5743         continue;
5744 
5745       Diag(SO->second.front().Method->getLocation(),
5746            diag::note_pure_virtual_function)
5747         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5748     }
5749   }
5750 
5751   if (!PureVirtualClassDiagSet)
5752     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5753   PureVirtualClassDiagSet->insert(RD);
5754 }
5755 
5756 namespace {
5757 struct AbstractUsageInfo {
5758   Sema &S;
5759   CXXRecordDecl *Record;
5760   CanQualType AbstractType;
5761   bool Invalid;
5762 
5763   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5764     : S(S), Record(Record),
5765       AbstractType(S.Context.getCanonicalType(
5766                    S.Context.getTypeDeclType(Record))),
5767       Invalid(false) {}
5768 
5769   void DiagnoseAbstractType() {
5770     if (Invalid) return;
5771     S.DiagnoseAbstractType(Record);
5772     Invalid = true;
5773   }
5774 
5775   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5776 };
5777 
5778 struct CheckAbstractUsage {
5779   AbstractUsageInfo &Info;
5780   const NamedDecl *Ctx;
5781 
5782   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5783     : Info(Info), Ctx(Ctx) {}
5784 
5785   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5786     switch (TL.getTypeLocClass()) {
5787 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5788 #define TYPELOC(CLASS, PARENT) \
5789     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5790 #include "clang/AST/TypeLocNodes.def"
5791     }
5792   }
5793 
5794   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5795     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5796     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5797       if (!TL.getParam(I))
5798         continue;
5799 
5800       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5801       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5802     }
5803   }
5804 
5805   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5806     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5807   }
5808 
5809   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5810     // Visit the type parameters from a permissive context.
5811     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5812       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5813       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5814         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5815           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5816       // TODO: other template argument types?
5817     }
5818   }
5819 
5820   // Visit pointee types from a permissive context.
5821 #define CheckPolymorphic(Type) \
5822   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5823     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5824   }
5825   CheckPolymorphic(PointerTypeLoc)
5826   CheckPolymorphic(ReferenceTypeLoc)
5827   CheckPolymorphic(MemberPointerTypeLoc)
5828   CheckPolymorphic(BlockPointerTypeLoc)
5829   CheckPolymorphic(AtomicTypeLoc)
5830 
5831   /// Handle all the types we haven't given a more specific
5832   /// implementation for above.
5833   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5834     // Every other kind of type that we haven't called out already
5835     // that has an inner type is either (1) sugar or (2) contains that
5836     // inner type in some way as a subobject.
5837     if (TypeLoc Next = TL.getNextTypeLoc())
5838       return Visit(Next, Sel);
5839 
5840     // If there's no inner type and we're in a permissive context,
5841     // don't diagnose.
5842     if (Sel == Sema::AbstractNone) return;
5843 
5844     // Check whether the type matches the abstract type.
5845     QualType T = TL.getType();
5846     if (T->isArrayType()) {
5847       Sel = Sema::AbstractArrayType;
5848       T = Info.S.Context.getBaseElementType(T);
5849     }
5850     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5851     if (CT != Info.AbstractType) return;
5852 
5853     // It matched; do some magic.
5854     if (Sel == Sema::AbstractArrayType) {
5855       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5856         << T << TL.getSourceRange();
5857     } else {
5858       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5859         << Sel << T << TL.getSourceRange();
5860     }
5861     Info.DiagnoseAbstractType();
5862   }
5863 };
5864 
5865 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5866                                   Sema::AbstractDiagSelID Sel) {
5867   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5868 }
5869 
5870 }
5871 
5872 /// Check for invalid uses of an abstract type in a method declaration.
5873 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5874                                     CXXMethodDecl *MD) {
5875   // No need to do the check on definitions, which require that
5876   // the return/param types be complete.
5877   if (MD->doesThisDeclarationHaveABody())
5878     return;
5879 
5880   // For safety's sake, just ignore it if we don't have type source
5881   // information.  This should never happen for non-implicit methods,
5882   // but...
5883   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5884     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5885 }
5886 
5887 /// Check for invalid uses of an abstract type within a class definition.
5888 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5889                                     CXXRecordDecl *RD) {
5890   for (auto *D : RD->decls()) {
5891     if (D->isImplicit()) continue;
5892 
5893     // Methods and method templates.
5894     if (isa<CXXMethodDecl>(D)) {
5895       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5896     } else if (isa<FunctionTemplateDecl>(D)) {
5897       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5898       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5899 
5900     // Fields and static variables.
5901     } else if (isa<FieldDecl>(D)) {
5902       FieldDecl *FD = cast<FieldDecl>(D);
5903       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5904         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5905     } else if (isa<VarDecl>(D)) {
5906       VarDecl *VD = cast<VarDecl>(D);
5907       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5908         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5909 
5910     // Nested classes and class templates.
5911     } else if (isa<CXXRecordDecl>(D)) {
5912       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5913     } else if (isa<ClassTemplateDecl>(D)) {
5914       CheckAbstractClassUsage(Info,
5915                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5916     }
5917   }
5918 }
5919 
5920 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5921   Attr *ClassAttr = getDLLAttr(Class);
5922   if (!ClassAttr)
5923     return;
5924 
5925   assert(ClassAttr->getKind() == attr::DLLExport);
5926 
5927   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5928 
5929   if (TSK == TSK_ExplicitInstantiationDeclaration)
5930     // Don't go any further if this is just an explicit instantiation
5931     // declaration.
5932     return;
5933 
5934   // Add a context note to explain how we got to any diagnostics produced below.
5935   struct MarkingClassDllexported {
5936     Sema &S;
5937     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5938                             SourceLocation AttrLoc)
5939         : S(S) {
5940       Sema::CodeSynthesisContext Ctx;
5941       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5942       Ctx.PointOfInstantiation = AttrLoc;
5943       Ctx.Entity = Class;
5944       S.pushCodeSynthesisContext(Ctx);
5945     }
5946     ~MarkingClassDllexported() {
5947       S.popCodeSynthesisContext();
5948     }
5949   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5950 
5951   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5952     S.MarkVTableUsed(Class->getLocation(), Class, true);
5953 
5954   for (Decl *Member : Class->decls()) {
5955     // Defined static variables that are members of an exported base
5956     // class must be marked export too.
5957     auto *VD = dyn_cast<VarDecl>(Member);
5958     if (VD && Member->getAttr<DLLExportAttr>() &&
5959         VD->getStorageClass() == SC_Static &&
5960         TSK == TSK_ImplicitInstantiation)
5961       S.MarkVariableReferenced(VD->getLocation(), VD);
5962 
5963     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5964     if (!MD)
5965       continue;
5966 
5967     if (Member->getAttr<DLLExportAttr>()) {
5968       if (MD->isUserProvided()) {
5969         // Instantiate non-default class member functions ...
5970 
5971         // .. except for certain kinds of template specializations.
5972         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5973           continue;
5974 
5975         S.MarkFunctionReferenced(Class->getLocation(), MD);
5976 
5977         // The function will be passed to the consumer when its definition is
5978         // encountered.
5979       } else if (MD->isExplicitlyDefaulted()) {
5980         // Synthesize and instantiate explicitly defaulted methods.
5981         S.MarkFunctionReferenced(Class->getLocation(), MD);
5982 
5983         if (TSK != TSK_ExplicitInstantiationDefinition) {
5984           // Except for explicit instantiation defs, we will not see the
5985           // definition again later, so pass it to the consumer now.
5986           S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5987         }
5988       } else if (!MD->isTrivial() ||
5989                  MD->isCopyAssignmentOperator() ||
5990                  MD->isMoveAssignmentOperator()) {
5991         // Synthesize and instantiate non-trivial implicit methods, and the copy
5992         // and move assignment operators. The latter are exported even if they
5993         // are trivial, because the address of an operator can be taken and
5994         // should compare equal across libraries.
5995         S.MarkFunctionReferenced(Class->getLocation(), MD);
5996 
5997         // There is no later point when we will see the definition of this
5998         // function, so pass it to the consumer now.
5999         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6000       }
6001     }
6002   }
6003 }
6004 
6005 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6006                                                         CXXRecordDecl *Class) {
6007   // Only the MS ABI has default constructor closures, so we don't need to do
6008   // this semantic checking anywhere else.
6009   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6010     return;
6011 
6012   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6013   for (Decl *Member : Class->decls()) {
6014     // Look for exported default constructors.
6015     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6016     if (!CD || !CD->isDefaultConstructor())
6017       continue;
6018     auto *Attr = CD->getAttr<DLLExportAttr>();
6019     if (!Attr)
6020       continue;
6021 
6022     // If the class is non-dependent, mark the default arguments as ODR-used so
6023     // that we can properly codegen the constructor closure.
6024     if (!Class->isDependentContext()) {
6025       for (ParmVarDecl *PD : CD->parameters()) {
6026         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6027         S.DiscardCleanupsInEvaluationContext();
6028       }
6029     }
6030 
6031     if (LastExportedDefaultCtor) {
6032       S.Diag(LastExportedDefaultCtor->getLocation(),
6033              diag::err_attribute_dll_ambiguous_default_ctor)
6034           << Class;
6035       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6036           << CD->getDeclName();
6037       return;
6038     }
6039     LastExportedDefaultCtor = CD;
6040   }
6041 }
6042 
6043 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6044                                                        CXXRecordDecl *Class) {
6045   bool ErrorReported = false;
6046   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6047                                                      ClassTemplateDecl *TD) {
6048     if (ErrorReported)
6049       return;
6050     S.Diag(TD->getLocation(),
6051            diag::err_cuda_device_builtin_surftex_cls_template)
6052         << /*surface*/ 0 << TD;
6053     ErrorReported = true;
6054   };
6055 
6056   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6057   if (!TD) {
6058     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6059     if (!SD) {
6060       S.Diag(Class->getLocation(),
6061              diag::err_cuda_device_builtin_surftex_ref_decl)
6062           << /*surface*/ 0 << Class;
6063       S.Diag(Class->getLocation(),
6064              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6065           << Class;
6066       return;
6067     }
6068     TD = SD->getSpecializedTemplate();
6069   }
6070 
6071   TemplateParameterList *Params = TD->getTemplateParameters();
6072   unsigned N = Params->size();
6073 
6074   if (N != 2) {
6075     reportIllegalClassTemplate(S, TD);
6076     S.Diag(TD->getLocation(),
6077            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6078         << TD << 2;
6079   }
6080   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6081     reportIllegalClassTemplate(S, TD);
6082     S.Diag(TD->getLocation(),
6083            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6084         << TD << /*1st*/ 0 << /*type*/ 0;
6085   }
6086   if (N > 1) {
6087     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6088     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6089       reportIllegalClassTemplate(S, TD);
6090       S.Diag(TD->getLocation(),
6091              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6092           << TD << /*2nd*/ 1 << /*integer*/ 1;
6093     }
6094   }
6095 }
6096 
6097 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6098                                                        CXXRecordDecl *Class) {
6099   bool ErrorReported = false;
6100   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6101                                                      ClassTemplateDecl *TD) {
6102     if (ErrorReported)
6103       return;
6104     S.Diag(TD->getLocation(),
6105            diag::err_cuda_device_builtin_surftex_cls_template)
6106         << /*texture*/ 1 << TD;
6107     ErrorReported = true;
6108   };
6109 
6110   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6111   if (!TD) {
6112     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6113     if (!SD) {
6114       S.Diag(Class->getLocation(),
6115              diag::err_cuda_device_builtin_surftex_ref_decl)
6116           << /*texture*/ 1 << Class;
6117       S.Diag(Class->getLocation(),
6118              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6119           << Class;
6120       return;
6121     }
6122     TD = SD->getSpecializedTemplate();
6123   }
6124 
6125   TemplateParameterList *Params = TD->getTemplateParameters();
6126   unsigned N = Params->size();
6127 
6128   if (N != 3) {
6129     reportIllegalClassTemplate(S, TD);
6130     S.Diag(TD->getLocation(),
6131            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6132         << TD << 3;
6133   }
6134   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6135     reportIllegalClassTemplate(S, TD);
6136     S.Diag(TD->getLocation(),
6137            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6138         << TD << /*1st*/ 0 << /*type*/ 0;
6139   }
6140   if (N > 1) {
6141     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6142     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6143       reportIllegalClassTemplate(S, TD);
6144       S.Diag(TD->getLocation(),
6145              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6146           << TD << /*2nd*/ 1 << /*integer*/ 1;
6147     }
6148   }
6149   if (N > 2) {
6150     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6151     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6152       reportIllegalClassTemplate(S, TD);
6153       S.Diag(TD->getLocation(),
6154              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6155           << TD << /*3rd*/ 2 << /*integer*/ 1;
6156     }
6157   }
6158 }
6159 
6160 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6161   // Mark any compiler-generated routines with the implicit code_seg attribute.
6162   for (auto *Method : Class->methods()) {
6163     if (Method->isUserProvided())
6164       continue;
6165     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6166       Method->addAttr(A);
6167   }
6168 }
6169 
6170 /// Check class-level dllimport/dllexport attribute.
6171 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6172   Attr *ClassAttr = getDLLAttr(Class);
6173 
6174   // MSVC inherits DLL attributes to partial class template specializations.
6175   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6176     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6177       if (Attr *TemplateAttr =
6178               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6179         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6180         A->setInherited(true);
6181         ClassAttr = A;
6182       }
6183     }
6184   }
6185 
6186   if (!ClassAttr)
6187     return;
6188 
6189   if (!Class->isExternallyVisible()) {
6190     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6191         << Class << ClassAttr;
6192     return;
6193   }
6194 
6195   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6196       !ClassAttr->isInherited()) {
6197     // Diagnose dll attributes on members of class with dll attribute.
6198     for (Decl *Member : Class->decls()) {
6199       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6200         continue;
6201       InheritableAttr *MemberAttr = getDLLAttr(Member);
6202       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6203         continue;
6204 
6205       Diag(MemberAttr->getLocation(),
6206              diag::err_attribute_dll_member_of_dll_class)
6207           << MemberAttr << ClassAttr;
6208       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6209       Member->setInvalidDecl();
6210     }
6211   }
6212 
6213   if (Class->getDescribedClassTemplate())
6214     // Don't inherit dll attribute until the template is instantiated.
6215     return;
6216 
6217   // The class is either imported or exported.
6218   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6219 
6220   // Check if this was a dllimport attribute propagated from a derived class to
6221   // a base class template specialization. We don't apply these attributes to
6222   // static data members.
6223   const bool PropagatedImport =
6224       !ClassExported &&
6225       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6226 
6227   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6228 
6229   // Ignore explicit dllexport on explicit class template instantiation
6230   // declarations, except in MinGW mode.
6231   if (ClassExported && !ClassAttr->isInherited() &&
6232       TSK == TSK_ExplicitInstantiationDeclaration &&
6233       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6234     Class->dropAttr<DLLExportAttr>();
6235     return;
6236   }
6237 
6238   // Force declaration of implicit members so they can inherit the attribute.
6239   ForceDeclarationOfImplicitMembers(Class);
6240 
6241   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6242   // seem to be true in practice?
6243 
6244   for (Decl *Member : Class->decls()) {
6245     VarDecl *VD = dyn_cast<VarDecl>(Member);
6246     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6247 
6248     // Only methods and static fields inherit the attributes.
6249     if (!VD && !MD)
6250       continue;
6251 
6252     if (MD) {
6253       // Don't process deleted methods.
6254       if (MD->isDeleted())
6255         continue;
6256 
6257       if (MD->isInlined()) {
6258         // MinGW does not import or export inline methods. But do it for
6259         // template instantiations.
6260         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6261             TSK != TSK_ExplicitInstantiationDeclaration &&
6262             TSK != TSK_ExplicitInstantiationDefinition)
6263           continue;
6264 
6265         // MSVC versions before 2015 don't export the move assignment operators
6266         // and move constructor, so don't attempt to import/export them if
6267         // we have a definition.
6268         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6269         if ((MD->isMoveAssignmentOperator() ||
6270              (Ctor && Ctor->isMoveConstructor())) &&
6271             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6272           continue;
6273 
6274         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6275         // operator is exported anyway.
6276         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6277             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6278           continue;
6279       }
6280     }
6281 
6282     // Don't apply dllimport attributes to static data members of class template
6283     // instantiations when the attribute is propagated from a derived class.
6284     if (VD && PropagatedImport)
6285       continue;
6286 
6287     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6288       continue;
6289 
6290     if (!getDLLAttr(Member)) {
6291       InheritableAttr *NewAttr = nullptr;
6292 
6293       // Do not export/import inline function when -fno-dllexport-inlines is
6294       // passed. But add attribute for later local static var check.
6295       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6296           TSK != TSK_ExplicitInstantiationDeclaration &&
6297           TSK != TSK_ExplicitInstantiationDefinition) {
6298         if (ClassExported) {
6299           NewAttr = ::new (getASTContext())
6300               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6301         } else {
6302           NewAttr = ::new (getASTContext())
6303               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6304         }
6305       } else {
6306         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6307       }
6308 
6309       NewAttr->setInherited(true);
6310       Member->addAttr(NewAttr);
6311 
6312       if (MD) {
6313         // Propagate DLLAttr to friend re-declarations of MD that have already
6314         // been constructed.
6315         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6316              FD = FD->getPreviousDecl()) {
6317           if (FD->getFriendObjectKind() == Decl::FOK_None)
6318             continue;
6319           assert(!getDLLAttr(FD) &&
6320                  "friend re-decl should not already have a DLLAttr");
6321           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6322           NewAttr->setInherited(true);
6323           FD->addAttr(NewAttr);
6324         }
6325       }
6326     }
6327   }
6328 
6329   if (ClassExported)
6330     DelayedDllExportClasses.push_back(Class);
6331 }
6332 
6333 /// Perform propagation of DLL attributes from a derived class to a
6334 /// templated base class for MS compatibility.
6335 void Sema::propagateDLLAttrToBaseClassTemplate(
6336     CXXRecordDecl *Class, Attr *ClassAttr,
6337     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6338   if (getDLLAttr(
6339           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6340     // If the base class template has a DLL attribute, don't try to change it.
6341     return;
6342   }
6343 
6344   auto TSK = BaseTemplateSpec->getSpecializationKind();
6345   if (!getDLLAttr(BaseTemplateSpec) &&
6346       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6347        TSK == TSK_ImplicitInstantiation)) {
6348     // The template hasn't been instantiated yet (or it has, but only as an
6349     // explicit instantiation declaration or implicit instantiation, which means
6350     // we haven't codegenned any members yet), so propagate the attribute.
6351     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6352     NewAttr->setInherited(true);
6353     BaseTemplateSpec->addAttr(NewAttr);
6354 
6355     // If this was an import, mark that we propagated it from a derived class to
6356     // a base class template specialization.
6357     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6358       ImportAttr->setPropagatedToBaseTemplate();
6359 
6360     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6361     // needs to be run again to work see the new attribute. Otherwise this will
6362     // get run whenever the template is instantiated.
6363     if (TSK != TSK_Undeclared)
6364       checkClassLevelDLLAttribute(BaseTemplateSpec);
6365 
6366     return;
6367   }
6368 
6369   if (getDLLAttr(BaseTemplateSpec)) {
6370     // The template has already been specialized or instantiated with an
6371     // attribute, explicitly or through propagation. We should not try to change
6372     // it.
6373     return;
6374   }
6375 
6376   // The template was previously instantiated or explicitly specialized without
6377   // a dll attribute, It's too late for us to add an attribute, so warn that
6378   // this is unsupported.
6379   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6380       << BaseTemplateSpec->isExplicitSpecialization();
6381   Diag(ClassAttr->getLocation(), diag::note_attribute);
6382   if (BaseTemplateSpec->isExplicitSpecialization()) {
6383     Diag(BaseTemplateSpec->getLocation(),
6384            diag::note_template_class_explicit_specialization_was_here)
6385         << BaseTemplateSpec;
6386   } else {
6387     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6388            diag::note_template_class_instantiation_was_here)
6389         << BaseTemplateSpec;
6390   }
6391 }
6392 
6393 /// Determine the kind of defaulting that would be done for a given function.
6394 ///
6395 /// If the function is both a default constructor and a copy / move constructor
6396 /// (due to having a default argument for the first parameter), this picks
6397 /// CXXDefaultConstructor.
6398 ///
6399 /// FIXME: Check that case is properly handled by all callers.
6400 Sema::DefaultedFunctionKind
6401 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6402   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6403     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6404       if (Ctor->isDefaultConstructor())
6405         return Sema::CXXDefaultConstructor;
6406 
6407       if (Ctor->isCopyConstructor())
6408         return Sema::CXXCopyConstructor;
6409 
6410       if (Ctor->isMoveConstructor())
6411         return Sema::CXXMoveConstructor;
6412     }
6413 
6414     if (MD->isCopyAssignmentOperator())
6415       return Sema::CXXCopyAssignment;
6416 
6417     if (MD->isMoveAssignmentOperator())
6418       return Sema::CXXMoveAssignment;
6419 
6420     if (isa<CXXDestructorDecl>(FD))
6421       return Sema::CXXDestructor;
6422   }
6423 
6424   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6425   case OO_EqualEqual:
6426     return DefaultedComparisonKind::Equal;
6427 
6428   case OO_ExclaimEqual:
6429     return DefaultedComparisonKind::NotEqual;
6430 
6431   case OO_Spaceship:
6432     // No point allowing this if <=> doesn't exist in the current language mode.
6433     if (!getLangOpts().CPlusPlus20)
6434       break;
6435     return DefaultedComparisonKind::ThreeWay;
6436 
6437   case OO_Less:
6438   case OO_LessEqual:
6439   case OO_Greater:
6440   case OO_GreaterEqual:
6441     // No point allowing this if <=> doesn't exist in the current language mode.
6442     if (!getLangOpts().CPlusPlus20)
6443       break;
6444     return DefaultedComparisonKind::Relational;
6445 
6446   default:
6447     break;
6448   }
6449 
6450   // Not defaultable.
6451   return DefaultedFunctionKind();
6452 }
6453 
6454 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6455                                     SourceLocation DefaultLoc) {
6456   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6457   if (DFK.isComparison())
6458     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6459 
6460   switch (DFK.asSpecialMember()) {
6461   case Sema::CXXDefaultConstructor:
6462     S.DefineImplicitDefaultConstructor(DefaultLoc,
6463                                        cast<CXXConstructorDecl>(FD));
6464     break;
6465   case Sema::CXXCopyConstructor:
6466     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6467     break;
6468   case Sema::CXXCopyAssignment:
6469     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6470     break;
6471   case Sema::CXXDestructor:
6472     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6473     break;
6474   case Sema::CXXMoveConstructor:
6475     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6476     break;
6477   case Sema::CXXMoveAssignment:
6478     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6479     break;
6480   case Sema::CXXInvalid:
6481     llvm_unreachable("Invalid special member.");
6482   }
6483 }
6484 
6485 /// Determine whether a type is permitted to be passed or returned in
6486 /// registers, per C++ [class.temporary]p3.
6487 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6488                                TargetInfo::CallingConvKind CCK) {
6489   if (D->isDependentType() || D->isInvalidDecl())
6490     return false;
6491 
6492   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6493   // The PS4 platform ABI follows the behavior of Clang 3.2.
6494   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6495     return !D->hasNonTrivialDestructorForCall() &&
6496            !D->hasNonTrivialCopyConstructorForCall();
6497 
6498   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6499     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6500     bool DtorIsTrivialForCall = false;
6501 
6502     // If a class has at least one non-deleted, trivial copy constructor, it
6503     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6504     //
6505     // Note: This permits classes with non-trivial copy or move ctors to be
6506     // passed in registers, so long as they *also* have a trivial copy ctor,
6507     // which is non-conforming.
6508     if (D->needsImplicitCopyConstructor()) {
6509       if (!D->defaultedCopyConstructorIsDeleted()) {
6510         if (D->hasTrivialCopyConstructor())
6511           CopyCtorIsTrivial = true;
6512         if (D->hasTrivialCopyConstructorForCall())
6513           CopyCtorIsTrivialForCall = true;
6514       }
6515     } else {
6516       for (const CXXConstructorDecl *CD : D->ctors()) {
6517         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6518           if (CD->isTrivial())
6519             CopyCtorIsTrivial = true;
6520           if (CD->isTrivialForCall())
6521             CopyCtorIsTrivialForCall = true;
6522         }
6523       }
6524     }
6525 
6526     if (D->needsImplicitDestructor()) {
6527       if (!D->defaultedDestructorIsDeleted() &&
6528           D->hasTrivialDestructorForCall())
6529         DtorIsTrivialForCall = true;
6530     } else if (const auto *DD = D->getDestructor()) {
6531       if (!DD->isDeleted() && DD->isTrivialForCall())
6532         DtorIsTrivialForCall = true;
6533     }
6534 
6535     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6536     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6537       return true;
6538 
6539     // If a class has a destructor, we'd really like to pass it indirectly
6540     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6541     // impossible for small types, which it will pass in a single register or
6542     // stack slot. Most objects with dtors are large-ish, so handle that early.
6543     // We can't call out all large objects as being indirect because there are
6544     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6545     // how we pass large POD types.
6546 
6547     // Note: This permits small classes with nontrivial destructors to be
6548     // passed in registers, which is non-conforming.
6549     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6550     uint64_t TypeSize = isAArch64 ? 128 : 64;
6551 
6552     if (CopyCtorIsTrivial &&
6553         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6554       return true;
6555     return false;
6556   }
6557 
6558   // Per C++ [class.temporary]p3, the relevant condition is:
6559   //   each copy constructor, move constructor, and destructor of X is
6560   //   either trivial or deleted, and X has at least one non-deleted copy
6561   //   or move constructor
6562   bool HasNonDeletedCopyOrMove = false;
6563 
6564   if (D->needsImplicitCopyConstructor() &&
6565       !D->defaultedCopyConstructorIsDeleted()) {
6566     if (!D->hasTrivialCopyConstructorForCall())
6567       return false;
6568     HasNonDeletedCopyOrMove = true;
6569   }
6570 
6571   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6572       !D->defaultedMoveConstructorIsDeleted()) {
6573     if (!D->hasTrivialMoveConstructorForCall())
6574       return false;
6575     HasNonDeletedCopyOrMove = true;
6576   }
6577 
6578   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6579       !D->hasTrivialDestructorForCall())
6580     return false;
6581 
6582   for (const CXXMethodDecl *MD : D->methods()) {
6583     if (MD->isDeleted())
6584       continue;
6585 
6586     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6587     if (CD && CD->isCopyOrMoveConstructor())
6588       HasNonDeletedCopyOrMove = true;
6589     else if (!isa<CXXDestructorDecl>(MD))
6590       continue;
6591 
6592     if (!MD->isTrivialForCall())
6593       return false;
6594   }
6595 
6596   return HasNonDeletedCopyOrMove;
6597 }
6598 
6599 /// Report an error regarding overriding, along with any relevant
6600 /// overridden methods.
6601 ///
6602 /// \param DiagID the primary error to report.
6603 /// \param MD the overriding method.
6604 static bool
6605 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6606                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6607   bool IssuedDiagnostic = false;
6608   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6609     if (Report(O)) {
6610       if (!IssuedDiagnostic) {
6611         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6612         IssuedDiagnostic = true;
6613       }
6614       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6615     }
6616   }
6617   return IssuedDiagnostic;
6618 }
6619 
6620 /// Perform semantic checks on a class definition that has been
6621 /// completing, introducing implicitly-declared members, checking for
6622 /// abstract types, etc.
6623 ///
6624 /// \param S The scope in which the class was parsed. Null if we didn't just
6625 ///        parse a class definition.
6626 /// \param Record The completed class.
6627 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6628   if (!Record)
6629     return;
6630 
6631   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6632     AbstractUsageInfo Info(*this, Record);
6633     CheckAbstractClassUsage(Info, Record);
6634   }
6635 
6636   // If this is not an aggregate type and has no user-declared constructor,
6637   // complain about any non-static data members of reference or const scalar
6638   // type, since they will never get initializers.
6639   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6640       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6641       !Record->isLambda()) {
6642     bool Complained = false;
6643     for (const auto *F : Record->fields()) {
6644       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6645         continue;
6646 
6647       if (F->getType()->isReferenceType() ||
6648           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6649         if (!Complained) {
6650           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6651             << Record->getTagKind() << Record;
6652           Complained = true;
6653         }
6654 
6655         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6656           << F->getType()->isReferenceType()
6657           << F->getDeclName();
6658       }
6659     }
6660   }
6661 
6662   if (Record->getIdentifier()) {
6663     // C++ [class.mem]p13:
6664     //   If T is the name of a class, then each of the following shall have a
6665     //   name different from T:
6666     //     - every member of every anonymous union that is a member of class T.
6667     //
6668     // C++ [class.mem]p14:
6669     //   In addition, if class T has a user-declared constructor (12.1), every
6670     //   non-static data member of class T shall have a name different from T.
6671     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6672     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6673          ++I) {
6674       NamedDecl *D = (*I)->getUnderlyingDecl();
6675       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6676            Record->hasUserDeclaredConstructor()) ||
6677           isa<IndirectFieldDecl>(D)) {
6678         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6679           << D->getDeclName();
6680         break;
6681       }
6682     }
6683   }
6684 
6685   // Warn if the class has virtual methods but non-virtual public destructor.
6686   if (Record->isPolymorphic() && !Record->isDependentType()) {
6687     CXXDestructorDecl *dtor = Record->getDestructor();
6688     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6689         !Record->hasAttr<FinalAttr>())
6690       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6691            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6692   }
6693 
6694   if (Record->isAbstract()) {
6695     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6696       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6697         << FA->isSpelledAsSealed();
6698       DiagnoseAbstractType(Record);
6699     }
6700   }
6701 
6702   // Warn if the class has a final destructor but is not itself marked final.
6703   if (!Record->hasAttr<FinalAttr>()) {
6704     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6705       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6706         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6707             << FA->isSpelledAsSealed()
6708             << FixItHint::CreateInsertion(
6709                    getLocForEndOfToken(Record->getLocation()),
6710                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6711         Diag(Record->getLocation(),
6712              diag::note_final_dtor_non_final_class_silence)
6713             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6714       }
6715     }
6716   }
6717 
6718   // See if trivial_abi has to be dropped.
6719   if (Record->hasAttr<TrivialABIAttr>())
6720     checkIllFormedTrivialABIStruct(*Record);
6721 
6722   // Set HasTrivialSpecialMemberForCall if the record has attribute
6723   // "trivial_abi".
6724   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6725 
6726   if (HasTrivialABI)
6727     Record->setHasTrivialSpecialMemberForCall();
6728 
6729   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6730   // We check these last because they can depend on the properties of the
6731   // primary comparison functions (==, <=>).
6732   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6733 
6734   // Perform checks that can't be done until we know all the properties of a
6735   // member function (whether it's defaulted, deleted, virtual, overriding,
6736   // ...).
6737   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6738     // A static function cannot override anything.
6739     if (MD->getStorageClass() == SC_Static) {
6740       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6741                           [](const CXXMethodDecl *) { return true; }))
6742         return;
6743     }
6744 
6745     // A deleted function cannot override a non-deleted function and vice
6746     // versa.
6747     if (ReportOverrides(*this,
6748                         MD->isDeleted() ? diag::err_deleted_override
6749                                         : diag::err_non_deleted_override,
6750                         MD, [&](const CXXMethodDecl *V) {
6751                           return MD->isDeleted() != V->isDeleted();
6752                         })) {
6753       if (MD->isDefaulted() && MD->isDeleted())
6754         // Explain why this defaulted function was deleted.
6755         DiagnoseDeletedDefaultedFunction(MD);
6756       return;
6757     }
6758 
6759     // A consteval function cannot override a non-consteval function and vice
6760     // versa.
6761     if (ReportOverrides(*this,
6762                         MD->isConsteval() ? diag::err_consteval_override
6763                                           : diag::err_non_consteval_override,
6764                         MD, [&](const CXXMethodDecl *V) {
6765                           return MD->isConsteval() != V->isConsteval();
6766                         })) {
6767       if (MD->isDefaulted() && MD->isDeleted())
6768         // Explain why this defaulted function was deleted.
6769         DiagnoseDeletedDefaultedFunction(MD);
6770       return;
6771     }
6772   };
6773 
6774   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6775     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6776       return false;
6777 
6778     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6779     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6780         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6781       DefaultedSecondaryComparisons.push_back(FD);
6782       return true;
6783     }
6784 
6785     CheckExplicitlyDefaultedFunction(S, FD);
6786     return false;
6787   };
6788 
6789   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6790     // Check whether the explicitly-defaulted members are valid.
6791     bool Incomplete = CheckForDefaultedFunction(M);
6792 
6793     // Skip the rest of the checks for a member of a dependent class.
6794     if (Record->isDependentType())
6795       return;
6796 
6797     // For an explicitly defaulted or deleted special member, we defer
6798     // determining triviality until the class is complete. That time is now!
6799     CXXSpecialMember CSM = getSpecialMember(M);
6800     if (!M->isImplicit() && !M->isUserProvided()) {
6801       if (CSM != CXXInvalid) {
6802         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6803         // Inform the class that we've finished declaring this member.
6804         Record->finishedDefaultedOrDeletedMember(M);
6805         M->setTrivialForCall(
6806             HasTrivialABI ||
6807             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6808         Record->setTrivialForCallFlags(M);
6809       }
6810     }
6811 
6812     // Set triviality for the purpose of calls if this is a user-provided
6813     // copy/move constructor or destructor.
6814     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6815          CSM == CXXDestructor) && M->isUserProvided()) {
6816       M->setTrivialForCall(HasTrivialABI);
6817       Record->setTrivialForCallFlags(M);
6818     }
6819 
6820     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6821         M->hasAttr<DLLExportAttr>()) {
6822       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6823           M->isTrivial() &&
6824           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6825            CSM == CXXDestructor))
6826         M->dropAttr<DLLExportAttr>();
6827 
6828       if (M->hasAttr<DLLExportAttr>()) {
6829         // Define after any fields with in-class initializers have been parsed.
6830         DelayedDllExportMemberFunctions.push_back(M);
6831       }
6832     }
6833 
6834     // Define defaulted constexpr virtual functions that override a base class
6835     // function right away.
6836     // FIXME: We can defer doing this until the vtable is marked as used.
6837     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6838       DefineDefaultedFunction(*this, M, M->getLocation());
6839 
6840     if (!Incomplete)
6841       CheckCompletedMemberFunction(M);
6842   };
6843 
6844   // Check the destructor before any other member function. We need to
6845   // determine whether it's trivial in order to determine whether the claas
6846   // type is a literal type, which is a prerequisite for determining whether
6847   // other special member functions are valid and whether they're implicitly
6848   // 'constexpr'.
6849   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6850     CompleteMemberFunction(Dtor);
6851 
6852   bool HasMethodWithOverrideControl = false,
6853        HasOverridingMethodWithoutOverrideControl = false;
6854   for (auto *D : Record->decls()) {
6855     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6856       // FIXME: We could do this check for dependent types with non-dependent
6857       // bases.
6858       if (!Record->isDependentType()) {
6859         // See if a method overloads virtual methods in a base
6860         // class without overriding any.
6861         if (!M->isStatic())
6862           DiagnoseHiddenVirtualMethods(M);
6863         if (M->hasAttr<OverrideAttr>())
6864           HasMethodWithOverrideControl = true;
6865         else if (M->size_overridden_methods() > 0)
6866           HasOverridingMethodWithoutOverrideControl = true;
6867       }
6868 
6869       if (!isa<CXXDestructorDecl>(M))
6870         CompleteMemberFunction(M);
6871     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6872       CheckForDefaultedFunction(
6873           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6874     }
6875   }
6876 
6877   if (HasOverridingMethodWithoutOverrideControl) {
6878     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6879     for (auto *M : Record->methods())
6880       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6881   }
6882 
6883   // Check the defaulted secondary comparisons after any other member functions.
6884   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6885     CheckExplicitlyDefaultedFunction(S, FD);
6886 
6887     // If this is a member function, we deferred checking it until now.
6888     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6889       CheckCompletedMemberFunction(MD);
6890   }
6891 
6892   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6893   // whether this class uses any C++ features that are implemented
6894   // completely differently in MSVC, and if so, emit a diagnostic.
6895   // That diagnostic defaults to an error, but we allow projects to
6896   // map it down to a warning (or ignore it).  It's a fairly common
6897   // practice among users of the ms_struct pragma to mass-annotate
6898   // headers, sweeping up a bunch of types that the project doesn't
6899   // really rely on MSVC-compatible layout for.  We must therefore
6900   // support "ms_struct except for C++ stuff" as a secondary ABI.
6901   // Don't emit this diagnostic if the feature was enabled as a
6902   // language option (as opposed to via a pragma or attribute), as
6903   // the option -mms-bitfields otherwise essentially makes it impossible
6904   // to build C++ code, unless this diagnostic is turned off.
6905   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6906       (Record->isPolymorphic() || Record->getNumBases())) {
6907     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6908   }
6909 
6910   checkClassLevelDLLAttribute(Record);
6911   checkClassLevelCodeSegAttribute(Record);
6912 
6913   bool ClangABICompat4 =
6914       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6915   TargetInfo::CallingConvKind CCK =
6916       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6917   bool CanPass = canPassInRegisters(*this, Record, CCK);
6918 
6919   // Do not change ArgPassingRestrictions if it has already been set to
6920   // APK_CanNeverPassInRegs.
6921   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6922     Record->setArgPassingRestrictions(CanPass
6923                                           ? RecordDecl::APK_CanPassInRegs
6924                                           : RecordDecl::APK_CannotPassInRegs);
6925 
6926   // If canPassInRegisters returns true despite the record having a non-trivial
6927   // destructor, the record is destructed in the callee. This happens only when
6928   // the record or one of its subobjects has a field annotated with trivial_abi
6929   // or a field qualified with ObjC __strong/__weak.
6930   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6931     Record->setParamDestroyedInCallee(true);
6932   else if (Record->hasNonTrivialDestructor())
6933     Record->setParamDestroyedInCallee(CanPass);
6934 
6935   if (getLangOpts().ForceEmitVTables) {
6936     // If we want to emit all the vtables, we need to mark it as used.  This
6937     // is especially required for cases like vtable assumption loads.
6938     MarkVTableUsed(Record->getInnerLocStart(), Record);
6939   }
6940 
6941   if (getLangOpts().CUDA) {
6942     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6943       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6944     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6945       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6946   }
6947 }
6948 
6949 /// Look up the special member function that would be called by a special
6950 /// member function for a subobject of class type.
6951 ///
6952 /// \param Class The class type of the subobject.
6953 /// \param CSM The kind of special member function.
6954 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6955 /// \param ConstRHS True if this is a copy operation with a const object
6956 ///        on its RHS, that is, if the argument to the outer special member
6957 ///        function is 'const' and this is not a field marked 'mutable'.
6958 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6959     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6960     unsigned FieldQuals, bool ConstRHS) {
6961   unsigned LHSQuals = 0;
6962   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6963     LHSQuals = FieldQuals;
6964 
6965   unsigned RHSQuals = FieldQuals;
6966   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6967     RHSQuals = 0;
6968   else if (ConstRHS)
6969     RHSQuals |= Qualifiers::Const;
6970 
6971   return S.LookupSpecialMember(Class, CSM,
6972                                RHSQuals & Qualifiers::Const,
6973                                RHSQuals & Qualifiers::Volatile,
6974                                false,
6975                                LHSQuals & Qualifiers::Const,
6976                                LHSQuals & Qualifiers::Volatile);
6977 }
6978 
6979 class Sema::InheritedConstructorInfo {
6980   Sema &S;
6981   SourceLocation UseLoc;
6982 
6983   /// A mapping from the base classes through which the constructor was
6984   /// inherited to the using shadow declaration in that base class (or a null
6985   /// pointer if the constructor was declared in that base class).
6986   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6987       InheritedFromBases;
6988 
6989 public:
6990   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6991                            ConstructorUsingShadowDecl *Shadow)
6992       : S(S), UseLoc(UseLoc) {
6993     bool DiagnosedMultipleConstructedBases = false;
6994     CXXRecordDecl *ConstructedBase = nullptr;
6995     UsingDecl *ConstructedBaseUsing = nullptr;
6996 
6997     // Find the set of such base class subobjects and check that there's a
6998     // unique constructed subobject.
6999     for (auto *D : Shadow->redecls()) {
7000       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7001       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7002       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7003 
7004       InheritedFromBases.insert(
7005           std::make_pair(DNominatedBase->getCanonicalDecl(),
7006                          DShadow->getNominatedBaseClassShadowDecl()));
7007       if (DShadow->constructsVirtualBase())
7008         InheritedFromBases.insert(
7009             std::make_pair(DConstructedBase->getCanonicalDecl(),
7010                            DShadow->getConstructedBaseClassShadowDecl()));
7011       else
7012         assert(DNominatedBase == DConstructedBase);
7013 
7014       // [class.inhctor.init]p2:
7015       //   If the constructor was inherited from multiple base class subobjects
7016       //   of type B, the program is ill-formed.
7017       if (!ConstructedBase) {
7018         ConstructedBase = DConstructedBase;
7019         ConstructedBaseUsing = D->getUsingDecl();
7020       } else if (ConstructedBase != DConstructedBase &&
7021                  !Shadow->isInvalidDecl()) {
7022         if (!DiagnosedMultipleConstructedBases) {
7023           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7024               << Shadow->getTargetDecl();
7025           S.Diag(ConstructedBaseUsing->getLocation(),
7026                diag::note_ambiguous_inherited_constructor_using)
7027               << ConstructedBase;
7028           DiagnosedMultipleConstructedBases = true;
7029         }
7030         S.Diag(D->getUsingDecl()->getLocation(),
7031                diag::note_ambiguous_inherited_constructor_using)
7032             << DConstructedBase;
7033       }
7034     }
7035 
7036     if (DiagnosedMultipleConstructedBases)
7037       Shadow->setInvalidDecl();
7038   }
7039 
7040   /// Find the constructor to use for inherited construction of a base class,
7041   /// and whether that base class constructor inherits the constructor from a
7042   /// virtual base class (in which case it won't actually invoke it).
7043   std::pair<CXXConstructorDecl *, bool>
7044   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7045     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7046     if (It == InheritedFromBases.end())
7047       return std::make_pair(nullptr, false);
7048 
7049     // This is an intermediary class.
7050     if (It->second)
7051       return std::make_pair(
7052           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7053           It->second->constructsVirtualBase());
7054 
7055     // This is the base class from which the constructor was inherited.
7056     return std::make_pair(Ctor, false);
7057   }
7058 };
7059 
7060 /// Is the special member function which would be selected to perform the
7061 /// specified operation on the specified class type a constexpr constructor?
7062 static bool
7063 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7064                          Sema::CXXSpecialMember CSM, unsigned Quals,
7065                          bool ConstRHS,
7066                          CXXConstructorDecl *InheritedCtor = nullptr,
7067                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7068   // If we're inheriting a constructor, see if we need to call it for this base
7069   // class.
7070   if (InheritedCtor) {
7071     assert(CSM == Sema::CXXDefaultConstructor);
7072     auto BaseCtor =
7073         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7074     if (BaseCtor)
7075       return BaseCtor->isConstexpr();
7076   }
7077 
7078   if (CSM == Sema::CXXDefaultConstructor)
7079     return ClassDecl->hasConstexprDefaultConstructor();
7080   if (CSM == Sema::CXXDestructor)
7081     return ClassDecl->hasConstexprDestructor();
7082 
7083   Sema::SpecialMemberOverloadResult SMOR =
7084       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7085   if (!SMOR.getMethod())
7086     // A constructor we wouldn't select can't be "involved in initializing"
7087     // anything.
7088     return true;
7089   return SMOR.getMethod()->isConstexpr();
7090 }
7091 
7092 /// Determine whether the specified special member function would be constexpr
7093 /// if it were implicitly defined.
7094 static bool defaultedSpecialMemberIsConstexpr(
7095     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7096     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7097     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7098   if (!S.getLangOpts().CPlusPlus11)
7099     return false;
7100 
7101   // C++11 [dcl.constexpr]p4:
7102   // In the definition of a constexpr constructor [...]
7103   bool Ctor = true;
7104   switch (CSM) {
7105   case Sema::CXXDefaultConstructor:
7106     if (Inherited)
7107       break;
7108     // Since default constructor lookup is essentially trivial (and cannot
7109     // involve, for instance, template instantiation), we compute whether a
7110     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7111     //
7112     // This is important for performance; we need to know whether the default
7113     // constructor is constexpr to determine whether the type is a literal type.
7114     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7115 
7116   case Sema::CXXCopyConstructor:
7117   case Sema::CXXMoveConstructor:
7118     // For copy or move constructors, we need to perform overload resolution.
7119     break;
7120 
7121   case Sema::CXXCopyAssignment:
7122   case Sema::CXXMoveAssignment:
7123     if (!S.getLangOpts().CPlusPlus14)
7124       return false;
7125     // In C++1y, we need to perform overload resolution.
7126     Ctor = false;
7127     break;
7128 
7129   case Sema::CXXDestructor:
7130     return ClassDecl->defaultedDestructorIsConstexpr();
7131 
7132   case Sema::CXXInvalid:
7133     return false;
7134   }
7135 
7136   //   -- if the class is a non-empty union, or for each non-empty anonymous
7137   //      union member of a non-union class, exactly one non-static data member
7138   //      shall be initialized; [DR1359]
7139   //
7140   // If we squint, this is guaranteed, since exactly one non-static data member
7141   // will be initialized (if the constructor isn't deleted), we just don't know
7142   // which one.
7143   if (Ctor && ClassDecl->isUnion())
7144     return CSM == Sema::CXXDefaultConstructor
7145                ? ClassDecl->hasInClassInitializer() ||
7146                      !ClassDecl->hasVariantMembers()
7147                : true;
7148 
7149   //   -- the class shall not have any virtual base classes;
7150   if (Ctor && ClassDecl->getNumVBases())
7151     return false;
7152 
7153   // C++1y [class.copy]p26:
7154   //   -- [the class] is a literal type, and
7155   if (!Ctor && !ClassDecl->isLiteral())
7156     return false;
7157 
7158   //   -- every constructor involved in initializing [...] base class
7159   //      sub-objects shall be a constexpr constructor;
7160   //   -- the assignment operator selected to copy/move each direct base
7161   //      class is a constexpr function, and
7162   for (const auto &B : ClassDecl->bases()) {
7163     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7164     if (!BaseType) continue;
7165 
7166     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7167     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7168                                   InheritedCtor, Inherited))
7169       return false;
7170   }
7171 
7172   //   -- every constructor involved in initializing non-static data members
7173   //      [...] shall be a constexpr constructor;
7174   //   -- every non-static data member and base class sub-object shall be
7175   //      initialized
7176   //   -- for each non-static data member of X that is of class type (or array
7177   //      thereof), the assignment operator selected to copy/move that member is
7178   //      a constexpr function
7179   for (const auto *F : ClassDecl->fields()) {
7180     if (F->isInvalidDecl())
7181       continue;
7182     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7183       continue;
7184     QualType BaseType = S.Context.getBaseElementType(F->getType());
7185     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7186       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7187       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7188                                     BaseType.getCVRQualifiers(),
7189                                     ConstArg && !F->isMutable()))
7190         return false;
7191     } else if (CSM == Sema::CXXDefaultConstructor) {
7192       return false;
7193     }
7194   }
7195 
7196   // All OK, it's constexpr!
7197   return true;
7198 }
7199 
7200 namespace {
7201 /// RAII object to register a defaulted function as having its exception
7202 /// specification computed.
7203 struct ComputingExceptionSpec {
7204   Sema &S;
7205 
7206   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7207       : S(S) {
7208     Sema::CodeSynthesisContext Ctx;
7209     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7210     Ctx.PointOfInstantiation = Loc;
7211     Ctx.Entity = FD;
7212     S.pushCodeSynthesisContext(Ctx);
7213   }
7214   ~ComputingExceptionSpec() {
7215     S.popCodeSynthesisContext();
7216   }
7217 };
7218 }
7219 
7220 static Sema::ImplicitExceptionSpecification
7221 ComputeDefaultedSpecialMemberExceptionSpec(
7222     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7223     Sema::InheritedConstructorInfo *ICI);
7224 
7225 static Sema::ImplicitExceptionSpecification
7226 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7227                                         FunctionDecl *FD,
7228                                         Sema::DefaultedComparisonKind DCK);
7229 
7230 static Sema::ImplicitExceptionSpecification
7231 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7232   auto DFK = S.getDefaultedFunctionKind(FD);
7233   if (DFK.isSpecialMember())
7234     return ComputeDefaultedSpecialMemberExceptionSpec(
7235         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7236   if (DFK.isComparison())
7237     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7238                                                    DFK.asComparison());
7239 
7240   auto *CD = cast<CXXConstructorDecl>(FD);
7241   assert(CD->getInheritedConstructor() &&
7242          "only defaulted functions and inherited constructors have implicit "
7243          "exception specs");
7244   Sema::InheritedConstructorInfo ICI(
7245       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7246   return ComputeDefaultedSpecialMemberExceptionSpec(
7247       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7248 }
7249 
7250 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7251                                                             CXXMethodDecl *MD) {
7252   FunctionProtoType::ExtProtoInfo EPI;
7253 
7254   // Build an exception specification pointing back at this member.
7255   EPI.ExceptionSpec.Type = EST_Unevaluated;
7256   EPI.ExceptionSpec.SourceDecl = MD;
7257 
7258   // Set the calling convention to the default for C++ instance methods.
7259   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7260       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7261                                             /*IsCXXMethod=*/true));
7262   return EPI;
7263 }
7264 
7265 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7266   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7267   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7268     return;
7269 
7270   // Evaluate the exception specification.
7271   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7272   auto ESI = IES.getExceptionSpec();
7273 
7274   // Update the type of the special member to use it.
7275   UpdateExceptionSpec(FD, ESI);
7276 }
7277 
7278 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7279   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7280 
7281   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7282   if (!DefKind) {
7283     assert(FD->getDeclContext()->isDependentContext());
7284     return;
7285   }
7286 
7287   if (DefKind.isSpecialMember()
7288           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7289                                                   DefKind.asSpecialMember())
7290           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7291     FD->setInvalidDecl();
7292 }
7293 
7294 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7295                                                  CXXSpecialMember CSM) {
7296   CXXRecordDecl *RD = MD->getParent();
7297 
7298   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7299          "not an explicitly-defaulted special member");
7300 
7301   // Defer all checking for special members of a dependent type.
7302   if (RD->isDependentType())
7303     return false;
7304 
7305   // Whether this was the first-declared instance of the constructor.
7306   // This affects whether we implicitly add an exception spec and constexpr.
7307   bool First = MD == MD->getCanonicalDecl();
7308 
7309   bool HadError = false;
7310 
7311   // C++11 [dcl.fct.def.default]p1:
7312   //   A function that is explicitly defaulted shall
7313   //     -- be a special member function [...] (checked elsewhere),
7314   //     -- have the same type (except for ref-qualifiers, and except that a
7315   //        copy operation can take a non-const reference) as an implicit
7316   //        declaration, and
7317   //     -- not have default arguments.
7318   // C++2a changes the second bullet to instead delete the function if it's
7319   // defaulted on its first declaration, unless it's "an assignment operator,
7320   // and its return type differs or its parameter type is not a reference".
7321   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7322   bool ShouldDeleteForTypeMismatch = false;
7323   unsigned ExpectedParams = 1;
7324   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7325     ExpectedParams = 0;
7326   if (MD->getNumParams() != ExpectedParams) {
7327     // This checks for default arguments: a copy or move constructor with a
7328     // default argument is classified as a default constructor, and assignment
7329     // operations and destructors can't have default arguments.
7330     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7331       << CSM << MD->getSourceRange();
7332     HadError = true;
7333   } else if (MD->isVariadic()) {
7334     if (DeleteOnTypeMismatch)
7335       ShouldDeleteForTypeMismatch = true;
7336     else {
7337       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7338         << CSM << MD->getSourceRange();
7339       HadError = true;
7340     }
7341   }
7342 
7343   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7344 
7345   bool CanHaveConstParam = false;
7346   if (CSM == CXXCopyConstructor)
7347     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7348   else if (CSM == CXXCopyAssignment)
7349     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7350 
7351   QualType ReturnType = Context.VoidTy;
7352   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7353     // Check for return type matching.
7354     ReturnType = Type->getReturnType();
7355 
7356     QualType DeclType = Context.getTypeDeclType(RD);
7357     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7358     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7359 
7360     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7361       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7362         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7363       HadError = true;
7364     }
7365 
7366     // A defaulted special member cannot have cv-qualifiers.
7367     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7368       if (DeleteOnTypeMismatch)
7369         ShouldDeleteForTypeMismatch = true;
7370       else {
7371         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7372           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7373         HadError = true;
7374       }
7375     }
7376   }
7377 
7378   // Check for parameter type matching.
7379   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7380   bool HasConstParam = false;
7381   if (ExpectedParams && ArgType->isReferenceType()) {
7382     // Argument must be reference to possibly-const T.
7383     QualType ReferentType = ArgType->getPointeeType();
7384     HasConstParam = ReferentType.isConstQualified();
7385 
7386     if (ReferentType.isVolatileQualified()) {
7387       if (DeleteOnTypeMismatch)
7388         ShouldDeleteForTypeMismatch = true;
7389       else {
7390         Diag(MD->getLocation(),
7391              diag::err_defaulted_special_member_volatile_param) << CSM;
7392         HadError = true;
7393       }
7394     }
7395 
7396     if (HasConstParam && !CanHaveConstParam) {
7397       if (DeleteOnTypeMismatch)
7398         ShouldDeleteForTypeMismatch = true;
7399       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7400         Diag(MD->getLocation(),
7401              diag::err_defaulted_special_member_copy_const_param)
7402           << (CSM == CXXCopyAssignment);
7403         // FIXME: Explain why this special member can't be const.
7404         HadError = true;
7405       } else {
7406         Diag(MD->getLocation(),
7407              diag::err_defaulted_special_member_move_const_param)
7408           << (CSM == CXXMoveAssignment);
7409         HadError = true;
7410       }
7411     }
7412   } else if (ExpectedParams) {
7413     // A copy assignment operator can take its argument by value, but a
7414     // defaulted one cannot.
7415     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7416     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7417     HadError = true;
7418   }
7419 
7420   // C++11 [dcl.fct.def.default]p2:
7421   //   An explicitly-defaulted function may be declared constexpr only if it
7422   //   would have been implicitly declared as constexpr,
7423   // Do not apply this rule to members of class templates, since core issue 1358
7424   // makes such functions always instantiate to constexpr functions. For
7425   // functions which cannot be constexpr (for non-constructors in C++11 and for
7426   // destructors in C++14 and C++17), this is checked elsewhere.
7427   //
7428   // FIXME: This should not apply if the member is deleted.
7429   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7430                                                      HasConstParam);
7431   if ((getLangOpts().CPlusPlus20 ||
7432        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7433                                   : isa<CXXConstructorDecl>(MD))) &&
7434       MD->isConstexpr() && !Constexpr &&
7435       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7436     Diag(MD->getBeginLoc(), MD->isConsteval()
7437                                 ? diag::err_incorrect_defaulted_consteval
7438                                 : diag::err_incorrect_defaulted_constexpr)
7439         << CSM;
7440     // FIXME: Explain why the special member can't be constexpr.
7441     HadError = true;
7442   }
7443 
7444   if (First) {
7445     // C++2a [dcl.fct.def.default]p3:
7446     //   If a function is explicitly defaulted on its first declaration, it is
7447     //   implicitly considered to be constexpr if the implicit declaration
7448     //   would be.
7449     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7450                                           ? ConstexprSpecKind::Consteval
7451                                           : ConstexprSpecKind::Constexpr)
7452                                    : ConstexprSpecKind::Unspecified);
7453 
7454     if (!Type->hasExceptionSpec()) {
7455       // C++2a [except.spec]p3:
7456       //   If a declaration of a function does not have a noexcept-specifier
7457       //   [and] is defaulted on its first declaration, [...] the exception
7458       //   specification is as specified below
7459       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7460       EPI.ExceptionSpec.Type = EST_Unevaluated;
7461       EPI.ExceptionSpec.SourceDecl = MD;
7462       MD->setType(Context.getFunctionType(ReturnType,
7463                                           llvm::makeArrayRef(&ArgType,
7464                                                              ExpectedParams),
7465                                           EPI));
7466     }
7467   }
7468 
7469   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7470     if (First) {
7471       SetDeclDeleted(MD, MD->getLocation());
7472       if (!inTemplateInstantiation() && !HadError) {
7473         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7474         if (ShouldDeleteForTypeMismatch) {
7475           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7476         } else {
7477           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7478         }
7479       }
7480       if (ShouldDeleteForTypeMismatch && !HadError) {
7481         Diag(MD->getLocation(),
7482              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7483       }
7484     } else {
7485       // C++11 [dcl.fct.def.default]p4:
7486       //   [For a] user-provided explicitly-defaulted function [...] if such a
7487       //   function is implicitly defined as deleted, the program is ill-formed.
7488       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7489       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7490       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7491       HadError = true;
7492     }
7493   }
7494 
7495   return HadError;
7496 }
7497 
7498 namespace {
7499 /// Helper class for building and checking a defaulted comparison.
7500 ///
7501 /// Defaulted functions are built in two phases:
7502 ///
7503 ///  * First, the set of operations that the function will perform are
7504 ///    identified, and some of them are checked. If any of the checked
7505 ///    operations is invalid in certain ways, the comparison function is
7506 ///    defined as deleted and no body is built.
7507 ///  * Then, if the function is not defined as deleted, the body is built.
7508 ///
7509 /// This is accomplished by performing two visitation steps over the eventual
7510 /// body of the function.
7511 template<typename Derived, typename ResultList, typename Result,
7512          typename Subobject>
7513 class DefaultedComparisonVisitor {
7514 public:
7515   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7516 
7517   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7518                              DefaultedComparisonKind DCK)
7519       : S(S), RD(RD), FD(FD), DCK(DCK) {
7520     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7521       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7522       // UnresolvedSet to avoid this copy.
7523       Fns.assign(Info->getUnqualifiedLookups().begin(),
7524                  Info->getUnqualifiedLookups().end());
7525     }
7526   }
7527 
7528   ResultList visit() {
7529     // The type of an lvalue naming a parameter of this function.
7530     QualType ParamLvalType =
7531         FD->getParamDecl(0)->getType().getNonReferenceType();
7532 
7533     ResultList Results;
7534 
7535     switch (DCK) {
7536     case DefaultedComparisonKind::None:
7537       llvm_unreachable("not a defaulted comparison");
7538 
7539     case DefaultedComparisonKind::Equal:
7540     case DefaultedComparisonKind::ThreeWay:
7541       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7542       return Results;
7543 
7544     case DefaultedComparisonKind::NotEqual:
7545     case DefaultedComparisonKind::Relational:
7546       Results.add(getDerived().visitExpandedSubobject(
7547           ParamLvalType, getDerived().getCompleteObject()));
7548       return Results;
7549     }
7550     llvm_unreachable("");
7551   }
7552 
7553 protected:
7554   Derived &getDerived() { return static_cast<Derived&>(*this); }
7555 
7556   /// Visit the expanded list of subobjects of the given type, as specified in
7557   /// C++2a [class.compare.default].
7558   ///
7559   /// \return \c true if the ResultList object said we're done, \c false if not.
7560   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7561                        Qualifiers Quals) {
7562     // C++2a [class.compare.default]p4:
7563     //   The direct base class subobjects of C
7564     for (CXXBaseSpecifier &Base : Record->bases())
7565       if (Results.add(getDerived().visitSubobject(
7566               S.Context.getQualifiedType(Base.getType(), Quals),
7567               getDerived().getBase(&Base))))
7568         return true;
7569 
7570     //   followed by the non-static data members of C
7571     for (FieldDecl *Field : Record->fields()) {
7572       // Recursively expand anonymous structs.
7573       if (Field->isAnonymousStructOrUnion()) {
7574         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7575                             Quals))
7576           return true;
7577         continue;
7578       }
7579 
7580       // Figure out the type of an lvalue denoting this field.
7581       Qualifiers FieldQuals = Quals;
7582       if (Field->isMutable())
7583         FieldQuals.removeConst();
7584       QualType FieldType =
7585           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7586 
7587       if (Results.add(getDerived().visitSubobject(
7588               FieldType, getDerived().getField(Field))))
7589         return true;
7590     }
7591 
7592     //   form a list of subobjects.
7593     return false;
7594   }
7595 
7596   Result visitSubobject(QualType Type, Subobject Subobj) {
7597     //   In that list, any subobject of array type is recursively expanded
7598     const ArrayType *AT = S.Context.getAsArrayType(Type);
7599     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7600       return getDerived().visitSubobjectArray(CAT->getElementType(),
7601                                               CAT->getSize(), Subobj);
7602     return getDerived().visitExpandedSubobject(Type, Subobj);
7603   }
7604 
7605   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7606                              Subobject Subobj) {
7607     return getDerived().visitSubobject(Type, Subobj);
7608   }
7609 
7610 protected:
7611   Sema &S;
7612   CXXRecordDecl *RD;
7613   FunctionDecl *FD;
7614   DefaultedComparisonKind DCK;
7615   UnresolvedSet<16> Fns;
7616 };
7617 
7618 /// Information about a defaulted comparison, as determined by
7619 /// DefaultedComparisonAnalyzer.
7620 struct DefaultedComparisonInfo {
7621   bool Deleted = false;
7622   bool Constexpr = true;
7623   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7624 
7625   static DefaultedComparisonInfo deleted() {
7626     DefaultedComparisonInfo Deleted;
7627     Deleted.Deleted = true;
7628     return Deleted;
7629   }
7630 
7631   bool add(const DefaultedComparisonInfo &R) {
7632     Deleted |= R.Deleted;
7633     Constexpr &= R.Constexpr;
7634     Category = commonComparisonType(Category, R.Category);
7635     return Deleted;
7636   }
7637 };
7638 
7639 /// An element in the expanded list of subobjects of a defaulted comparison, as
7640 /// specified in C++2a [class.compare.default]p4.
7641 struct DefaultedComparisonSubobject {
7642   enum { CompleteObject, Member, Base } Kind;
7643   NamedDecl *Decl;
7644   SourceLocation Loc;
7645 };
7646 
7647 /// A visitor over the notional body of a defaulted comparison that determines
7648 /// whether that body would be deleted or constexpr.
7649 class DefaultedComparisonAnalyzer
7650     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7651                                         DefaultedComparisonInfo,
7652                                         DefaultedComparisonInfo,
7653                                         DefaultedComparisonSubobject> {
7654 public:
7655   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7656 
7657 private:
7658   DiagnosticKind Diagnose;
7659 
7660 public:
7661   using Base = DefaultedComparisonVisitor;
7662   using Result = DefaultedComparisonInfo;
7663   using Subobject = DefaultedComparisonSubobject;
7664 
7665   friend Base;
7666 
7667   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7668                               DefaultedComparisonKind DCK,
7669                               DiagnosticKind Diagnose = NoDiagnostics)
7670       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7671 
7672   Result visit() {
7673     if ((DCK == DefaultedComparisonKind::Equal ||
7674          DCK == DefaultedComparisonKind::ThreeWay) &&
7675         RD->hasVariantMembers()) {
7676       // C++2a [class.compare.default]p2 [P2002R0]:
7677       //   A defaulted comparison operator function for class C is defined as
7678       //   deleted if [...] C has variant members.
7679       if (Diagnose == ExplainDeleted) {
7680         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7681           << FD << RD->isUnion() << RD;
7682       }
7683       return Result::deleted();
7684     }
7685 
7686     return Base::visit();
7687   }
7688 
7689 private:
7690   Subobject getCompleteObject() {
7691     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7692   }
7693 
7694   Subobject getBase(CXXBaseSpecifier *Base) {
7695     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7696                      Base->getBaseTypeLoc()};
7697   }
7698 
7699   Subobject getField(FieldDecl *Field) {
7700     return Subobject{Subobject::Member, Field, Field->getLocation()};
7701   }
7702 
7703   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7704     // C++2a [class.compare.default]p2 [P2002R0]:
7705     //   A defaulted <=> or == operator function for class C is defined as
7706     //   deleted if any non-static data member of C is of reference type
7707     if (Type->isReferenceType()) {
7708       if (Diagnose == ExplainDeleted) {
7709         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7710             << FD << RD;
7711       }
7712       return Result::deleted();
7713     }
7714 
7715     // [...] Let xi be an lvalue denoting the ith element [...]
7716     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7717     Expr *Args[] = {&Xi, &Xi};
7718 
7719     // All operators start by trying to apply that same operator recursively.
7720     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7721     assert(OO != OO_None && "not an overloaded operator!");
7722     return visitBinaryOperator(OO, Args, Subobj);
7723   }
7724 
7725   Result
7726   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7727                       Subobject Subobj,
7728                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7729     // Note that there is no need to consider rewritten candidates here if
7730     // we've already found there is no viable 'operator<=>' candidate (and are
7731     // considering synthesizing a '<=>' from '==' and '<').
7732     OverloadCandidateSet CandidateSet(
7733         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7734         OverloadCandidateSet::OperatorRewriteInfo(
7735             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7736 
7737     /// C++2a [class.compare.default]p1 [P2002R0]:
7738     ///   [...] the defaulted function itself is never a candidate for overload
7739     ///   resolution [...]
7740     CandidateSet.exclude(FD);
7741 
7742     if (Args[0]->getType()->isOverloadableType())
7743       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7744     else if (OO == OO_EqualEqual ||
7745              !Args[0]->getType()->isFunctionPointerType()) {
7746       // FIXME: We determine whether this is a valid expression by checking to
7747       // see if there's a viable builtin operator candidate for it. That isn't
7748       // really what the rules ask us to do, but should give the right results.
7749       //
7750       // Note that the builtin operator for relational comparisons on function
7751       // pointers is the only known case which cannot be used.
7752       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7753     }
7754 
7755     Result R;
7756 
7757     OverloadCandidateSet::iterator Best;
7758     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7759     case OR_Success: {
7760       // C++2a [class.compare.secondary]p2 [P2002R0]:
7761       //   The operator function [...] is defined as deleted if [...] the
7762       //   candidate selected by overload resolution is not a rewritten
7763       //   candidate.
7764       if ((DCK == DefaultedComparisonKind::NotEqual ||
7765            DCK == DefaultedComparisonKind::Relational) &&
7766           !Best->RewriteKind) {
7767         if (Diagnose == ExplainDeleted) {
7768           S.Diag(Best->Function->getLocation(),
7769                  diag::note_defaulted_comparison_not_rewritten_callee)
7770               << FD;
7771         }
7772         return Result::deleted();
7773       }
7774 
7775       // Throughout C++2a [class.compare]: if overload resolution does not
7776       // result in a usable function, the candidate function is defined as
7777       // deleted. This requires that we selected an accessible function.
7778       //
7779       // Note that this only considers the access of the function when named
7780       // within the type of the subobject, and not the access path for any
7781       // derived-to-base conversion.
7782       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7783       if (ArgClass && Best->FoundDecl.getDecl() &&
7784           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7785         QualType ObjectType = Subobj.Kind == Subobject::Member
7786                                   ? Args[0]->getType()
7787                                   : S.Context.getRecordType(RD);
7788         if (!S.isMemberAccessibleForDeletion(
7789                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7790                 Diagnose == ExplainDeleted
7791                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7792                           << FD << Subobj.Kind << Subobj.Decl
7793                     : S.PDiag()))
7794           return Result::deleted();
7795       }
7796 
7797       // C++2a [class.compare.default]p3 [P2002R0]:
7798       //   A defaulted comparison function is constexpr-compatible if [...]
7799       //   no overlod resolution performed [...] results in a non-constexpr
7800       //   function.
7801       if (FunctionDecl *BestFD = Best->Function) {
7802         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7803         // If it's not constexpr, explain why not.
7804         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7805           if (Subobj.Kind != Subobject::CompleteObject)
7806             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7807               << Subobj.Kind << Subobj.Decl;
7808           S.Diag(BestFD->getLocation(),
7809                  diag::note_defaulted_comparison_not_constexpr_here);
7810           // Bail out after explaining; we don't want any more notes.
7811           return Result::deleted();
7812         }
7813         R.Constexpr &= BestFD->isConstexpr();
7814       }
7815 
7816       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7817         if (auto *BestFD = Best->Function) {
7818           // If any callee has an undeduced return type, deduce it now.
7819           // FIXME: It's not clear how a failure here should be handled. For
7820           // now, we produce an eager diagnostic, because that is forward
7821           // compatible with most (all?) other reasonable options.
7822           if (BestFD->getReturnType()->isUndeducedType() &&
7823               S.DeduceReturnType(BestFD, FD->getLocation(),
7824                                  /*Diagnose=*/false)) {
7825             // Don't produce a duplicate error when asked to explain why the
7826             // comparison is deleted: we diagnosed that when initially checking
7827             // the defaulted operator.
7828             if (Diagnose == NoDiagnostics) {
7829               S.Diag(
7830                   FD->getLocation(),
7831                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7832                   << Subobj.Kind << Subobj.Decl;
7833               S.Diag(
7834                   Subobj.Loc,
7835                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7836                   << Subobj.Kind << Subobj.Decl;
7837               S.Diag(BestFD->getLocation(),
7838                      diag::note_defaulted_comparison_cannot_deduce_callee)
7839                   << Subobj.Kind << Subobj.Decl;
7840             }
7841             return Result::deleted();
7842           }
7843           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7844               BestFD->getCallResultType())) {
7845             R.Category = Info->Kind;
7846           } else {
7847             if (Diagnose == ExplainDeleted) {
7848               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7849                   << Subobj.Kind << Subobj.Decl
7850                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7851               S.Diag(BestFD->getLocation(),
7852                      diag::note_defaulted_comparison_cannot_deduce_callee)
7853                   << Subobj.Kind << Subobj.Decl;
7854             }
7855             return Result::deleted();
7856           }
7857         } else {
7858           Optional<ComparisonCategoryType> Cat =
7859               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7860           assert(Cat && "no category for builtin comparison?");
7861           R.Category = *Cat;
7862         }
7863       }
7864 
7865       // Note that we might be rewriting to a different operator. That call is
7866       // not considered until we come to actually build the comparison function.
7867       break;
7868     }
7869 
7870     case OR_Ambiguous:
7871       if (Diagnose == ExplainDeleted) {
7872         unsigned Kind = 0;
7873         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7874           Kind = OO == OO_EqualEqual ? 1 : 2;
7875         CandidateSet.NoteCandidates(
7876             PartialDiagnosticAt(
7877                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7878                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7879             S, OCD_AmbiguousCandidates, Args);
7880       }
7881       R = Result::deleted();
7882       break;
7883 
7884     case OR_Deleted:
7885       if (Diagnose == ExplainDeleted) {
7886         if ((DCK == DefaultedComparisonKind::NotEqual ||
7887              DCK == DefaultedComparisonKind::Relational) &&
7888             !Best->RewriteKind) {
7889           S.Diag(Best->Function->getLocation(),
7890                  diag::note_defaulted_comparison_not_rewritten_callee)
7891               << FD;
7892         } else {
7893           S.Diag(Subobj.Loc,
7894                  diag::note_defaulted_comparison_calls_deleted)
7895               << FD << Subobj.Kind << Subobj.Decl;
7896           S.NoteDeletedFunction(Best->Function);
7897         }
7898       }
7899       R = Result::deleted();
7900       break;
7901 
7902     case OR_No_Viable_Function:
7903       // If there's no usable candidate, we're done unless we can rewrite a
7904       // '<=>' in terms of '==' and '<'.
7905       if (OO == OO_Spaceship &&
7906           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7907         // For any kind of comparison category return type, we need a usable
7908         // '==' and a usable '<'.
7909         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7910                                        &CandidateSet)))
7911           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7912         break;
7913       }
7914 
7915       if (Diagnose == ExplainDeleted) {
7916         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7917             << FD << Subobj.Kind << Subobj.Decl;
7918 
7919         // For a three-way comparison, list both the candidates for the
7920         // original operator and the candidates for the synthesized operator.
7921         if (SpaceshipCandidates) {
7922           SpaceshipCandidates->NoteCandidates(
7923               S, Args,
7924               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7925                                                       Args, FD->getLocation()));
7926           S.Diag(Subobj.Loc,
7927                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7928               << (OO == OO_EqualEqual ? 0 : 1);
7929         }
7930 
7931         CandidateSet.NoteCandidates(
7932             S, Args,
7933             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7934                                             FD->getLocation()));
7935       }
7936       R = Result::deleted();
7937       break;
7938     }
7939 
7940     return R;
7941   }
7942 };
7943 
7944 /// A list of statements.
7945 struct StmtListResult {
7946   bool IsInvalid = false;
7947   llvm::SmallVector<Stmt*, 16> Stmts;
7948 
7949   bool add(const StmtResult &S) {
7950     IsInvalid |= S.isInvalid();
7951     if (IsInvalid)
7952       return true;
7953     Stmts.push_back(S.get());
7954     return false;
7955   }
7956 };
7957 
7958 /// A visitor over the notional body of a defaulted comparison that synthesizes
7959 /// the actual body.
7960 class DefaultedComparisonSynthesizer
7961     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7962                                         StmtListResult, StmtResult,
7963                                         std::pair<ExprResult, ExprResult>> {
7964   SourceLocation Loc;
7965   unsigned ArrayDepth = 0;
7966 
7967 public:
7968   using Base = DefaultedComparisonVisitor;
7969   using ExprPair = std::pair<ExprResult, ExprResult>;
7970 
7971   friend Base;
7972 
7973   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7974                                  DefaultedComparisonKind DCK,
7975                                  SourceLocation BodyLoc)
7976       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7977 
7978   /// Build a suitable function body for this defaulted comparison operator.
7979   StmtResult build() {
7980     Sema::CompoundScopeRAII CompoundScope(S);
7981 
7982     StmtListResult Stmts = visit();
7983     if (Stmts.IsInvalid)
7984       return StmtError();
7985 
7986     ExprResult RetVal;
7987     switch (DCK) {
7988     case DefaultedComparisonKind::None:
7989       llvm_unreachable("not a defaulted comparison");
7990 
7991     case DefaultedComparisonKind::Equal: {
7992       // C++2a [class.eq]p3:
7993       //   [...] compar[e] the corresponding elements [...] until the first
7994       //   index i where xi == yi yields [...] false. If no such index exists,
7995       //   V is true. Otherwise, V is false.
7996       //
7997       // Join the comparisons with '&&'s and return the result. Use a right
7998       // fold (traversing the conditions right-to-left), because that
7999       // short-circuits more naturally.
8000       auto OldStmts = std::move(Stmts.Stmts);
8001       Stmts.Stmts.clear();
8002       ExprResult CmpSoFar;
8003       // Finish a particular comparison chain.
8004       auto FinishCmp = [&] {
8005         if (Expr *Prior = CmpSoFar.get()) {
8006           // Convert the last expression to 'return ...;'
8007           if (RetVal.isUnset() && Stmts.Stmts.empty())
8008             RetVal = CmpSoFar;
8009           // Convert any prior comparison to 'if (!(...)) return false;'
8010           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8011             return true;
8012           CmpSoFar = ExprResult();
8013         }
8014         return false;
8015       };
8016       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8017         Expr *E = dyn_cast<Expr>(EAsStmt);
8018         if (!E) {
8019           // Found an array comparison.
8020           if (FinishCmp() || Stmts.add(EAsStmt))
8021             return StmtError();
8022           continue;
8023         }
8024 
8025         if (CmpSoFar.isUnset()) {
8026           CmpSoFar = E;
8027           continue;
8028         }
8029         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8030         if (CmpSoFar.isInvalid())
8031           return StmtError();
8032       }
8033       if (FinishCmp())
8034         return StmtError();
8035       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8036       //   If no such index exists, V is true.
8037       if (RetVal.isUnset())
8038         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8039       break;
8040     }
8041 
8042     case DefaultedComparisonKind::ThreeWay: {
8043       // Per C++2a [class.spaceship]p3, as a fallback add:
8044       // return static_cast<R>(std::strong_ordering::equal);
8045       QualType StrongOrdering = S.CheckComparisonCategoryType(
8046           ComparisonCategoryType::StrongOrdering, Loc,
8047           Sema::ComparisonCategoryUsage::DefaultedOperator);
8048       if (StrongOrdering.isNull())
8049         return StmtError();
8050       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8051                              .getValueInfo(ComparisonCategoryResult::Equal)
8052                              ->VD;
8053       RetVal = getDecl(EqualVD);
8054       if (RetVal.isInvalid())
8055         return StmtError();
8056       RetVal = buildStaticCastToR(RetVal.get());
8057       break;
8058     }
8059 
8060     case DefaultedComparisonKind::NotEqual:
8061     case DefaultedComparisonKind::Relational:
8062       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8063       break;
8064     }
8065 
8066     // Build the final return statement.
8067     if (RetVal.isInvalid())
8068       return StmtError();
8069     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8070     if (ReturnStmt.isInvalid())
8071       return StmtError();
8072     Stmts.Stmts.push_back(ReturnStmt.get());
8073 
8074     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8075   }
8076 
8077 private:
8078   ExprResult getDecl(ValueDecl *VD) {
8079     return S.BuildDeclarationNameExpr(
8080         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8081   }
8082 
8083   ExprResult getParam(unsigned I) {
8084     ParmVarDecl *PD = FD->getParamDecl(I);
8085     return getDecl(PD);
8086   }
8087 
8088   ExprPair getCompleteObject() {
8089     unsigned Param = 0;
8090     ExprResult LHS;
8091     if (isa<CXXMethodDecl>(FD)) {
8092       // LHS is '*this'.
8093       LHS = S.ActOnCXXThis(Loc);
8094       if (!LHS.isInvalid())
8095         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8096     } else {
8097       LHS = getParam(Param++);
8098     }
8099     ExprResult RHS = getParam(Param++);
8100     assert(Param == FD->getNumParams());
8101     return {LHS, RHS};
8102   }
8103 
8104   ExprPair getBase(CXXBaseSpecifier *Base) {
8105     ExprPair Obj = getCompleteObject();
8106     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8107       return {ExprError(), ExprError()};
8108     CXXCastPath Path = {Base};
8109     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8110                                 CK_DerivedToBase, VK_LValue, &Path),
8111             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8112                                 CK_DerivedToBase, VK_LValue, &Path)};
8113   }
8114 
8115   ExprPair getField(FieldDecl *Field) {
8116     ExprPair Obj = getCompleteObject();
8117     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8118       return {ExprError(), ExprError()};
8119 
8120     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8121     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8122     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8123                                       CXXScopeSpec(), Field, Found, NameInfo),
8124             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8125                                       CXXScopeSpec(), Field, Found, NameInfo)};
8126   }
8127 
8128   // FIXME: When expanding a subobject, register a note in the code synthesis
8129   // stack to say which subobject we're comparing.
8130 
8131   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8132     if (Cond.isInvalid())
8133       return StmtError();
8134 
8135     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8136     if (NotCond.isInvalid())
8137       return StmtError();
8138 
8139     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8140     assert(!False.isInvalid() && "should never fail");
8141     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8142     if (ReturnFalse.isInvalid())
8143       return StmtError();
8144 
8145     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8146                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8147                                           Sema::ConditionKind::Boolean),
8148                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8149   }
8150 
8151   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8152                                  ExprPair Subobj) {
8153     QualType SizeType = S.Context.getSizeType();
8154     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8155 
8156     // Build 'size_t i$n = 0'.
8157     IdentifierInfo *IterationVarName = nullptr;
8158     {
8159       SmallString<8> Str;
8160       llvm::raw_svector_ostream OS(Str);
8161       OS << "i" << ArrayDepth;
8162       IterationVarName = &S.Context.Idents.get(OS.str());
8163     }
8164     VarDecl *IterationVar = VarDecl::Create(
8165         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8166         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8167     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8168     IterationVar->setInit(
8169         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8170     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8171 
8172     auto IterRef = [&] {
8173       ExprResult Ref = S.BuildDeclarationNameExpr(
8174           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8175           IterationVar);
8176       assert(!Ref.isInvalid() && "can't reference our own variable?");
8177       return Ref.get();
8178     };
8179 
8180     // Build 'i$n != Size'.
8181     ExprResult Cond = S.CreateBuiltinBinOp(
8182         Loc, BO_NE, IterRef(),
8183         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8184     assert(!Cond.isInvalid() && "should never fail");
8185 
8186     // Build '++i$n'.
8187     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8188     assert(!Inc.isInvalid() && "should never fail");
8189 
8190     // Build 'a[i$n]' and 'b[i$n]'.
8191     auto Index = [&](ExprResult E) {
8192       if (E.isInvalid())
8193         return ExprError();
8194       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8195     };
8196     Subobj.first = Index(Subobj.first);
8197     Subobj.second = Index(Subobj.second);
8198 
8199     // Compare the array elements.
8200     ++ArrayDepth;
8201     StmtResult Substmt = visitSubobject(Type, Subobj);
8202     --ArrayDepth;
8203 
8204     if (Substmt.isInvalid())
8205       return StmtError();
8206 
8207     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8208     // For outer levels or for an 'operator<=>' we already have a suitable
8209     // statement that returns as necessary.
8210     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8211       assert(DCK == DefaultedComparisonKind::Equal &&
8212              "should have non-expression statement");
8213       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8214       if (Substmt.isInvalid())
8215         return StmtError();
8216     }
8217 
8218     // Build 'for (...) ...'
8219     return S.ActOnForStmt(Loc, Loc, Init,
8220                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8221                                            Sema::ConditionKind::Boolean),
8222                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8223                           Substmt.get());
8224   }
8225 
8226   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8227     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8228       return StmtError();
8229 
8230     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8231     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8232     ExprResult Op;
8233     if (Type->isOverloadableType())
8234       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8235                                    Obj.second.get(), /*PerformADL=*/true,
8236                                    /*AllowRewrittenCandidates=*/true, FD);
8237     else
8238       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8239     if (Op.isInvalid())
8240       return StmtError();
8241 
8242     switch (DCK) {
8243     case DefaultedComparisonKind::None:
8244       llvm_unreachable("not a defaulted comparison");
8245 
8246     case DefaultedComparisonKind::Equal:
8247       // Per C++2a [class.eq]p2, each comparison is individually contextually
8248       // converted to bool.
8249       Op = S.PerformContextuallyConvertToBool(Op.get());
8250       if (Op.isInvalid())
8251         return StmtError();
8252       return Op.get();
8253 
8254     case DefaultedComparisonKind::ThreeWay: {
8255       // Per C++2a [class.spaceship]p3, form:
8256       //   if (R cmp = static_cast<R>(op); cmp != 0)
8257       //     return cmp;
8258       QualType R = FD->getReturnType();
8259       Op = buildStaticCastToR(Op.get());
8260       if (Op.isInvalid())
8261         return StmtError();
8262 
8263       // R cmp = ...;
8264       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8265       VarDecl *VD =
8266           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8267                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8268       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8269       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8270 
8271       // cmp != 0
8272       ExprResult VDRef = getDecl(VD);
8273       if (VDRef.isInvalid())
8274         return StmtError();
8275       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8276       Expr *Zero =
8277           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8278       ExprResult Comp;
8279       if (VDRef.get()->getType()->isOverloadableType())
8280         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8281                                        true, FD);
8282       else
8283         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8284       if (Comp.isInvalid())
8285         return StmtError();
8286       Sema::ConditionResult Cond = S.ActOnCondition(
8287           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8288       if (Cond.isInvalid())
8289         return StmtError();
8290 
8291       // return cmp;
8292       VDRef = getDecl(VD);
8293       if (VDRef.isInvalid())
8294         return StmtError();
8295       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8296       if (ReturnStmt.isInvalid())
8297         return StmtError();
8298 
8299       // if (...)
8300       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8301                            ReturnStmt.get(),
8302                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8303     }
8304 
8305     case DefaultedComparisonKind::NotEqual:
8306     case DefaultedComparisonKind::Relational:
8307       // C++2a [class.compare.secondary]p2:
8308       //   Otherwise, the operator function yields x @ y.
8309       return Op.get();
8310     }
8311     llvm_unreachable("");
8312   }
8313 
8314   /// Build "static_cast<R>(E)".
8315   ExprResult buildStaticCastToR(Expr *E) {
8316     QualType R = FD->getReturnType();
8317     assert(!R->isUndeducedType() && "type should have been deduced already");
8318 
8319     // Don't bother forming a no-op cast in the common case.
8320     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8321       return E;
8322     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8323                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8324                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8325   }
8326 };
8327 }
8328 
8329 /// Perform the unqualified lookups that might be needed to form a defaulted
8330 /// comparison function for the given operator.
8331 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8332                                                   UnresolvedSetImpl &Operators,
8333                                                   OverloadedOperatorKind Op) {
8334   auto Lookup = [&](OverloadedOperatorKind OO) {
8335     Self.LookupOverloadedOperatorName(OO, S, Operators);
8336   };
8337 
8338   // Every defaulted operator looks up itself.
8339   Lookup(Op);
8340   // ... and the rewritten form of itself, if any.
8341   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8342     Lookup(ExtraOp);
8343 
8344   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8345   // synthesize a three-way comparison from '<' and '=='. In a dependent
8346   // context, we also need to look up '==' in case we implicitly declare a
8347   // defaulted 'operator=='.
8348   if (Op == OO_Spaceship) {
8349     Lookup(OO_ExclaimEqual);
8350     Lookup(OO_Less);
8351     Lookup(OO_EqualEqual);
8352   }
8353 }
8354 
8355 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8356                                               DefaultedComparisonKind DCK) {
8357   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8358 
8359   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8360   assert(RD && "defaulted comparison is not defaulted in a class");
8361 
8362   // Perform any unqualified lookups we're going to need to default this
8363   // function.
8364   if (S) {
8365     UnresolvedSet<32> Operators;
8366     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8367                                           FD->getOverloadedOperator());
8368     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8369         Context, Operators.pairs()));
8370   }
8371 
8372   // C++2a [class.compare.default]p1:
8373   //   A defaulted comparison operator function for some class C shall be a
8374   //   non-template function declared in the member-specification of C that is
8375   //    -- a non-static const member of C having one parameter of type
8376   //       const C&, or
8377   //    -- a friend of C having two parameters of type const C& or two
8378   //       parameters of type C.
8379   QualType ExpectedParmType1 = Context.getRecordType(RD);
8380   QualType ExpectedParmType2 =
8381       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8382   if (isa<CXXMethodDecl>(FD))
8383     ExpectedParmType1 = ExpectedParmType2;
8384   for (const ParmVarDecl *Param : FD->parameters()) {
8385     if (!Param->getType()->isDependentType() &&
8386         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8387         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8388       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8389       // corresponding defaulted 'operator<=>' already.
8390       if (!FD->isImplicit()) {
8391         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8392             << (int)DCK << Param->getType() << ExpectedParmType1
8393             << !isa<CXXMethodDecl>(FD)
8394             << ExpectedParmType2 << Param->getSourceRange();
8395       }
8396       return true;
8397     }
8398   }
8399   if (FD->getNumParams() == 2 &&
8400       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8401                            FD->getParamDecl(1)->getType())) {
8402     if (!FD->isImplicit()) {
8403       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8404           << (int)DCK
8405           << FD->getParamDecl(0)->getType()
8406           << FD->getParamDecl(0)->getSourceRange()
8407           << FD->getParamDecl(1)->getType()
8408           << FD->getParamDecl(1)->getSourceRange();
8409     }
8410     return true;
8411   }
8412 
8413   // ... non-static const member ...
8414   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8415     assert(!MD->isStatic() && "comparison function cannot be a static member");
8416     if (!MD->isConst()) {
8417       SourceLocation InsertLoc;
8418       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8419         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8420       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8421       // corresponding defaulted 'operator<=>' already.
8422       if (!MD->isImplicit()) {
8423         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8424           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8425       }
8426 
8427       // Add the 'const' to the type to recover.
8428       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8429       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8430       EPI.TypeQuals.addConst();
8431       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8432                                           FPT->getParamTypes(), EPI));
8433     }
8434   } else {
8435     // A non-member function declared in a class must be a friend.
8436     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8437   }
8438 
8439   // C++2a [class.eq]p1, [class.rel]p1:
8440   //   A [defaulted comparison other than <=>] shall have a declared return
8441   //   type bool.
8442   if (DCK != DefaultedComparisonKind::ThreeWay &&
8443       !FD->getDeclaredReturnType()->isDependentType() &&
8444       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8445     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8446         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8447         << FD->getReturnTypeSourceRange();
8448     return true;
8449   }
8450   // C++2a [class.spaceship]p2 [P2002R0]:
8451   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8452   //   R shall not contain a placeholder type.
8453   if (DCK == DefaultedComparisonKind::ThreeWay &&
8454       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8455       !Context.hasSameType(FD->getDeclaredReturnType(),
8456                            Context.getAutoDeductType())) {
8457     Diag(FD->getLocation(),
8458          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8459         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8460         << FD->getReturnTypeSourceRange();
8461     return true;
8462   }
8463 
8464   // For a defaulted function in a dependent class, defer all remaining checks
8465   // until instantiation.
8466   if (RD->isDependentType())
8467     return false;
8468 
8469   // Determine whether the function should be defined as deleted.
8470   DefaultedComparisonInfo Info =
8471       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8472 
8473   bool First = FD == FD->getCanonicalDecl();
8474 
8475   // If we want to delete the function, then do so; there's nothing else to
8476   // check in that case.
8477   if (Info.Deleted) {
8478     if (!First) {
8479       // C++11 [dcl.fct.def.default]p4:
8480       //   [For a] user-provided explicitly-defaulted function [...] if such a
8481       //   function is implicitly defined as deleted, the program is ill-formed.
8482       //
8483       // This is really just a consequence of the general rule that you can
8484       // only delete a function on its first declaration.
8485       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8486           << FD->isImplicit() << (int)DCK;
8487       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8488                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8489           .visit();
8490       return true;
8491     }
8492 
8493     SetDeclDeleted(FD, FD->getLocation());
8494     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8495       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8496           << (int)DCK;
8497       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8498                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8499           .visit();
8500     }
8501     return false;
8502   }
8503 
8504   // C++2a [class.spaceship]p2:
8505   //   The return type is deduced as the common comparison type of R0, R1, ...
8506   if (DCK == DefaultedComparisonKind::ThreeWay &&
8507       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8508     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8509     if (RetLoc.isInvalid())
8510       RetLoc = FD->getBeginLoc();
8511     // FIXME: Should we really care whether we have the complete type and the
8512     // 'enumerator' constants here? A forward declaration seems sufficient.
8513     QualType Cat = CheckComparisonCategoryType(
8514         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8515     if (Cat.isNull())
8516       return true;
8517     Context.adjustDeducedFunctionResultType(
8518         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8519   }
8520 
8521   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8522   //   An explicitly-defaulted function that is not defined as deleted may be
8523   //   declared constexpr or consteval only if it is constexpr-compatible.
8524   // C++2a [class.compare.default]p3 [P2002R0]:
8525   //   A defaulted comparison function is constexpr-compatible if it satisfies
8526   //   the requirements for a constexpr function [...]
8527   // The only relevant requirements are that the parameter and return types are
8528   // literal types. The remaining conditions are checked by the analyzer.
8529   if (FD->isConstexpr()) {
8530     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8531         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8532         !Info.Constexpr) {
8533       Diag(FD->getBeginLoc(),
8534            diag::err_incorrect_defaulted_comparison_constexpr)
8535           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8536       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8537                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8538           .visit();
8539     }
8540   }
8541 
8542   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8543   //   If a constexpr-compatible function is explicitly defaulted on its first
8544   //   declaration, it is implicitly considered to be constexpr.
8545   // FIXME: Only applying this to the first declaration seems problematic, as
8546   // simple reorderings can affect the meaning of the program.
8547   if (First && !FD->isConstexpr() && Info.Constexpr)
8548     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8549 
8550   // C++2a [except.spec]p3:
8551   //   If a declaration of a function does not have a noexcept-specifier
8552   //   [and] is defaulted on its first declaration, [...] the exception
8553   //   specification is as specified below
8554   if (FD->getExceptionSpecType() == EST_None) {
8555     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8556     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8557     EPI.ExceptionSpec.Type = EST_Unevaluated;
8558     EPI.ExceptionSpec.SourceDecl = FD;
8559     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8560                                         FPT->getParamTypes(), EPI));
8561   }
8562 
8563   return false;
8564 }
8565 
8566 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8567                                              FunctionDecl *Spaceship) {
8568   Sema::CodeSynthesisContext Ctx;
8569   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8570   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8571   Ctx.Entity = Spaceship;
8572   pushCodeSynthesisContext(Ctx);
8573 
8574   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8575     EqualEqual->setImplicit();
8576 
8577   popCodeSynthesisContext();
8578 }
8579 
8580 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8581                                      DefaultedComparisonKind DCK) {
8582   assert(FD->isDefaulted() && !FD->isDeleted() &&
8583          !FD->doesThisDeclarationHaveABody());
8584   if (FD->willHaveBody() || FD->isInvalidDecl())
8585     return;
8586 
8587   SynthesizedFunctionScope Scope(*this, FD);
8588 
8589   // Add a context note for diagnostics produced after this point.
8590   Scope.addContextNote(UseLoc);
8591 
8592   {
8593     // Build and set up the function body.
8594     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8595     SourceLocation BodyLoc =
8596         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8597     StmtResult Body =
8598         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8599     if (Body.isInvalid()) {
8600       FD->setInvalidDecl();
8601       return;
8602     }
8603     FD->setBody(Body.get());
8604     FD->markUsed(Context);
8605   }
8606 
8607   // The exception specification is needed because we are defining the
8608   // function. Note that this will reuse the body we just built.
8609   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8610 
8611   if (ASTMutationListener *L = getASTMutationListener())
8612     L->CompletedImplicitDefinition(FD);
8613 }
8614 
8615 static Sema::ImplicitExceptionSpecification
8616 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8617                                         FunctionDecl *FD,
8618                                         Sema::DefaultedComparisonKind DCK) {
8619   ComputingExceptionSpec CES(S, FD, Loc);
8620   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8621 
8622   if (FD->isInvalidDecl())
8623     return ExceptSpec;
8624 
8625   // The common case is that we just defined the comparison function. In that
8626   // case, just look at whether the body can throw.
8627   if (FD->hasBody()) {
8628     ExceptSpec.CalledStmt(FD->getBody());
8629   } else {
8630     // Otherwise, build a body so we can check it. This should ideally only
8631     // happen when we're not actually marking the function referenced. (This is
8632     // only really important for efficiency: we don't want to build and throw
8633     // away bodies for comparison functions more than we strictly need to.)
8634 
8635     // Pretend to synthesize the function body in an unevaluated context.
8636     // Note that we can't actually just go ahead and define the function here:
8637     // we are not permitted to mark its callees as referenced.
8638     Sema::SynthesizedFunctionScope Scope(S, FD);
8639     EnterExpressionEvaluationContext Context(
8640         S, Sema::ExpressionEvaluationContext::Unevaluated);
8641 
8642     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8643     SourceLocation BodyLoc =
8644         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8645     StmtResult Body =
8646         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8647     if (!Body.isInvalid())
8648       ExceptSpec.CalledStmt(Body.get());
8649 
8650     // FIXME: Can we hold onto this body and just transform it to potentially
8651     // evaluated when we're asked to define the function rather than rebuilding
8652     // it? Either that, or we should only build the bits of the body that we
8653     // need (the expressions, not the statements).
8654   }
8655 
8656   return ExceptSpec;
8657 }
8658 
8659 void Sema::CheckDelayedMemberExceptionSpecs() {
8660   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8661   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8662 
8663   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8664   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8665 
8666   // Perform any deferred checking of exception specifications for virtual
8667   // destructors.
8668   for (auto &Check : Overriding)
8669     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8670 
8671   // Perform any deferred checking of exception specifications for befriended
8672   // special members.
8673   for (auto &Check : Equivalent)
8674     CheckEquivalentExceptionSpec(Check.second, Check.first);
8675 }
8676 
8677 namespace {
8678 /// CRTP base class for visiting operations performed by a special member
8679 /// function (or inherited constructor).
8680 template<typename Derived>
8681 struct SpecialMemberVisitor {
8682   Sema &S;
8683   CXXMethodDecl *MD;
8684   Sema::CXXSpecialMember CSM;
8685   Sema::InheritedConstructorInfo *ICI;
8686 
8687   // Properties of the special member, computed for convenience.
8688   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8689 
8690   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8691                        Sema::InheritedConstructorInfo *ICI)
8692       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8693     switch (CSM) {
8694     case Sema::CXXDefaultConstructor:
8695     case Sema::CXXCopyConstructor:
8696     case Sema::CXXMoveConstructor:
8697       IsConstructor = true;
8698       break;
8699     case Sema::CXXCopyAssignment:
8700     case Sema::CXXMoveAssignment:
8701       IsAssignment = true;
8702       break;
8703     case Sema::CXXDestructor:
8704       break;
8705     case Sema::CXXInvalid:
8706       llvm_unreachable("invalid special member kind");
8707     }
8708 
8709     if (MD->getNumParams()) {
8710       if (const ReferenceType *RT =
8711               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8712         ConstArg = RT->getPointeeType().isConstQualified();
8713     }
8714   }
8715 
8716   Derived &getDerived() { return static_cast<Derived&>(*this); }
8717 
8718   /// Is this a "move" special member?
8719   bool isMove() const {
8720     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8721   }
8722 
8723   /// Look up the corresponding special member in the given class.
8724   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8725                                              unsigned Quals, bool IsMutable) {
8726     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8727                                        ConstArg && !IsMutable);
8728   }
8729 
8730   /// Look up the constructor for the specified base class to see if it's
8731   /// overridden due to this being an inherited constructor.
8732   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8733     if (!ICI)
8734       return {};
8735     assert(CSM == Sema::CXXDefaultConstructor);
8736     auto *BaseCtor =
8737       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8738     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8739       return MD;
8740     return {};
8741   }
8742 
8743   /// A base or member subobject.
8744   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8745 
8746   /// Get the location to use for a subobject in diagnostics.
8747   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8748     // FIXME: For an indirect virtual base, the direct base leading to
8749     // the indirect virtual base would be a more useful choice.
8750     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8751       return B->getBaseTypeLoc();
8752     else
8753       return Subobj.get<FieldDecl*>()->getLocation();
8754   }
8755 
8756   enum BasesToVisit {
8757     /// Visit all non-virtual (direct) bases.
8758     VisitNonVirtualBases,
8759     /// Visit all direct bases, virtual or not.
8760     VisitDirectBases,
8761     /// Visit all non-virtual bases, and all virtual bases if the class
8762     /// is not abstract.
8763     VisitPotentiallyConstructedBases,
8764     /// Visit all direct or virtual bases.
8765     VisitAllBases
8766   };
8767 
8768   // Visit the bases and members of the class.
8769   bool visit(BasesToVisit Bases) {
8770     CXXRecordDecl *RD = MD->getParent();
8771 
8772     if (Bases == VisitPotentiallyConstructedBases)
8773       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8774 
8775     for (auto &B : RD->bases())
8776       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8777           getDerived().visitBase(&B))
8778         return true;
8779 
8780     if (Bases == VisitAllBases)
8781       for (auto &B : RD->vbases())
8782         if (getDerived().visitBase(&B))
8783           return true;
8784 
8785     for (auto *F : RD->fields())
8786       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8787           getDerived().visitField(F))
8788         return true;
8789 
8790     return false;
8791   }
8792 };
8793 }
8794 
8795 namespace {
8796 struct SpecialMemberDeletionInfo
8797     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8798   bool Diagnose;
8799 
8800   SourceLocation Loc;
8801 
8802   bool AllFieldsAreConst;
8803 
8804   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8805                             Sema::CXXSpecialMember CSM,
8806                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8807       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8808         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8809 
8810   bool inUnion() const { return MD->getParent()->isUnion(); }
8811 
8812   Sema::CXXSpecialMember getEffectiveCSM() {
8813     return ICI ? Sema::CXXInvalid : CSM;
8814   }
8815 
8816   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8817 
8818   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8819   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8820 
8821   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8822   bool shouldDeleteForField(FieldDecl *FD);
8823   bool shouldDeleteForAllConstMembers();
8824 
8825   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8826                                      unsigned Quals);
8827   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8828                                     Sema::SpecialMemberOverloadResult SMOR,
8829                                     bool IsDtorCallInCtor);
8830 
8831   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8832 };
8833 }
8834 
8835 /// Is the given special member inaccessible when used on the given
8836 /// sub-object.
8837 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8838                                              CXXMethodDecl *target) {
8839   /// If we're operating on a base class, the object type is the
8840   /// type of this special member.
8841   QualType objectTy;
8842   AccessSpecifier access = target->getAccess();
8843   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8844     objectTy = S.Context.getTypeDeclType(MD->getParent());
8845     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8846 
8847   // If we're operating on a field, the object type is the type of the field.
8848   } else {
8849     objectTy = S.Context.getTypeDeclType(target->getParent());
8850   }
8851 
8852   return S.isMemberAccessibleForDeletion(
8853       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8854 }
8855 
8856 /// Check whether we should delete a special member due to the implicit
8857 /// definition containing a call to a special member of a subobject.
8858 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8859     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8860     bool IsDtorCallInCtor) {
8861   CXXMethodDecl *Decl = SMOR.getMethod();
8862   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8863 
8864   int DiagKind = -1;
8865 
8866   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8867     DiagKind = !Decl ? 0 : 1;
8868   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8869     DiagKind = 2;
8870   else if (!isAccessible(Subobj, Decl))
8871     DiagKind = 3;
8872   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8873            !Decl->isTrivial()) {
8874     // A member of a union must have a trivial corresponding special member.
8875     // As a weird special case, a destructor call from a union's constructor
8876     // must be accessible and non-deleted, but need not be trivial. Such a
8877     // destructor is never actually called, but is semantically checked as
8878     // if it were.
8879     DiagKind = 4;
8880   }
8881 
8882   if (DiagKind == -1)
8883     return false;
8884 
8885   if (Diagnose) {
8886     if (Field) {
8887       S.Diag(Field->getLocation(),
8888              diag::note_deleted_special_member_class_subobject)
8889         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8890         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8891     } else {
8892       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8893       S.Diag(Base->getBeginLoc(),
8894              diag::note_deleted_special_member_class_subobject)
8895           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8896           << Base->getType() << DiagKind << IsDtorCallInCtor
8897           << /*IsObjCPtr*/false;
8898     }
8899 
8900     if (DiagKind == 1)
8901       S.NoteDeletedFunction(Decl);
8902     // FIXME: Explain inaccessibility if DiagKind == 3.
8903   }
8904 
8905   return true;
8906 }
8907 
8908 /// Check whether we should delete a special member function due to having a
8909 /// direct or virtual base class or non-static data member of class type M.
8910 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8911     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8912   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8913   bool IsMutable = Field && Field->isMutable();
8914 
8915   // C++11 [class.ctor]p5:
8916   // -- any direct or virtual base class, or non-static data member with no
8917   //    brace-or-equal-initializer, has class type M (or array thereof) and
8918   //    either M has no default constructor or overload resolution as applied
8919   //    to M's default constructor results in an ambiguity or in a function
8920   //    that is deleted or inaccessible
8921   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8922   // -- a direct or virtual base class B that cannot be copied/moved because
8923   //    overload resolution, as applied to B's corresponding special member,
8924   //    results in an ambiguity or a function that is deleted or inaccessible
8925   //    from the defaulted special member
8926   // C++11 [class.dtor]p5:
8927   // -- any direct or virtual base class [...] has a type with a destructor
8928   //    that is deleted or inaccessible
8929   if (!(CSM == Sema::CXXDefaultConstructor &&
8930         Field && Field->hasInClassInitializer()) &&
8931       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8932                                    false))
8933     return true;
8934 
8935   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8936   // -- any direct or virtual base class or non-static data member has a
8937   //    type with a destructor that is deleted or inaccessible
8938   if (IsConstructor) {
8939     Sema::SpecialMemberOverloadResult SMOR =
8940         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8941                               false, false, false, false, false);
8942     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8943       return true;
8944   }
8945 
8946   return false;
8947 }
8948 
8949 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8950     FieldDecl *FD, QualType FieldType) {
8951   // The defaulted special functions are defined as deleted if this is a variant
8952   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8953   // type under ARC.
8954   if (!FieldType.hasNonTrivialObjCLifetime())
8955     return false;
8956 
8957   // Don't make the defaulted default constructor defined as deleted if the
8958   // member has an in-class initializer.
8959   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8960     return false;
8961 
8962   if (Diagnose) {
8963     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8964     S.Diag(FD->getLocation(),
8965            diag::note_deleted_special_member_class_subobject)
8966         << getEffectiveCSM() << ParentClass << /*IsField*/true
8967         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8968   }
8969 
8970   return true;
8971 }
8972 
8973 /// Check whether we should delete a special member function due to the class
8974 /// having a particular direct or virtual base class.
8975 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8976   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8977   // If program is correct, BaseClass cannot be null, but if it is, the error
8978   // must be reported elsewhere.
8979   if (!BaseClass)
8980     return false;
8981   // If we have an inheriting constructor, check whether we're calling an
8982   // inherited constructor instead of a default constructor.
8983   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8984   if (auto *BaseCtor = SMOR.getMethod()) {
8985     // Note that we do not check access along this path; other than that,
8986     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8987     // FIXME: Check that the base has a usable destructor! Sink this into
8988     // shouldDeleteForClassSubobject.
8989     if (BaseCtor->isDeleted() && Diagnose) {
8990       S.Diag(Base->getBeginLoc(),
8991              diag::note_deleted_special_member_class_subobject)
8992           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8993           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8994           << /*IsObjCPtr*/false;
8995       S.NoteDeletedFunction(BaseCtor);
8996     }
8997     return BaseCtor->isDeleted();
8998   }
8999   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9000 }
9001 
9002 /// Check whether we should delete a special member function due to the class
9003 /// having a particular non-static data member.
9004 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9005   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9006   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9007 
9008   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9009     return true;
9010 
9011   if (CSM == Sema::CXXDefaultConstructor) {
9012     // For a default constructor, all references must be initialized in-class
9013     // and, if a union, it must have a non-const member.
9014     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9015       if (Diagnose)
9016         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9017           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9018       return true;
9019     }
9020     // C++11 [class.ctor]p5: any non-variant non-static data member of
9021     // const-qualified type (or array thereof) with no
9022     // brace-or-equal-initializer does not have a user-provided default
9023     // constructor.
9024     if (!inUnion() && FieldType.isConstQualified() &&
9025         !FD->hasInClassInitializer() &&
9026         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9027       if (Diagnose)
9028         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9029           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9030       return true;
9031     }
9032 
9033     if (inUnion() && !FieldType.isConstQualified())
9034       AllFieldsAreConst = false;
9035   } else if (CSM == Sema::CXXCopyConstructor) {
9036     // For a copy constructor, data members must not be of rvalue reference
9037     // type.
9038     if (FieldType->isRValueReferenceType()) {
9039       if (Diagnose)
9040         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9041           << MD->getParent() << FD << FieldType;
9042       return true;
9043     }
9044   } else if (IsAssignment) {
9045     // For an assignment operator, data members must not be of reference type.
9046     if (FieldType->isReferenceType()) {
9047       if (Diagnose)
9048         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9049           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9050       return true;
9051     }
9052     if (!FieldRecord && FieldType.isConstQualified()) {
9053       // C++11 [class.copy]p23:
9054       // -- a non-static data member of const non-class type (or array thereof)
9055       if (Diagnose)
9056         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9057           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9058       return true;
9059     }
9060   }
9061 
9062   if (FieldRecord) {
9063     // Some additional restrictions exist on the variant members.
9064     if (!inUnion() && FieldRecord->isUnion() &&
9065         FieldRecord->isAnonymousStructOrUnion()) {
9066       bool AllVariantFieldsAreConst = true;
9067 
9068       // FIXME: Handle anonymous unions declared within anonymous unions.
9069       for (auto *UI : FieldRecord->fields()) {
9070         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9071 
9072         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9073           return true;
9074 
9075         if (!UnionFieldType.isConstQualified())
9076           AllVariantFieldsAreConst = false;
9077 
9078         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9079         if (UnionFieldRecord &&
9080             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9081                                           UnionFieldType.getCVRQualifiers()))
9082           return true;
9083       }
9084 
9085       // At least one member in each anonymous union must be non-const
9086       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9087           !FieldRecord->field_empty()) {
9088         if (Diagnose)
9089           S.Diag(FieldRecord->getLocation(),
9090                  diag::note_deleted_default_ctor_all_const)
9091             << !!ICI << MD->getParent() << /*anonymous union*/1;
9092         return true;
9093       }
9094 
9095       // Don't check the implicit member of the anonymous union type.
9096       // This is technically non-conformant, but sanity demands it.
9097       return false;
9098     }
9099 
9100     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9101                                       FieldType.getCVRQualifiers()))
9102       return true;
9103   }
9104 
9105   return false;
9106 }
9107 
9108 /// C++11 [class.ctor] p5:
9109 ///   A defaulted default constructor for a class X is defined as deleted if
9110 /// X is a union and all of its variant members are of const-qualified type.
9111 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9112   // This is a silly definition, because it gives an empty union a deleted
9113   // default constructor. Don't do that.
9114   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9115     bool AnyFields = false;
9116     for (auto *F : MD->getParent()->fields())
9117       if ((AnyFields = !F->isUnnamedBitfield()))
9118         break;
9119     if (!AnyFields)
9120       return false;
9121     if (Diagnose)
9122       S.Diag(MD->getParent()->getLocation(),
9123              diag::note_deleted_default_ctor_all_const)
9124         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9125     return true;
9126   }
9127   return false;
9128 }
9129 
9130 /// Determine whether a defaulted special member function should be defined as
9131 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9132 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9133 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9134                                      InheritedConstructorInfo *ICI,
9135                                      bool Diagnose) {
9136   if (MD->isInvalidDecl())
9137     return false;
9138   CXXRecordDecl *RD = MD->getParent();
9139   assert(!RD->isDependentType() && "do deletion after instantiation");
9140   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9141     return false;
9142 
9143   // C++11 [expr.lambda.prim]p19:
9144   //   The closure type associated with a lambda-expression has a
9145   //   deleted (8.4.3) default constructor and a deleted copy
9146   //   assignment operator.
9147   // C++2a adds back these operators if the lambda has no lambda-capture.
9148   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9149       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9150     if (Diagnose)
9151       Diag(RD->getLocation(), diag::note_lambda_decl);
9152     return true;
9153   }
9154 
9155   // For an anonymous struct or union, the copy and assignment special members
9156   // will never be used, so skip the check. For an anonymous union declared at
9157   // namespace scope, the constructor and destructor are used.
9158   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9159       RD->isAnonymousStructOrUnion())
9160     return false;
9161 
9162   // C++11 [class.copy]p7, p18:
9163   //   If the class definition declares a move constructor or move assignment
9164   //   operator, an implicitly declared copy constructor or copy assignment
9165   //   operator is defined as deleted.
9166   if (MD->isImplicit() &&
9167       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9168     CXXMethodDecl *UserDeclaredMove = nullptr;
9169 
9170     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9171     // deletion of the corresponding copy operation, not both copy operations.
9172     // MSVC 2015 has adopted the standards conforming behavior.
9173     bool DeletesOnlyMatchingCopy =
9174         getLangOpts().MSVCCompat &&
9175         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9176 
9177     if (RD->hasUserDeclaredMoveConstructor() &&
9178         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9179       if (!Diagnose) return true;
9180 
9181       // Find any user-declared move constructor.
9182       for (auto *I : RD->ctors()) {
9183         if (I->isMoveConstructor()) {
9184           UserDeclaredMove = I;
9185           break;
9186         }
9187       }
9188       assert(UserDeclaredMove);
9189     } else if (RD->hasUserDeclaredMoveAssignment() &&
9190                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9191       if (!Diagnose) return true;
9192 
9193       // Find any user-declared move assignment operator.
9194       for (auto *I : RD->methods()) {
9195         if (I->isMoveAssignmentOperator()) {
9196           UserDeclaredMove = I;
9197           break;
9198         }
9199       }
9200       assert(UserDeclaredMove);
9201     }
9202 
9203     if (UserDeclaredMove) {
9204       Diag(UserDeclaredMove->getLocation(),
9205            diag::note_deleted_copy_user_declared_move)
9206         << (CSM == CXXCopyAssignment) << RD
9207         << UserDeclaredMove->isMoveAssignmentOperator();
9208       return true;
9209     }
9210   }
9211 
9212   // Do access control from the special member function
9213   ContextRAII MethodContext(*this, MD);
9214 
9215   // C++11 [class.dtor]p5:
9216   // -- for a virtual destructor, lookup of the non-array deallocation function
9217   //    results in an ambiguity or in a function that is deleted or inaccessible
9218   if (CSM == CXXDestructor && MD->isVirtual()) {
9219     FunctionDecl *OperatorDelete = nullptr;
9220     DeclarationName Name =
9221       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9222     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9223                                  OperatorDelete, /*Diagnose*/false)) {
9224       if (Diagnose)
9225         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9226       return true;
9227     }
9228   }
9229 
9230   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9231 
9232   // Per DR1611, do not consider virtual bases of constructors of abstract
9233   // classes, since we are not going to construct them.
9234   // Per DR1658, do not consider virtual bases of destructors of abstract
9235   // classes either.
9236   // Per DR2180, for assignment operators we only assign (and thus only
9237   // consider) direct bases.
9238   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9239                                  : SMI.VisitPotentiallyConstructedBases))
9240     return true;
9241 
9242   if (SMI.shouldDeleteForAllConstMembers())
9243     return true;
9244 
9245   if (getLangOpts().CUDA) {
9246     // We should delete the special member in CUDA mode if target inference
9247     // failed.
9248     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9249     // is treated as certain special member, which may not reflect what special
9250     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9251     // expects CSM to match MD, therefore recalculate CSM.
9252     assert(ICI || CSM == getSpecialMember(MD));
9253     auto RealCSM = CSM;
9254     if (ICI)
9255       RealCSM = getSpecialMember(MD);
9256 
9257     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9258                                                    SMI.ConstArg, Diagnose);
9259   }
9260 
9261   return false;
9262 }
9263 
9264 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9265   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9266   assert(DFK && "not a defaultable function");
9267   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9268 
9269   if (DFK.isSpecialMember()) {
9270     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9271                               nullptr, /*Diagnose=*/true);
9272   } else {
9273     DefaultedComparisonAnalyzer(
9274         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9275         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9276         .visit();
9277   }
9278 }
9279 
9280 /// Perform lookup for a special member of the specified kind, and determine
9281 /// whether it is trivial. If the triviality can be determined without the
9282 /// lookup, skip it. This is intended for use when determining whether a
9283 /// special member of a containing object is trivial, and thus does not ever
9284 /// perform overload resolution for default constructors.
9285 ///
9286 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9287 /// member that was most likely to be intended to be trivial, if any.
9288 ///
9289 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9290 /// determine whether the special member is trivial.
9291 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9292                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9293                                      bool ConstRHS,
9294                                      Sema::TrivialABIHandling TAH,
9295                                      CXXMethodDecl **Selected) {
9296   if (Selected)
9297     *Selected = nullptr;
9298 
9299   switch (CSM) {
9300   case Sema::CXXInvalid:
9301     llvm_unreachable("not a special member");
9302 
9303   case Sema::CXXDefaultConstructor:
9304     // C++11 [class.ctor]p5:
9305     //   A default constructor is trivial if:
9306     //    - all the [direct subobjects] have trivial default constructors
9307     //
9308     // Note, no overload resolution is performed in this case.
9309     if (RD->hasTrivialDefaultConstructor())
9310       return true;
9311 
9312     if (Selected) {
9313       // If there's a default constructor which could have been trivial, dig it
9314       // out. Otherwise, if there's any user-provided default constructor, point
9315       // to that as an example of why there's not a trivial one.
9316       CXXConstructorDecl *DefCtor = nullptr;
9317       if (RD->needsImplicitDefaultConstructor())
9318         S.DeclareImplicitDefaultConstructor(RD);
9319       for (auto *CI : RD->ctors()) {
9320         if (!CI->isDefaultConstructor())
9321           continue;
9322         DefCtor = CI;
9323         if (!DefCtor->isUserProvided())
9324           break;
9325       }
9326 
9327       *Selected = DefCtor;
9328     }
9329 
9330     return false;
9331 
9332   case Sema::CXXDestructor:
9333     // C++11 [class.dtor]p5:
9334     //   A destructor is trivial if:
9335     //    - all the direct [subobjects] have trivial destructors
9336     if (RD->hasTrivialDestructor() ||
9337         (TAH == Sema::TAH_ConsiderTrivialABI &&
9338          RD->hasTrivialDestructorForCall()))
9339       return true;
9340 
9341     if (Selected) {
9342       if (RD->needsImplicitDestructor())
9343         S.DeclareImplicitDestructor(RD);
9344       *Selected = RD->getDestructor();
9345     }
9346 
9347     return false;
9348 
9349   case Sema::CXXCopyConstructor:
9350     // C++11 [class.copy]p12:
9351     //   A copy constructor is trivial if:
9352     //    - the constructor selected to copy each direct [subobject] is trivial
9353     if (RD->hasTrivialCopyConstructor() ||
9354         (TAH == Sema::TAH_ConsiderTrivialABI &&
9355          RD->hasTrivialCopyConstructorForCall())) {
9356       if (Quals == Qualifiers::Const)
9357         // We must either select the trivial copy constructor or reach an
9358         // ambiguity; no need to actually perform overload resolution.
9359         return true;
9360     } else if (!Selected) {
9361       return false;
9362     }
9363     // In C++98, we are not supposed to perform overload resolution here, but we
9364     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9365     // cases like B as having a non-trivial copy constructor:
9366     //   struct A { template<typename T> A(T&); };
9367     //   struct B { mutable A a; };
9368     goto NeedOverloadResolution;
9369 
9370   case Sema::CXXCopyAssignment:
9371     // C++11 [class.copy]p25:
9372     //   A copy assignment operator is trivial if:
9373     //    - the assignment operator selected to copy each direct [subobject] is
9374     //      trivial
9375     if (RD->hasTrivialCopyAssignment()) {
9376       if (Quals == Qualifiers::Const)
9377         return true;
9378     } else if (!Selected) {
9379       return false;
9380     }
9381     // In C++98, we are not supposed to perform overload resolution here, but we
9382     // treat that as a language defect.
9383     goto NeedOverloadResolution;
9384 
9385   case Sema::CXXMoveConstructor:
9386   case Sema::CXXMoveAssignment:
9387   NeedOverloadResolution:
9388     Sema::SpecialMemberOverloadResult SMOR =
9389         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9390 
9391     // The standard doesn't describe how to behave if the lookup is ambiguous.
9392     // We treat it as not making the member non-trivial, just like the standard
9393     // mandates for the default constructor. This should rarely matter, because
9394     // the member will also be deleted.
9395     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9396       return true;
9397 
9398     if (!SMOR.getMethod()) {
9399       assert(SMOR.getKind() ==
9400              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9401       return false;
9402     }
9403 
9404     // We deliberately don't check if we found a deleted special member. We're
9405     // not supposed to!
9406     if (Selected)
9407       *Selected = SMOR.getMethod();
9408 
9409     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9410         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9411       return SMOR.getMethod()->isTrivialForCall();
9412     return SMOR.getMethod()->isTrivial();
9413   }
9414 
9415   llvm_unreachable("unknown special method kind");
9416 }
9417 
9418 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9419   for (auto *CI : RD->ctors())
9420     if (!CI->isImplicit())
9421       return CI;
9422 
9423   // Look for constructor templates.
9424   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9425   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9426     if (CXXConstructorDecl *CD =
9427           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9428       return CD;
9429   }
9430 
9431   return nullptr;
9432 }
9433 
9434 /// The kind of subobject we are checking for triviality. The values of this
9435 /// enumeration are used in diagnostics.
9436 enum TrivialSubobjectKind {
9437   /// The subobject is a base class.
9438   TSK_BaseClass,
9439   /// The subobject is a non-static data member.
9440   TSK_Field,
9441   /// The object is actually the complete object.
9442   TSK_CompleteObject
9443 };
9444 
9445 /// Check whether the special member selected for a given type would be trivial.
9446 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9447                                       QualType SubType, bool ConstRHS,
9448                                       Sema::CXXSpecialMember CSM,
9449                                       TrivialSubobjectKind Kind,
9450                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9451   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9452   if (!SubRD)
9453     return true;
9454 
9455   CXXMethodDecl *Selected;
9456   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9457                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9458     return true;
9459 
9460   if (Diagnose) {
9461     if (ConstRHS)
9462       SubType.addConst();
9463 
9464     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9465       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9466         << Kind << SubType.getUnqualifiedType();
9467       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9468         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9469     } else if (!Selected)
9470       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9471         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9472     else if (Selected->isUserProvided()) {
9473       if (Kind == TSK_CompleteObject)
9474         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9475           << Kind << SubType.getUnqualifiedType() << CSM;
9476       else {
9477         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9478           << Kind << SubType.getUnqualifiedType() << CSM;
9479         S.Diag(Selected->getLocation(), diag::note_declared_at);
9480       }
9481     } else {
9482       if (Kind != TSK_CompleteObject)
9483         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9484           << Kind << SubType.getUnqualifiedType() << CSM;
9485 
9486       // Explain why the defaulted or deleted special member isn't trivial.
9487       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9488                                Diagnose);
9489     }
9490   }
9491 
9492   return false;
9493 }
9494 
9495 /// Check whether the members of a class type allow a special member to be
9496 /// trivial.
9497 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9498                                      Sema::CXXSpecialMember CSM,
9499                                      bool ConstArg,
9500                                      Sema::TrivialABIHandling TAH,
9501                                      bool Diagnose) {
9502   for (const auto *FI : RD->fields()) {
9503     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9504       continue;
9505 
9506     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9507 
9508     // Pretend anonymous struct or union members are members of this class.
9509     if (FI->isAnonymousStructOrUnion()) {
9510       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9511                                     CSM, ConstArg, TAH, Diagnose))
9512         return false;
9513       continue;
9514     }
9515 
9516     // C++11 [class.ctor]p5:
9517     //   A default constructor is trivial if [...]
9518     //    -- no non-static data member of its class has a
9519     //       brace-or-equal-initializer
9520     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9521       if (Diagnose)
9522         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9523             << FI;
9524       return false;
9525     }
9526 
9527     // Objective C ARC 4.3.5:
9528     //   [...] nontrivally ownership-qualified types are [...] not trivially
9529     //   default constructible, copy constructible, move constructible, copy
9530     //   assignable, move assignable, or destructible [...]
9531     if (FieldType.hasNonTrivialObjCLifetime()) {
9532       if (Diagnose)
9533         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9534           << RD << FieldType.getObjCLifetime();
9535       return false;
9536     }
9537 
9538     bool ConstRHS = ConstArg && !FI->isMutable();
9539     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9540                                    CSM, TSK_Field, TAH, Diagnose))
9541       return false;
9542   }
9543 
9544   return true;
9545 }
9546 
9547 /// Diagnose why the specified class does not have a trivial special member of
9548 /// the given kind.
9549 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9550   QualType Ty = Context.getRecordType(RD);
9551 
9552   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9553   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9554                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9555                             /*Diagnose*/true);
9556 }
9557 
9558 /// Determine whether a defaulted or deleted special member function is trivial,
9559 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9560 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9561 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9562                                   TrivialABIHandling TAH, bool Diagnose) {
9563   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9564 
9565   CXXRecordDecl *RD = MD->getParent();
9566 
9567   bool ConstArg = false;
9568 
9569   // C++11 [class.copy]p12, p25: [DR1593]
9570   //   A [special member] is trivial if [...] its parameter-type-list is
9571   //   equivalent to the parameter-type-list of an implicit declaration [...]
9572   switch (CSM) {
9573   case CXXDefaultConstructor:
9574   case CXXDestructor:
9575     // Trivial default constructors and destructors cannot have parameters.
9576     break;
9577 
9578   case CXXCopyConstructor:
9579   case CXXCopyAssignment: {
9580     // Trivial copy operations always have const, non-volatile parameter types.
9581     ConstArg = true;
9582     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9583     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9584     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9585       if (Diagnose)
9586         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9587           << Param0->getSourceRange() << Param0->getType()
9588           << Context.getLValueReferenceType(
9589                Context.getRecordType(RD).withConst());
9590       return false;
9591     }
9592     break;
9593   }
9594 
9595   case CXXMoveConstructor:
9596   case CXXMoveAssignment: {
9597     // Trivial move operations always have non-cv-qualified parameters.
9598     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9599     const RValueReferenceType *RT =
9600       Param0->getType()->getAs<RValueReferenceType>();
9601     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9602       if (Diagnose)
9603         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9604           << Param0->getSourceRange() << Param0->getType()
9605           << Context.getRValueReferenceType(Context.getRecordType(RD));
9606       return false;
9607     }
9608     break;
9609   }
9610 
9611   case CXXInvalid:
9612     llvm_unreachable("not a special member");
9613   }
9614 
9615   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9616     if (Diagnose)
9617       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9618            diag::note_nontrivial_default_arg)
9619         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9620     return false;
9621   }
9622   if (MD->isVariadic()) {
9623     if (Diagnose)
9624       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9625     return false;
9626   }
9627 
9628   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9629   //   A copy/move [constructor or assignment operator] is trivial if
9630   //    -- the [member] selected to copy/move each direct base class subobject
9631   //       is trivial
9632   //
9633   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9634   //   A [default constructor or destructor] is trivial if
9635   //    -- all the direct base classes have trivial [default constructors or
9636   //       destructors]
9637   for (const auto &BI : RD->bases())
9638     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9639                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9640       return false;
9641 
9642   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9643   //   A copy/move [constructor or assignment operator] for a class X is
9644   //   trivial if
9645   //    -- for each non-static data member of X that is of class type (or array
9646   //       thereof), the constructor selected to copy/move that member is
9647   //       trivial
9648   //
9649   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9650   //   A [default constructor or destructor] is trivial if
9651   //    -- for all of the non-static data members of its class that are of class
9652   //       type (or array thereof), each such class has a trivial [default
9653   //       constructor or destructor]
9654   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9655     return false;
9656 
9657   // C++11 [class.dtor]p5:
9658   //   A destructor is trivial if [...]
9659   //    -- the destructor is not virtual
9660   if (CSM == CXXDestructor && MD->isVirtual()) {
9661     if (Diagnose)
9662       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9663     return false;
9664   }
9665 
9666   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9667   //   A [special member] for class X is trivial if [...]
9668   //    -- class X has no virtual functions and no virtual base classes
9669   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9670     if (!Diagnose)
9671       return false;
9672 
9673     if (RD->getNumVBases()) {
9674       // Check for virtual bases. We already know that the corresponding
9675       // member in all bases is trivial, so vbases must all be direct.
9676       CXXBaseSpecifier &BS = *RD->vbases_begin();
9677       assert(BS.isVirtual());
9678       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9679       return false;
9680     }
9681 
9682     // Must have a virtual method.
9683     for (const auto *MI : RD->methods()) {
9684       if (MI->isVirtual()) {
9685         SourceLocation MLoc = MI->getBeginLoc();
9686         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9687         return false;
9688       }
9689     }
9690 
9691     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9692   }
9693 
9694   // Looks like it's trivial!
9695   return true;
9696 }
9697 
9698 namespace {
9699 struct FindHiddenVirtualMethod {
9700   Sema *S;
9701   CXXMethodDecl *Method;
9702   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9703   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9704 
9705 private:
9706   /// Check whether any most overridden method from MD in Methods
9707   static bool CheckMostOverridenMethods(
9708       const CXXMethodDecl *MD,
9709       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9710     if (MD->size_overridden_methods() == 0)
9711       return Methods.count(MD->getCanonicalDecl());
9712     for (const CXXMethodDecl *O : MD->overridden_methods())
9713       if (CheckMostOverridenMethods(O, Methods))
9714         return true;
9715     return false;
9716   }
9717 
9718 public:
9719   /// Member lookup function that determines whether a given C++
9720   /// method overloads virtual methods in a base class without overriding any,
9721   /// to be used with CXXRecordDecl::lookupInBases().
9722   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9723     RecordDecl *BaseRecord =
9724         Specifier->getType()->castAs<RecordType>()->getDecl();
9725 
9726     DeclarationName Name = Method->getDeclName();
9727     assert(Name.getNameKind() == DeclarationName::Identifier);
9728 
9729     bool foundSameNameMethod = false;
9730     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9731     for (Path.Decls = BaseRecord->lookup(Name).begin();
9732          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9733       NamedDecl *D = *Path.Decls;
9734       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9735         MD = MD->getCanonicalDecl();
9736         foundSameNameMethod = true;
9737         // Interested only in hidden virtual methods.
9738         if (!MD->isVirtual())
9739           continue;
9740         // If the method we are checking overrides a method from its base
9741         // don't warn about the other overloaded methods. Clang deviates from
9742         // GCC by only diagnosing overloads of inherited virtual functions that
9743         // do not override any other virtual functions in the base. GCC's
9744         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9745         // function from a base class. These cases may be better served by a
9746         // warning (not specific to virtual functions) on call sites when the
9747         // call would select a different function from the base class, were it
9748         // visible.
9749         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9750         if (!S->IsOverload(Method, MD, false))
9751           return true;
9752         // Collect the overload only if its hidden.
9753         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9754           overloadedMethods.push_back(MD);
9755       }
9756     }
9757 
9758     if (foundSameNameMethod)
9759       OverloadedMethods.append(overloadedMethods.begin(),
9760                                overloadedMethods.end());
9761     return foundSameNameMethod;
9762   }
9763 };
9764 } // end anonymous namespace
9765 
9766 /// Add the most overriden methods from MD to Methods
9767 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9768                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9769   if (MD->size_overridden_methods() == 0)
9770     Methods.insert(MD->getCanonicalDecl());
9771   else
9772     for (const CXXMethodDecl *O : MD->overridden_methods())
9773       AddMostOverridenMethods(O, Methods);
9774 }
9775 
9776 /// Check if a method overloads virtual methods in a base class without
9777 /// overriding any.
9778 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9779                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9780   if (!MD->getDeclName().isIdentifier())
9781     return;
9782 
9783   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9784                      /*bool RecordPaths=*/false,
9785                      /*bool DetectVirtual=*/false);
9786   FindHiddenVirtualMethod FHVM;
9787   FHVM.Method = MD;
9788   FHVM.S = this;
9789 
9790   // Keep the base methods that were overridden or introduced in the subclass
9791   // by 'using' in a set. A base method not in this set is hidden.
9792   CXXRecordDecl *DC = MD->getParent();
9793   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9794   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9795     NamedDecl *ND = *I;
9796     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9797       ND = shad->getTargetDecl();
9798     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9799       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9800   }
9801 
9802   if (DC->lookupInBases(FHVM, Paths))
9803     OverloadedMethods = FHVM.OverloadedMethods;
9804 }
9805 
9806 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9807                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9808   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9809     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9810     PartialDiagnostic PD = PDiag(
9811          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9812     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9813     Diag(overloadedMD->getLocation(), PD);
9814   }
9815 }
9816 
9817 /// Diagnose methods which overload virtual methods in a base class
9818 /// without overriding any.
9819 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9820   if (MD->isInvalidDecl())
9821     return;
9822 
9823   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9824     return;
9825 
9826   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9827   FindHiddenVirtualMethods(MD, OverloadedMethods);
9828   if (!OverloadedMethods.empty()) {
9829     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9830       << MD << (OverloadedMethods.size() > 1);
9831 
9832     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9833   }
9834 }
9835 
9836 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9837   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9838     // No diagnostics if this is a template instantiation.
9839     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9840       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9841            diag::ext_cannot_use_trivial_abi) << &RD;
9842       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9843            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9844     }
9845     RD.dropAttr<TrivialABIAttr>();
9846   };
9847 
9848   // Ill-formed if the copy and move constructors are deleted.
9849   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9850     // If the type is dependent, then assume it might have
9851     // implicit copy or move ctor because we won't know yet at this point.
9852     if (RD.isDependentType())
9853       return true;
9854     if (RD.needsImplicitCopyConstructor() &&
9855         !RD.defaultedCopyConstructorIsDeleted())
9856       return true;
9857     if (RD.needsImplicitMoveConstructor() &&
9858         !RD.defaultedMoveConstructorIsDeleted())
9859       return true;
9860     for (const CXXConstructorDecl *CD : RD.ctors())
9861       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9862         return true;
9863     return false;
9864   };
9865 
9866   if (!HasNonDeletedCopyOrMoveConstructor()) {
9867     PrintDiagAndRemoveAttr(0);
9868     return;
9869   }
9870 
9871   // Ill-formed if the struct has virtual functions.
9872   if (RD.isPolymorphic()) {
9873     PrintDiagAndRemoveAttr(1);
9874     return;
9875   }
9876 
9877   for (const auto &B : RD.bases()) {
9878     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9879     // virtual base.
9880     if (!B.getType()->isDependentType() &&
9881         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9882       PrintDiagAndRemoveAttr(2);
9883       return;
9884     }
9885 
9886     if (B.isVirtual()) {
9887       PrintDiagAndRemoveAttr(3);
9888       return;
9889     }
9890   }
9891 
9892   for (const auto *FD : RD.fields()) {
9893     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9894     // non-trivial for the purpose of calls.
9895     QualType FT = FD->getType();
9896     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9897       PrintDiagAndRemoveAttr(4);
9898       return;
9899     }
9900 
9901     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9902       if (!RT->isDependentType() &&
9903           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9904         PrintDiagAndRemoveAttr(5);
9905         return;
9906       }
9907   }
9908 }
9909 
9910 void Sema::ActOnFinishCXXMemberSpecification(
9911     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9912     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9913   if (!TagDecl)
9914     return;
9915 
9916   AdjustDeclIfTemplate(TagDecl);
9917 
9918   for (const ParsedAttr &AL : AttrList) {
9919     if (AL.getKind() != ParsedAttr::AT_Visibility)
9920       continue;
9921     AL.setInvalid();
9922     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9923   }
9924 
9925   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9926               // strict aliasing violation!
9927               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9928               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9929 
9930   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9931 }
9932 
9933 /// Find the equality comparison functions that should be implicitly declared
9934 /// in a given class definition, per C++2a [class.compare.default]p3.
9935 static void findImplicitlyDeclaredEqualityComparisons(
9936     ASTContext &Ctx, CXXRecordDecl *RD,
9937     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9938   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9939   if (!RD->lookup(EqEq).empty())
9940     // Member operator== explicitly declared: no implicit operator==s.
9941     return;
9942 
9943   // Traverse friends looking for an '==' or a '<=>'.
9944   for (FriendDecl *Friend : RD->friends()) {
9945     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9946     if (!FD) continue;
9947 
9948     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9949       // Friend operator== explicitly declared: no implicit operator==s.
9950       Spaceships.clear();
9951       return;
9952     }
9953 
9954     if (FD->getOverloadedOperator() == OO_Spaceship &&
9955         FD->isExplicitlyDefaulted())
9956       Spaceships.push_back(FD);
9957   }
9958 
9959   // Look for members named 'operator<=>'.
9960   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9961   for (NamedDecl *ND : RD->lookup(Cmp)) {
9962     // Note that we could find a non-function here (either a function template
9963     // or a using-declaration). Neither case results in an implicit
9964     // 'operator=='.
9965     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9966       if (FD->isExplicitlyDefaulted())
9967         Spaceships.push_back(FD);
9968   }
9969 }
9970 
9971 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9972 /// special functions, such as the default constructor, copy
9973 /// constructor, or destructor, to the given C++ class (C++
9974 /// [special]p1).  This routine can only be executed just before the
9975 /// definition of the class is complete.
9976 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9977   // Don't add implicit special members to templated classes.
9978   // FIXME: This means unqualified lookups for 'operator=' within a class
9979   // template don't work properly.
9980   if (!ClassDecl->isDependentType()) {
9981     if (ClassDecl->needsImplicitDefaultConstructor()) {
9982       ++getASTContext().NumImplicitDefaultConstructors;
9983 
9984       if (ClassDecl->hasInheritedConstructor())
9985         DeclareImplicitDefaultConstructor(ClassDecl);
9986     }
9987 
9988     if (ClassDecl->needsImplicitCopyConstructor()) {
9989       ++getASTContext().NumImplicitCopyConstructors;
9990 
9991       // If the properties or semantics of the copy constructor couldn't be
9992       // determined while the class was being declared, force a declaration
9993       // of it now.
9994       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9995           ClassDecl->hasInheritedConstructor())
9996         DeclareImplicitCopyConstructor(ClassDecl);
9997       // For the MS ABI we need to know whether the copy ctor is deleted. A
9998       // prerequisite for deleting the implicit copy ctor is that the class has
9999       // a move ctor or move assignment that is either user-declared or whose
10000       // semantics are inherited from a subobject. FIXME: We should provide a
10001       // more direct way for CodeGen to ask whether the constructor was deleted.
10002       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10003                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10004                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10005                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10006                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10007         DeclareImplicitCopyConstructor(ClassDecl);
10008     }
10009 
10010     if (getLangOpts().CPlusPlus11 &&
10011         ClassDecl->needsImplicitMoveConstructor()) {
10012       ++getASTContext().NumImplicitMoveConstructors;
10013 
10014       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10015           ClassDecl->hasInheritedConstructor())
10016         DeclareImplicitMoveConstructor(ClassDecl);
10017     }
10018 
10019     if (ClassDecl->needsImplicitCopyAssignment()) {
10020       ++getASTContext().NumImplicitCopyAssignmentOperators;
10021 
10022       // If we have a dynamic class, then the copy assignment operator may be
10023       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10024       // it shows up in the right place in the vtable and that we diagnose
10025       // problems with the implicit exception specification.
10026       if (ClassDecl->isDynamicClass() ||
10027           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10028           ClassDecl->hasInheritedAssignment())
10029         DeclareImplicitCopyAssignment(ClassDecl);
10030     }
10031 
10032     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10033       ++getASTContext().NumImplicitMoveAssignmentOperators;
10034 
10035       // Likewise for the move assignment operator.
10036       if (ClassDecl->isDynamicClass() ||
10037           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10038           ClassDecl->hasInheritedAssignment())
10039         DeclareImplicitMoveAssignment(ClassDecl);
10040     }
10041 
10042     if (ClassDecl->needsImplicitDestructor()) {
10043       ++getASTContext().NumImplicitDestructors;
10044 
10045       // If we have a dynamic class, then the destructor may be virtual, so we
10046       // have to declare the destructor immediately. This ensures that, e.g., it
10047       // shows up in the right place in the vtable and that we diagnose problems
10048       // with the implicit exception specification.
10049       if (ClassDecl->isDynamicClass() ||
10050           ClassDecl->needsOverloadResolutionForDestructor())
10051         DeclareImplicitDestructor(ClassDecl);
10052     }
10053   }
10054 
10055   // C++2a [class.compare.default]p3:
10056   //   If the member-specification does not explicitly declare any member or
10057   //   friend named operator==, an == operator function is declared implicitly
10058   //   for each defaulted three-way comparison operator function defined in
10059   //   the member-specification
10060   // FIXME: Consider doing this lazily.
10061   // We do this during the initial parse for a class template, not during
10062   // instantiation, so that we can handle unqualified lookups for 'operator=='
10063   // when parsing the template.
10064   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10065     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10066     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10067                                               DefaultedSpaceships);
10068     for (auto *FD : DefaultedSpaceships)
10069       DeclareImplicitEqualityComparison(ClassDecl, FD);
10070   }
10071 }
10072 
10073 unsigned
10074 Sema::ActOnReenterTemplateScope(Decl *D,
10075                                 llvm::function_ref<Scope *()> EnterScope) {
10076   if (!D)
10077     return 0;
10078   AdjustDeclIfTemplate(D);
10079 
10080   // In order to get name lookup right, reenter template scopes in order from
10081   // outermost to innermost.
10082   SmallVector<TemplateParameterList *, 4> ParameterLists;
10083   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10084 
10085   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10086     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10087       ParameterLists.push_back(DD->getTemplateParameterList(i));
10088 
10089     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10090       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10091         ParameterLists.push_back(FTD->getTemplateParameters());
10092     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10093       LookupDC = VD->getDeclContext();
10094 
10095       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10096         ParameterLists.push_back(VTD->getTemplateParameters());
10097       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10098         ParameterLists.push_back(PSD->getTemplateParameters());
10099     }
10100   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10101     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10102       ParameterLists.push_back(TD->getTemplateParameterList(i));
10103 
10104     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10105       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10106         ParameterLists.push_back(CTD->getTemplateParameters());
10107       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10108         ParameterLists.push_back(PSD->getTemplateParameters());
10109     }
10110   }
10111   // FIXME: Alias declarations and concepts.
10112 
10113   unsigned Count = 0;
10114   Scope *InnermostTemplateScope = nullptr;
10115   for (TemplateParameterList *Params : ParameterLists) {
10116     // Ignore explicit specializations; they don't contribute to the template
10117     // depth.
10118     if (Params->size() == 0)
10119       continue;
10120 
10121     InnermostTemplateScope = EnterScope();
10122     for (NamedDecl *Param : *Params) {
10123       if (Param->getDeclName()) {
10124         InnermostTemplateScope->AddDecl(Param);
10125         IdResolver.AddDecl(Param);
10126       }
10127     }
10128     ++Count;
10129   }
10130 
10131   // Associate the new template scopes with the corresponding entities.
10132   if (InnermostTemplateScope) {
10133     assert(LookupDC && "no enclosing DeclContext for template lookup");
10134     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10135   }
10136 
10137   return Count;
10138 }
10139 
10140 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10141   if (!RecordD) return;
10142   AdjustDeclIfTemplate(RecordD);
10143   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10144   PushDeclContext(S, Record);
10145 }
10146 
10147 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10148   if (!RecordD) return;
10149   PopDeclContext();
10150 }
10151 
10152 /// This is used to implement the constant expression evaluation part of the
10153 /// attribute enable_if extension. There is nothing in standard C++ which would
10154 /// require reentering parameters.
10155 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10156   if (!Param)
10157     return;
10158 
10159   S->AddDecl(Param);
10160   if (Param->getDeclName())
10161     IdResolver.AddDecl(Param);
10162 }
10163 
10164 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10165 /// parsing a top-level (non-nested) C++ class, and we are now
10166 /// parsing those parts of the given Method declaration that could
10167 /// not be parsed earlier (C++ [class.mem]p2), such as default
10168 /// arguments. This action should enter the scope of the given
10169 /// Method declaration as if we had just parsed the qualified method
10170 /// name. However, it should not bring the parameters into scope;
10171 /// that will be performed by ActOnDelayedCXXMethodParameter.
10172 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10173 }
10174 
10175 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10176 /// C++ method declaration. We're (re-)introducing the given
10177 /// function parameter into scope for use in parsing later parts of
10178 /// the method declaration. For example, we could see an
10179 /// ActOnParamDefaultArgument event for this parameter.
10180 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10181   if (!ParamD)
10182     return;
10183 
10184   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10185 
10186   S->AddDecl(Param);
10187   if (Param->getDeclName())
10188     IdResolver.AddDecl(Param);
10189 }
10190 
10191 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10192 /// processing the delayed method declaration for Method. The method
10193 /// declaration is now considered finished. There may be a separate
10194 /// ActOnStartOfFunctionDef action later (not necessarily
10195 /// immediately!) for this method, if it was also defined inside the
10196 /// class body.
10197 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10198   if (!MethodD)
10199     return;
10200 
10201   AdjustDeclIfTemplate(MethodD);
10202 
10203   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10204 
10205   // Now that we have our default arguments, check the constructor
10206   // again. It could produce additional diagnostics or affect whether
10207   // the class has implicitly-declared destructors, among other
10208   // things.
10209   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10210     CheckConstructor(Constructor);
10211 
10212   // Check the default arguments, which we may have added.
10213   if (!Method->isInvalidDecl())
10214     CheckCXXDefaultArguments(Method);
10215 }
10216 
10217 // Emit the given diagnostic for each non-address-space qualifier.
10218 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10219 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10220   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10221   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10222     bool DiagOccured = false;
10223     FTI.MethodQualifiers->forEachQualifier(
10224         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10225                                    SourceLocation SL) {
10226           // This diagnostic should be emitted on any qualifier except an addr
10227           // space qualifier. However, forEachQualifier currently doesn't visit
10228           // addr space qualifiers, so there's no way to write this condition
10229           // right now; we just diagnose on everything.
10230           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10231           DiagOccured = true;
10232         });
10233     if (DiagOccured)
10234       D.setInvalidType();
10235   }
10236 }
10237 
10238 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10239 /// the well-formedness of the constructor declarator @p D with type @p
10240 /// R. If there are any errors in the declarator, this routine will
10241 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10242 /// will be updated to reflect a well-formed type for the constructor and
10243 /// returned.
10244 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10245                                           StorageClass &SC) {
10246   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10247 
10248   // C++ [class.ctor]p3:
10249   //   A constructor shall not be virtual (10.3) or static (9.4). A
10250   //   constructor can be invoked for a const, volatile or const
10251   //   volatile object. A constructor shall not be declared const,
10252   //   volatile, or const volatile (9.3.2).
10253   if (isVirtual) {
10254     if (!D.isInvalidType())
10255       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10256         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10257         << SourceRange(D.getIdentifierLoc());
10258     D.setInvalidType();
10259   }
10260   if (SC == SC_Static) {
10261     if (!D.isInvalidType())
10262       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10263         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10264         << SourceRange(D.getIdentifierLoc());
10265     D.setInvalidType();
10266     SC = SC_None;
10267   }
10268 
10269   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10270     diagnoseIgnoredQualifiers(
10271         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10272         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10273         D.getDeclSpec().getRestrictSpecLoc(),
10274         D.getDeclSpec().getAtomicSpecLoc());
10275     D.setInvalidType();
10276   }
10277 
10278   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10279 
10280   // C++0x [class.ctor]p4:
10281   //   A constructor shall not be declared with a ref-qualifier.
10282   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10283   if (FTI.hasRefQualifier()) {
10284     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10285       << FTI.RefQualifierIsLValueRef
10286       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10287     D.setInvalidType();
10288   }
10289 
10290   // Rebuild the function type "R" without any type qualifiers (in
10291   // case any of the errors above fired) and with "void" as the
10292   // return type, since constructors don't have return types.
10293   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10294   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10295     return R;
10296 
10297   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10298   EPI.TypeQuals = Qualifiers();
10299   EPI.RefQualifier = RQ_None;
10300 
10301   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10302 }
10303 
10304 /// CheckConstructor - Checks a fully-formed constructor for
10305 /// well-formedness, issuing any diagnostics required. Returns true if
10306 /// the constructor declarator is invalid.
10307 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10308   CXXRecordDecl *ClassDecl
10309     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10310   if (!ClassDecl)
10311     return Constructor->setInvalidDecl();
10312 
10313   // C++ [class.copy]p3:
10314   //   A declaration of a constructor for a class X is ill-formed if
10315   //   its first parameter is of type (optionally cv-qualified) X and
10316   //   either there are no other parameters or else all other
10317   //   parameters have default arguments.
10318   if (!Constructor->isInvalidDecl() &&
10319       Constructor->hasOneParamOrDefaultArgs() &&
10320       Constructor->getTemplateSpecializationKind() !=
10321           TSK_ImplicitInstantiation) {
10322     QualType ParamType = Constructor->getParamDecl(0)->getType();
10323     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10324     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10325       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10326       const char *ConstRef
10327         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10328                                                         : " const &";
10329       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10330         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10331 
10332       // FIXME: Rather that making the constructor invalid, we should endeavor
10333       // to fix the type.
10334       Constructor->setInvalidDecl();
10335     }
10336   }
10337 }
10338 
10339 /// CheckDestructor - Checks a fully-formed destructor definition for
10340 /// well-formedness, issuing any diagnostics required.  Returns true
10341 /// on error.
10342 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10343   CXXRecordDecl *RD = Destructor->getParent();
10344 
10345   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10346     SourceLocation Loc;
10347 
10348     if (!Destructor->isImplicit())
10349       Loc = Destructor->getLocation();
10350     else
10351       Loc = RD->getLocation();
10352 
10353     // If we have a virtual destructor, look up the deallocation function
10354     if (FunctionDecl *OperatorDelete =
10355             FindDeallocationFunctionForDestructor(Loc, RD)) {
10356       Expr *ThisArg = nullptr;
10357 
10358       // If the notional 'delete this' expression requires a non-trivial
10359       // conversion from 'this' to the type of a destroying operator delete's
10360       // first parameter, perform that conversion now.
10361       if (OperatorDelete->isDestroyingOperatorDelete()) {
10362         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10363         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10364           // C++ [class.dtor]p13:
10365           //   ... as if for the expression 'delete this' appearing in a
10366           //   non-virtual destructor of the destructor's class.
10367           ContextRAII SwitchContext(*this, Destructor);
10368           ExprResult This =
10369               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10370           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10371           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10372           if (This.isInvalid()) {
10373             // FIXME: Register this as a context note so that it comes out
10374             // in the right order.
10375             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10376             return true;
10377           }
10378           ThisArg = This.get();
10379         }
10380       }
10381 
10382       DiagnoseUseOfDecl(OperatorDelete, Loc);
10383       MarkFunctionReferenced(Loc, OperatorDelete);
10384       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10385     }
10386   }
10387 
10388   return false;
10389 }
10390 
10391 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10392 /// the well-formednes of the destructor declarator @p D with type @p
10393 /// R. If there are any errors in the declarator, this routine will
10394 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10395 /// will be updated to reflect a well-formed type for the destructor and
10396 /// returned.
10397 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10398                                          StorageClass& SC) {
10399   // C++ [class.dtor]p1:
10400   //   [...] A typedef-name that names a class is a class-name
10401   //   (7.1.3); however, a typedef-name that names a class shall not
10402   //   be used as the identifier in the declarator for a destructor
10403   //   declaration.
10404   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10405   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10406     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10407       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10408   else if (const TemplateSpecializationType *TST =
10409              DeclaratorType->getAs<TemplateSpecializationType>())
10410     if (TST->isTypeAlias())
10411       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10412         << DeclaratorType << 1;
10413 
10414   // C++ [class.dtor]p2:
10415   //   A destructor is used to destroy objects of its class type. A
10416   //   destructor takes no parameters, and no return type can be
10417   //   specified for it (not even void). The address of a destructor
10418   //   shall not be taken. A destructor shall not be static. A
10419   //   destructor can be invoked for a const, volatile or const
10420   //   volatile object. A destructor shall not be declared const,
10421   //   volatile or const volatile (9.3.2).
10422   if (SC == SC_Static) {
10423     if (!D.isInvalidType())
10424       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10425         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10426         << SourceRange(D.getIdentifierLoc())
10427         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10428 
10429     SC = SC_None;
10430   }
10431   if (!D.isInvalidType()) {
10432     // Destructors don't have return types, but the parser will
10433     // happily parse something like:
10434     //
10435     //   class X {
10436     //     float ~X();
10437     //   };
10438     //
10439     // The return type will be eliminated later.
10440     if (D.getDeclSpec().hasTypeSpecifier())
10441       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10442         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10443         << SourceRange(D.getIdentifierLoc());
10444     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10445       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10446                                 SourceLocation(),
10447                                 D.getDeclSpec().getConstSpecLoc(),
10448                                 D.getDeclSpec().getVolatileSpecLoc(),
10449                                 D.getDeclSpec().getRestrictSpecLoc(),
10450                                 D.getDeclSpec().getAtomicSpecLoc());
10451       D.setInvalidType();
10452     }
10453   }
10454 
10455   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10456 
10457   // C++0x [class.dtor]p2:
10458   //   A destructor shall not be declared with a ref-qualifier.
10459   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10460   if (FTI.hasRefQualifier()) {
10461     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10462       << FTI.RefQualifierIsLValueRef
10463       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10464     D.setInvalidType();
10465   }
10466 
10467   // Make sure we don't have any parameters.
10468   if (FTIHasNonVoidParameters(FTI)) {
10469     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10470 
10471     // Delete the parameters.
10472     FTI.freeParams();
10473     D.setInvalidType();
10474   }
10475 
10476   // Make sure the destructor isn't variadic.
10477   if (FTI.isVariadic) {
10478     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10479     D.setInvalidType();
10480   }
10481 
10482   // Rebuild the function type "R" without any type qualifiers or
10483   // parameters (in case any of the errors above fired) and with
10484   // "void" as the return type, since destructors don't have return
10485   // types.
10486   if (!D.isInvalidType())
10487     return R;
10488 
10489   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10490   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10491   EPI.Variadic = false;
10492   EPI.TypeQuals = Qualifiers();
10493   EPI.RefQualifier = RQ_None;
10494   return Context.getFunctionType(Context.VoidTy, None, EPI);
10495 }
10496 
10497 static void extendLeft(SourceRange &R, SourceRange Before) {
10498   if (Before.isInvalid())
10499     return;
10500   R.setBegin(Before.getBegin());
10501   if (R.getEnd().isInvalid())
10502     R.setEnd(Before.getEnd());
10503 }
10504 
10505 static void extendRight(SourceRange &R, SourceRange After) {
10506   if (After.isInvalid())
10507     return;
10508   if (R.getBegin().isInvalid())
10509     R.setBegin(After.getBegin());
10510   R.setEnd(After.getEnd());
10511 }
10512 
10513 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10514 /// well-formednes of the conversion function declarator @p D with
10515 /// type @p R. If there are any errors in the declarator, this routine
10516 /// will emit diagnostics and return true. Otherwise, it will return
10517 /// false. Either way, the type @p R will be updated to reflect a
10518 /// well-formed type for the conversion operator.
10519 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10520                                      StorageClass& SC) {
10521   // C++ [class.conv.fct]p1:
10522   //   Neither parameter types nor return type can be specified. The
10523   //   type of a conversion function (8.3.5) is "function taking no
10524   //   parameter returning conversion-type-id."
10525   if (SC == SC_Static) {
10526     if (!D.isInvalidType())
10527       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10528         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10529         << D.getName().getSourceRange();
10530     D.setInvalidType();
10531     SC = SC_None;
10532   }
10533 
10534   TypeSourceInfo *ConvTSI = nullptr;
10535   QualType ConvType =
10536       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10537 
10538   const DeclSpec &DS = D.getDeclSpec();
10539   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10540     // Conversion functions don't have return types, but the parser will
10541     // happily parse something like:
10542     //
10543     //   class X {
10544     //     float operator bool();
10545     //   };
10546     //
10547     // The return type will be changed later anyway.
10548     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10549       << SourceRange(DS.getTypeSpecTypeLoc())
10550       << SourceRange(D.getIdentifierLoc());
10551     D.setInvalidType();
10552   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10553     // It's also plausible that the user writes type qualifiers in the wrong
10554     // place, such as:
10555     //   struct S { const operator int(); };
10556     // FIXME: we could provide a fixit to move the qualifiers onto the
10557     // conversion type.
10558     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10559         << SourceRange(D.getIdentifierLoc()) << 0;
10560     D.setInvalidType();
10561   }
10562 
10563   const auto *Proto = R->castAs<FunctionProtoType>();
10564 
10565   // Make sure we don't have any parameters.
10566   if (Proto->getNumParams() > 0) {
10567     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10568 
10569     // Delete the parameters.
10570     D.getFunctionTypeInfo().freeParams();
10571     D.setInvalidType();
10572   } else if (Proto->isVariadic()) {
10573     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10574     D.setInvalidType();
10575   }
10576 
10577   // Diagnose "&operator bool()" and other such nonsense.  This
10578   // is actually a gcc extension which we don't support.
10579   if (Proto->getReturnType() != ConvType) {
10580     bool NeedsTypedef = false;
10581     SourceRange Before, After;
10582 
10583     // Walk the chunks and extract information on them for our diagnostic.
10584     bool PastFunctionChunk = false;
10585     for (auto &Chunk : D.type_objects()) {
10586       switch (Chunk.Kind) {
10587       case DeclaratorChunk::Function:
10588         if (!PastFunctionChunk) {
10589           if (Chunk.Fun.HasTrailingReturnType) {
10590             TypeSourceInfo *TRT = nullptr;
10591             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10592             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10593           }
10594           PastFunctionChunk = true;
10595           break;
10596         }
10597         LLVM_FALLTHROUGH;
10598       case DeclaratorChunk::Array:
10599         NeedsTypedef = true;
10600         extendRight(After, Chunk.getSourceRange());
10601         break;
10602 
10603       case DeclaratorChunk::Pointer:
10604       case DeclaratorChunk::BlockPointer:
10605       case DeclaratorChunk::Reference:
10606       case DeclaratorChunk::MemberPointer:
10607       case DeclaratorChunk::Pipe:
10608         extendLeft(Before, Chunk.getSourceRange());
10609         break;
10610 
10611       case DeclaratorChunk::Paren:
10612         extendLeft(Before, Chunk.Loc);
10613         extendRight(After, Chunk.EndLoc);
10614         break;
10615       }
10616     }
10617 
10618     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10619                          After.isValid()  ? After.getBegin() :
10620                                             D.getIdentifierLoc();
10621     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10622     DB << Before << After;
10623 
10624     if (!NeedsTypedef) {
10625       DB << /*don't need a typedef*/0;
10626 
10627       // If we can provide a correct fix-it hint, do so.
10628       if (After.isInvalid() && ConvTSI) {
10629         SourceLocation InsertLoc =
10630             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10631         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10632            << FixItHint::CreateInsertionFromRange(
10633                   InsertLoc, CharSourceRange::getTokenRange(Before))
10634            << FixItHint::CreateRemoval(Before);
10635       }
10636     } else if (!Proto->getReturnType()->isDependentType()) {
10637       DB << /*typedef*/1 << Proto->getReturnType();
10638     } else if (getLangOpts().CPlusPlus11) {
10639       DB << /*alias template*/2 << Proto->getReturnType();
10640     } else {
10641       DB << /*might not be fixable*/3;
10642     }
10643 
10644     // Recover by incorporating the other type chunks into the result type.
10645     // Note, this does *not* change the name of the function. This is compatible
10646     // with the GCC extension:
10647     //   struct S { &operator int(); } s;
10648     //   int &r = s.operator int(); // ok in GCC
10649     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10650     ConvType = Proto->getReturnType();
10651   }
10652 
10653   // C++ [class.conv.fct]p4:
10654   //   The conversion-type-id shall not represent a function type nor
10655   //   an array type.
10656   if (ConvType->isArrayType()) {
10657     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10658     ConvType = Context.getPointerType(ConvType);
10659     D.setInvalidType();
10660   } else if (ConvType->isFunctionType()) {
10661     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10662     ConvType = Context.getPointerType(ConvType);
10663     D.setInvalidType();
10664   }
10665 
10666   // Rebuild the function type "R" without any parameters (in case any
10667   // of the errors above fired) and with the conversion type as the
10668   // return type.
10669   if (D.isInvalidType())
10670     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10671 
10672   // C++0x explicit conversion operators.
10673   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10674     Diag(DS.getExplicitSpecLoc(),
10675          getLangOpts().CPlusPlus11
10676              ? diag::warn_cxx98_compat_explicit_conversion_functions
10677              : diag::ext_explicit_conversion_functions)
10678         << SourceRange(DS.getExplicitSpecRange());
10679 }
10680 
10681 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10682 /// the declaration of the given C++ conversion function. This routine
10683 /// is responsible for recording the conversion function in the C++
10684 /// class, if possible.
10685 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10686   assert(Conversion && "Expected to receive a conversion function declaration");
10687 
10688   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10689 
10690   // Make sure we aren't redeclaring the conversion function.
10691   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10692   // C++ [class.conv.fct]p1:
10693   //   [...] A conversion function is never used to convert a
10694   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10695   //   same object type (or a reference to it), to a (possibly
10696   //   cv-qualified) base class of that type (or a reference to it),
10697   //   or to (possibly cv-qualified) void.
10698   QualType ClassType
10699     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10700   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10701     ConvType = ConvTypeRef->getPointeeType();
10702   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10703       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10704     /* Suppress diagnostics for instantiations. */;
10705   else if (Conversion->size_overridden_methods() != 0)
10706     /* Suppress diagnostics for overriding virtual function in a base class. */;
10707   else if (ConvType->isRecordType()) {
10708     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10709     if (ConvType == ClassType)
10710       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10711         << ClassType;
10712     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10713       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10714         <<  ClassType << ConvType;
10715   } else if (ConvType->isVoidType()) {
10716     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10717       << ClassType << ConvType;
10718   }
10719 
10720   if (FunctionTemplateDecl *ConversionTemplate
10721                                 = Conversion->getDescribedFunctionTemplate())
10722     return ConversionTemplate;
10723 
10724   return Conversion;
10725 }
10726 
10727 namespace {
10728 /// Utility class to accumulate and print a diagnostic listing the invalid
10729 /// specifier(s) on a declaration.
10730 struct BadSpecifierDiagnoser {
10731   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10732       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10733   ~BadSpecifierDiagnoser() {
10734     Diagnostic << Specifiers;
10735   }
10736 
10737   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10738     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10739   }
10740   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10741     return check(SpecLoc,
10742                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10743   }
10744   void check(SourceLocation SpecLoc, const char *Spec) {
10745     if (SpecLoc.isInvalid()) return;
10746     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10747     if (!Specifiers.empty()) Specifiers += " ";
10748     Specifiers += Spec;
10749   }
10750 
10751   Sema &S;
10752   Sema::SemaDiagnosticBuilder Diagnostic;
10753   std::string Specifiers;
10754 };
10755 }
10756 
10757 /// Check the validity of a declarator that we parsed for a deduction-guide.
10758 /// These aren't actually declarators in the grammar, so we need to check that
10759 /// the user didn't specify any pieces that are not part of the deduction-guide
10760 /// grammar.
10761 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10762                                          StorageClass &SC) {
10763   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10764   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10765   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10766 
10767   // C++ [temp.deduct.guide]p3:
10768   //   A deduction-gide shall be declared in the same scope as the
10769   //   corresponding class template.
10770   if (!CurContext->getRedeclContext()->Equals(
10771           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10772     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10773       << GuidedTemplateDecl;
10774     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10775   }
10776 
10777   auto &DS = D.getMutableDeclSpec();
10778   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10779   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10780       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10781       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10782     BadSpecifierDiagnoser Diagnoser(
10783         *this, D.getIdentifierLoc(),
10784         diag::err_deduction_guide_invalid_specifier);
10785 
10786     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10787     DS.ClearStorageClassSpecs();
10788     SC = SC_None;
10789 
10790     // 'explicit' is permitted.
10791     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10792     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10793     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10794     DS.ClearConstexprSpec();
10795 
10796     Diagnoser.check(DS.getConstSpecLoc(), "const");
10797     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10798     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10799     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10800     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10801     DS.ClearTypeQualifiers();
10802 
10803     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10804     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10805     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10806     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10807     DS.ClearTypeSpecType();
10808   }
10809 
10810   if (D.isInvalidType())
10811     return;
10812 
10813   // Check the declarator is simple enough.
10814   bool FoundFunction = false;
10815   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10816     if (Chunk.Kind == DeclaratorChunk::Paren)
10817       continue;
10818     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10819       Diag(D.getDeclSpec().getBeginLoc(),
10820            diag::err_deduction_guide_with_complex_decl)
10821           << D.getSourceRange();
10822       break;
10823     }
10824     if (!Chunk.Fun.hasTrailingReturnType()) {
10825       Diag(D.getName().getBeginLoc(),
10826            diag::err_deduction_guide_no_trailing_return_type);
10827       break;
10828     }
10829 
10830     // Check that the return type is written as a specialization of
10831     // the template specified as the deduction-guide's name.
10832     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10833     TypeSourceInfo *TSI = nullptr;
10834     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10835     assert(TSI && "deduction guide has valid type but invalid return type?");
10836     bool AcceptableReturnType = false;
10837     bool MightInstantiateToSpecialization = false;
10838     if (auto RetTST =
10839             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10840       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10841       bool TemplateMatches =
10842           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10843       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10844         AcceptableReturnType = true;
10845       else {
10846         // This could still instantiate to the right type, unless we know it
10847         // names the wrong class template.
10848         auto *TD = SpecifiedName.getAsTemplateDecl();
10849         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10850                                              !TemplateMatches);
10851       }
10852     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10853       MightInstantiateToSpecialization = true;
10854     }
10855 
10856     if (!AcceptableReturnType) {
10857       Diag(TSI->getTypeLoc().getBeginLoc(),
10858            diag::err_deduction_guide_bad_trailing_return_type)
10859           << GuidedTemplate << TSI->getType()
10860           << MightInstantiateToSpecialization
10861           << TSI->getTypeLoc().getSourceRange();
10862     }
10863 
10864     // Keep going to check that we don't have any inner declarator pieces (we
10865     // could still have a function returning a pointer to a function).
10866     FoundFunction = true;
10867   }
10868 
10869   if (D.isFunctionDefinition())
10870     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10871 }
10872 
10873 //===----------------------------------------------------------------------===//
10874 // Namespace Handling
10875 //===----------------------------------------------------------------------===//
10876 
10877 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10878 /// reopened.
10879 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10880                                             SourceLocation Loc,
10881                                             IdentifierInfo *II, bool *IsInline,
10882                                             NamespaceDecl *PrevNS) {
10883   assert(*IsInline != PrevNS->isInline());
10884 
10885   if (PrevNS->isInline())
10886     // The user probably just forgot the 'inline', so suggest that it
10887     // be added back.
10888     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10889       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10890   else
10891     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10892 
10893   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10894   *IsInline = PrevNS->isInline();
10895 }
10896 
10897 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10898 /// definition.
10899 Decl *Sema::ActOnStartNamespaceDef(
10900     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10901     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10902     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10903   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10904   // For anonymous namespace, take the location of the left brace.
10905   SourceLocation Loc = II ? IdentLoc : LBrace;
10906   bool IsInline = InlineLoc.isValid();
10907   bool IsInvalid = false;
10908   bool IsStd = false;
10909   bool AddToKnown = false;
10910   Scope *DeclRegionScope = NamespcScope->getParent();
10911 
10912   NamespaceDecl *PrevNS = nullptr;
10913   if (II) {
10914     // C++ [namespace.def]p2:
10915     //   The identifier in an original-namespace-definition shall not
10916     //   have been previously defined in the declarative region in
10917     //   which the original-namespace-definition appears. The
10918     //   identifier in an original-namespace-definition is the name of
10919     //   the namespace. Subsequently in that declarative region, it is
10920     //   treated as an original-namespace-name.
10921     //
10922     // Since namespace names are unique in their scope, and we don't
10923     // look through using directives, just look for any ordinary names
10924     // as if by qualified name lookup.
10925     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10926                    ForExternalRedeclaration);
10927     LookupQualifiedName(R, CurContext->getRedeclContext());
10928     NamedDecl *PrevDecl =
10929         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10930     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10931 
10932     if (PrevNS) {
10933       // This is an extended namespace definition.
10934       if (IsInline != PrevNS->isInline())
10935         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10936                                         &IsInline, PrevNS);
10937     } else if (PrevDecl) {
10938       // This is an invalid name redefinition.
10939       Diag(Loc, diag::err_redefinition_different_kind)
10940         << II;
10941       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10942       IsInvalid = true;
10943       // Continue on to push Namespc as current DeclContext and return it.
10944     } else if (II->isStr("std") &&
10945                CurContext->getRedeclContext()->isTranslationUnit()) {
10946       // This is the first "real" definition of the namespace "std", so update
10947       // our cache of the "std" namespace to point at this definition.
10948       PrevNS = getStdNamespace();
10949       IsStd = true;
10950       AddToKnown = !IsInline;
10951     } else {
10952       // We've seen this namespace for the first time.
10953       AddToKnown = !IsInline;
10954     }
10955   } else {
10956     // Anonymous namespaces.
10957 
10958     // Determine whether the parent already has an anonymous namespace.
10959     DeclContext *Parent = CurContext->getRedeclContext();
10960     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10961       PrevNS = TU->getAnonymousNamespace();
10962     } else {
10963       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10964       PrevNS = ND->getAnonymousNamespace();
10965     }
10966 
10967     if (PrevNS && IsInline != PrevNS->isInline())
10968       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10969                                       &IsInline, PrevNS);
10970   }
10971 
10972   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10973                                                  StartLoc, Loc, II, PrevNS);
10974   if (IsInvalid)
10975     Namespc->setInvalidDecl();
10976 
10977   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10978   AddPragmaAttributes(DeclRegionScope, Namespc);
10979 
10980   // FIXME: Should we be merging attributes?
10981   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10982     PushNamespaceVisibilityAttr(Attr, Loc);
10983 
10984   if (IsStd)
10985     StdNamespace = Namespc;
10986   if (AddToKnown)
10987     KnownNamespaces[Namespc] = false;
10988 
10989   if (II) {
10990     PushOnScopeChains(Namespc, DeclRegionScope);
10991   } else {
10992     // Link the anonymous namespace into its parent.
10993     DeclContext *Parent = CurContext->getRedeclContext();
10994     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10995       TU->setAnonymousNamespace(Namespc);
10996     } else {
10997       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10998     }
10999 
11000     CurContext->addDecl(Namespc);
11001 
11002     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11003     //   behaves as if it were replaced by
11004     //     namespace unique { /* empty body */ }
11005     //     using namespace unique;
11006     //     namespace unique { namespace-body }
11007     //   where all occurrences of 'unique' in a translation unit are
11008     //   replaced by the same identifier and this identifier differs
11009     //   from all other identifiers in the entire program.
11010 
11011     // We just create the namespace with an empty name and then add an
11012     // implicit using declaration, just like the standard suggests.
11013     //
11014     // CodeGen enforces the "universally unique" aspect by giving all
11015     // declarations semantically contained within an anonymous
11016     // namespace internal linkage.
11017 
11018     if (!PrevNS) {
11019       UD = UsingDirectiveDecl::Create(Context, Parent,
11020                                       /* 'using' */ LBrace,
11021                                       /* 'namespace' */ SourceLocation(),
11022                                       /* qualifier */ NestedNameSpecifierLoc(),
11023                                       /* identifier */ SourceLocation(),
11024                                       Namespc,
11025                                       /* Ancestor */ Parent);
11026       UD->setImplicit();
11027       Parent->addDecl(UD);
11028     }
11029   }
11030 
11031   ActOnDocumentableDecl(Namespc);
11032 
11033   // Although we could have an invalid decl (i.e. the namespace name is a
11034   // redefinition), push it as current DeclContext and try to continue parsing.
11035   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11036   // for the namespace has the declarations that showed up in that particular
11037   // namespace definition.
11038   PushDeclContext(NamespcScope, Namespc);
11039   return Namespc;
11040 }
11041 
11042 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11043 /// is a namespace alias, returns the namespace it points to.
11044 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11045   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11046     return AD->getNamespace();
11047   return dyn_cast_or_null<NamespaceDecl>(D);
11048 }
11049 
11050 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11051 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11052 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11053   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11054   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11055   Namespc->setRBraceLoc(RBrace);
11056   PopDeclContext();
11057   if (Namespc->hasAttr<VisibilityAttr>())
11058     PopPragmaVisibility(true, RBrace);
11059   // If this namespace contains an export-declaration, export it now.
11060   if (DeferredExportedNamespaces.erase(Namespc))
11061     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11062 }
11063 
11064 CXXRecordDecl *Sema::getStdBadAlloc() const {
11065   return cast_or_null<CXXRecordDecl>(
11066                                   StdBadAlloc.get(Context.getExternalSource()));
11067 }
11068 
11069 EnumDecl *Sema::getStdAlignValT() const {
11070   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11071 }
11072 
11073 NamespaceDecl *Sema::getStdNamespace() const {
11074   return cast_or_null<NamespaceDecl>(
11075                                  StdNamespace.get(Context.getExternalSource()));
11076 }
11077 
11078 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11079   if (!StdExperimentalNamespaceCache) {
11080     if (auto Std = getStdNamespace()) {
11081       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11082                           SourceLocation(), LookupNamespaceName);
11083       if (!LookupQualifiedName(Result, Std) ||
11084           !(StdExperimentalNamespaceCache =
11085                 Result.getAsSingle<NamespaceDecl>()))
11086         Result.suppressDiagnostics();
11087     }
11088   }
11089   return StdExperimentalNamespaceCache;
11090 }
11091 
11092 namespace {
11093 
11094 enum UnsupportedSTLSelect {
11095   USS_InvalidMember,
11096   USS_MissingMember,
11097   USS_NonTrivial,
11098   USS_Other
11099 };
11100 
11101 struct InvalidSTLDiagnoser {
11102   Sema &S;
11103   SourceLocation Loc;
11104   QualType TyForDiags;
11105 
11106   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11107                       const VarDecl *VD = nullptr) {
11108     {
11109       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11110                << TyForDiags << ((int)Sel);
11111       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11112         assert(!Name.empty());
11113         D << Name;
11114       }
11115     }
11116     if (Sel == USS_InvalidMember) {
11117       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11118           << VD << VD->getSourceRange();
11119     }
11120     return QualType();
11121   }
11122 };
11123 } // namespace
11124 
11125 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11126                                            SourceLocation Loc,
11127                                            ComparisonCategoryUsage Usage) {
11128   assert(getLangOpts().CPlusPlus &&
11129          "Looking for comparison category type outside of C++.");
11130 
11131   // Use an elaborated type for diagnostics which has a name containing the
11132   // prepended 'std' namespace but not any inline namespace names.
11133   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11134     auto *NNS =
11135         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11136     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11137   };
11138 
11139   // Check if we've already successfully checked the comparison category type
11140   // before. If so, skip checking it again.
11141   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11142   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11143     // The only thing we need to check is that the type has a reachable
11144     // definition in the current context.
11145     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11146       return QualType();
11147 
11148     return Info->getType();
11149   }
11150 
11151   // If lookup failed
11152   if (!Info) {
11153     std::string NameForDiags = "std::";
11154     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11155     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11156         << NameForDiags << (int)Usage;
11157     return QualType();
11158   }
11159 
11160   assert(Info->Kind == Kind);
11161   assert(Info->Record);
11162 
11163   // Update the Record decl in case we encountered a forward declaration on our
11164   // first pass. FIXME: This is a bit of a hack.
11165   if (Info->Record->hasDefinition())
11166     Info->Record = Info->Record->getDefinition();
11167 
11168   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11169     return QualType();
11170 
11171   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11172 
11173   if (!Info->Record->isTriviallyCopyable())
11174     return UnsupportedSTLError(USS_NonTrivial);
11175 
11176   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11177     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11178     // Tolerate empty base classes.
11179     if (Base->isEmpty())
11180       continue;
11181     // Reject STL implementations which have at least one non-empty base.
11182     return UnsupportedSTLError();
11183   }
11184 
11185   // Check that the STL has implemented the types using a single integer field.
11186   // This expectation allows better codegen for builtin operators. We require:
11187   //   (1) The class has exactly one field.
11188   //   (2) The field is an integral or enumeration type.
11189   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11190   if (std::distance(FIt, FEnd) != 1 ||
11191       !FIt->getType()->isIntegralOrEnumerationType()) {
11192     return UnsupportedSTLError();
11193   }
11194 
11195   // Build each of the require values and store them in Info.
11196   for (ComparisonCategoryResult CCR :
11197        ComparisonCategories::getPossibleResultsForType(Kind)) {
11198     StringRef MemName = ComparisonCategories::getResultString(CCR);
11199     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11200 
11201     if (!ValInfo)
11202       return UnsupportedSTLError(USS_MissingMember, MemName);
11203 
11204     VarDecl *VD = ValInfo->VD;
11205     assert(VD && "should not be null!");
11206 
11207     // Attempt to diagnose reasons why the STL definition of this type
11208     // might be foobar, including it failing to be a constant expression.
11209     // TODO Handle more ways the lookup or result can be invalid.
11210     if (!VD->isStaticDataMember() ||
11211         !VD->isUsableInConstantExpressions(Context))
11212       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11213 
11214     // Attempt to evaluate the var decl as a constant expression and extract
11215     // the value of its first field as a ICE. If this fails, the STL
11216     // implementation is not supported.
11217     if (!ValInfo->hasValidIntValue())
11218       return UnsupportedSTLError();
11219 
11220     MarkVariableReferenced(Loc, VD);
11221   }
11222 
11223   // We've successfully built the required types and expressions. Update
11224   // the cache and return the newly cached value.
11225   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11226   return Info->getType();
11227 }
11228 
11229 /// Retrieve the special "std" namespace, which may require us to
11230 /// implicitly define the namespace.
11231 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11232   if (!StdNamespace) {
11233     // The "std" namespace has not yet been defined, so build one implicitly.
11234     StdNamespace = NamespaceDecl::Create(Context,
11235                                          Context.getTranslationUnitDecl(),
11236                                          /*Inline=*/false,
11237                                          SourceLocation(), SourceLocation(),
11238                                          &PP.getIdentifierTable().get("std"),
11239                                          /*PrevDecl=*/nullptr);
11240     getStdNamespace()->setImplicit(true);
11241   }
11242 
11243   return getStdNamespace();
11244 }
11245 
11246 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11247   assert(getLangOpts().CPlusPlus &&
11248          "Looking for std::initializer_list outside of C++.");
11249 
11250   // We're looking for implicit instantiations of
11251   // template <typename E> class std::initializer_list.
11252 
11253   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11254     return false;
11255 
11256   ClassTemplateDecl *Template = nullptr;
11257   const TemplateArgument *Arguments = nullptr;
11258 
11259   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11260 
11261     ClassTemplateSpecializationDecl *Specialization =
11262         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11263     if (!Specialization)
11264       return false;
11265 
11266     Template = Specialization->getSpecializedTemplate();
11267     Arguments = Specialization->getTemplateArgs().data();
11268   } else if (const TemplateSpecializationType *TST =
11269                  Ty->getAs<TemplateSpecializationType>()) {
11270     Template = dyn_cast_or_null<ClassTemplateDecl>(
11271         TST->getTemplateName().getAsTemplateDecl());
11272     Arguments = TST->getArgs();
11273   }
11274   if (!Template)
11275     return false;
11276 
11277   if (!StdInitializerList) {
11278     // Haven't recognized std::initializer_list yet, maybe this is it.
11279     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11280     if (TemplateClass->getIdentifier() !=
11281             &PP.getIdentifierTable().get("initializer_list") ||
11282         !getStdNamespace()->InEnclosingNamespaceSetOf(
11283             TemplateClass->getDeclContext()))
11284       return false;
11285     // This is a template called std::initializer_list, but is it the right
11286     // template?
11287     TemplateParameterList *Params = Template->getTemplateParameters();
11288     if (Params->getMinRequiredArguments() != 1)
11289       return false;
11290     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11291       return false;
11292 
11293     // It's the right template.
11294     StdInitializerList = Template;
11295   }
11296 
11297   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11298     return false;
11299 
11300   // This is an instance of std::initializer_list. Find the argument type.
11301   if (Element)
11302     *Element = Arguments[0].getAsType();
11303   return true;
11304 }
11305 
11306 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11307   NamespaceDecl *Std = S.getStdNamespace();
11308   if (!Std) {
11309     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11310     return nullptr;
11311   }
11312 
11313   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11314                       Loc, Sema::LookupOrdinaryName);
11315   if (!S.LookupQualifiedName(Result, Std)) {
11316     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11317     return nullptr;
11318   }
11319   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11320   if (!Template) {
11321     Result.suppressDiagnostics();
11322     // We found something weird. Complain about the first thing we found.
11323     NamedDecl *Found = *Result.begin();
11324     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11325     return nullptr;
11326   }
11327 
11328   // We found some template called std::initializer_list. Now verify that it's
11329   // correct.
11330   TemplateParameterList *Params = Template->getTemplateParameters();
11331   if (Params->getMinRequiredArguments() != 1 ||
11332       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11333     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11334     return nullptr;
11335   }
11336 
11337   return Template;
11338 }
11339 
11340 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11341   if (!StdInitializerList) {
11342     StdInitializerList = LookupStdInitializerList(*this, Loc);
11343     if (!StdInitializerList)
11344       return QualType();
11345   }
11346 
11347   TemplateArgumentListInfo Args(Loc, Loc);
11348   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11349                                        Context.getTrivialTypeSourceInfo(Element,
11350                                                                         Loc)));
11351   return Context.getCanonicalType(
11352       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11353 }
11354 
11355 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11356   // C++ [dcl.init.list]p2:
11357   //   A constructor is an initializer-list constructor if its first parameter
11358   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11359   //   std::initializer_list<E> for some type E, and either there are no other
11360   //   parameters or else all other parameters have default arguments.
11361   if (!Ctor->hasOneParamOrDefaultArgs())
11362     return false;
11363 
11364   QualType ArgType = Ctor->getParamDecl(0)->getType();
11365   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11366     ArgType = RT->getPointeeType().getUnqualifiedType();
11367 
11368   return isStdInitializerList(ArgType, nullptr);
11369 }
11370 
11371 /// Determine whether a using statement is in a context where it will be
11372 /// apply in all contexts.
11373 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11374   switch (CurContext->getDeclKind()) {
11375     case Decl::TranslationUnit:
11376       return true;
11377     case Decl::LinkageSpec:
11378       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11379     default:
11380       return false;
11381   }
11382 }
11383 
11384 namespace {
11385 
11386 // Callback to only accept typo corrections that are namespaces.
11387 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11388 public:
11389   bool ValidateCandidate(const TypoCorrection &candidate) override {
11390     if (NamedDecl *ND = candidate.getCorrectionDecl())
11391       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11392     return false;
11393   }
11394 
11395   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11396     return std::make_unique<NamespaceValidatorCCC>(*this);
11397   }
11398 };
11399 
11400 }
11401 
11402 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11403                                        CXXScopeSpec &SS,
11404                                        SourceLocation IdentLoc,
11405                                        IdentifierInfo *Ident) {
11406   R.clear();
11407   NamespaceValidatorCCC CCC{};
11408   if (TypoCorrection Corrected =
11409           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11410                         Sema::CTK_ErrorRecovery)) {
11411     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11412       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11413       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11414                               Ident->getName().equals(CorrectedStr);
11415       S.diagnoseTypo(Corrected,
11416                      S.PDiag(diag::err_using_directive_member_suggest)
11417                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11418                      S.PDiag(diag::note_namespace_defined_here));
11419     } else {
11420       S.diagnoseTypo(Corrected,
11421                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11422                      S.PDiag(diag::note_namespace_defined_here));
11423     }
11424     R.addDecl(Corrected.getFoundDecl());
11425     return true;
11426   }
11427   return false;
11428 }
11429 
11430 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11431                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11432                                 SourceLocation IdentLoc,
11433                                 IdentifierInfo *NamespcName,
11434                                 const ParsedAttributesView &AttrList) {
11435   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11436   assert(NamespcName && "Invalid NamespcName.");
11437   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11438 
11439   // This can only happen along a recovery path.
11440   while (S->isTemplateParamScope())
11441     S = S->getParent();
11442   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11443 
11444   UsingDirectiveDecl *UDir = nullptr;
11445   NestedNameSpecifier *Qualifier = nullptr;
11446   if (SS.isSet())
11447     Qualifier = SS.getScopeRep();
11448 
11449   // Lookup namespace name.
11450   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11451   LookupParsedName(R, S, &SS);
11452   if (R.isAmbiguous())
11453     return nullptr;
11454 
11455   if (R.empty()) {
11456     R.clear();
11457     // Allow "using namespace std;" or "using namespace ::std;" even if
11458     // "std" hasn't been defined yet, for GCC compatibility.
11459     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11460         NamespcName->isStr("std")) {
11461       Diag(IdentLoc, diag::ext_using_undefined_std);
11462       R.addDecl(getOrCreateStdNamespace());
11463       R.resolveKind();
11464     }
11465     // Otherwise, attempt typo correction.
11466     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11467   }
11468 
11469   if (!R.empty()) {
11470     NamedDecl *Named = R.getRepresentativeDecl();
11471     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11472     assert(NS && "expected namespace decl");
11473 
11474     // The use of a nested name specifier may trigger deprecation warnings.
11475     DiagnoseUseOfDecl(Named, IdentLoc);
11476 
11477     // C++ [namespace.udir]p1:
11478     //   A using-directive specifies that the names in the nominated
11479     //   namespace can be used in the scope in which the
11480     //   using-directive appears after the using-directive. During
11481     //   unqualified name lookup (3.4.1), the names appear as if they
11482     //   were declared in the nearest enclosing namespace which
11483     //   contains both the using-directive and the nominated
11484     //   namespace. [Note: in this context, "contains" means "contains
11485     //   directly or indirectly". ]
11486 
11487     // Find enclosing context containing both using-directive and
11488     // nominated namespace.
11489     DeclContext *CommonAncestor = NS;
11490     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11491       CommonAncestor = CommonAncestor->getParent();
11492 
11493     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11494                                       SS.getWithLocInContext(Context),
11495                                       IdentLoc, Named, CommonAncestor);
11496 
11497     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11498         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11499       Diag(IdentLoc, diag::warn_using_directive_in_header);
11500     }
11501 
11502     PushUsingDirective(S, UDir);
11503   } else {
11504     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11505   }
11506 
11507   if (UDir)
11508     ProcessDeclAttributeList(S, UDir, AttrList);
11509 
11510   return UDir;
11511 }
11512 
11513 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11514   // If the scope has an associated entity and the using directive is at
11515   // namespace or translation unit scope, add the UsingDirectiveDecl into
11516   // its lookup structure so qualified name lookup can find it.
11517   DeclContext *Ctx = S->getEntity();
11518   if (Ctx && !Ctx->isFunctionOrMethod())
11519     Ctx->addDecl(UDir);
11520   else
11521     // Otherwise, it is at block scope. The using-directives will affect lookup
11522     // only to the end of the scope.
11523     S->PushUsingDirective(UDir);
11524 }
11525 
11526 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11527                                   SourceLocation UsingLoc,
11528                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11529                                   UnqualifiedId &Name,
11530                                   SourceLocation EllipsisLoc,
11531                                   const ParsedAttributesView &AttrList) {
11532   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11533 
11534   if (SS.isEmpty()) {
11535     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11536     return nullptr;
11537   }
11538 
11539   switch (Name.getKind()) {
11540   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11541   case UnqualifiedIdKind::IK_Identifier:
11542   case UnqualifiedIdKind::IK_OperatorFunctionId:
11543   case UnqualifiedIdKind::IK_LiteralOperatorId:
11544   case UnqualifiedIdKind::IK_ConversionFunctionId:
11545     break;
11546 
11547   case UnqualifiedIdKind::IK_ConstructorName:
11548   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11549     // C++11 inheriting constructors.
11550     Diag(Name.getBeginLoc(),
11551          getLangOpts().CPlusPlus11
11552              ? diag::warn_cxx98_compat_using_decl_constructor
11553              : diag::err_using_decl_constructor)
11554         << SS.getRange();
11555 
11556     if (getLangOpts().CPlusPlus11) break;
11557 
11558     return nullptr;
11559 
11560   case UnqualifiedIdKind::IK_DestructorName:
11561     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11562     return nullptr;
11563 
11564   case UnqualifiedIdKind::IK_TemplateId:
11565     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11566         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11567     return nullptr;
11568 
11569   case UnqualifiedIdKind::IK_DeductionGuideName:
11570     llvm_unreachable("cannot parse qualified deduction guide name");
11571   }
11572 
11573   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11574   DeclarationName TargetName = TargetNameInfo.getName();
11575   if (!TargetName)
11576     return nullptr;
11577 
11578   // Warn about access declarations.
11579   if (UsingLoc.isInvalid()) {
11580     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11581                                  ? diag::err_access_decl
11582                                  : diag::warn_access_decl_deprecated)
11583         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11584   }
11585 
11586   if (EllipsisLoc.isInvalid()) {
11587     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11588         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11589       return nullptr;
11590   } else {
11591     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11592         !TargetNameInfo.containsUnexpandedParameterPack()) {
11593       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11594         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11595       EllipsisLoc = SourceLocation();
11596     }
11597   }
11598 
11599   NamedDecl *UD =
11600       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11601                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11602                             /*IsInstantiation*/false);
11603   if (UD)
11604     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11605 
11606   return UD;
11607 }
11608 
11609 /// Determine whether a using declaration considers the given
11610 /// declarations as "equivalent", e.g., if they are redeclarations of
11611 /// the same entity or are both typedefs of the same type.
11612 static bool
11613 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11614   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11615     return true;
11616 
11617   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11618     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11619       return Context.hasSameType(TD1->getUnderlyingType(),
11620                                  TD2->getUnderlyingType());
11621 
11622   return false;
11623 }
11624 
11625 
11626 /// Determines whether to create a using shadow decl for a particular
11627 /// decl, given the set of decls existing prior to this using lookup.
11628 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11629                                 const LookupResult &Previous,
11630                                 UsingShadowDecl *&PrevShadow) {
11631   // Diagnose finding a decl which is not from a base class of the
11632   // current class.  We do this now because there are cases where this
11633   // function will silently decide not to build a shadow decl, which
11634   // will pre-empt further diagnostics.
11635   //
11636   // We don't need to do this in C++11 because we do the check once on
11637   // the qualifier.
11638   //
11639   // FIXME: diagnose the following if we care enough:
11640   //   struct A { int foo; };
11641   //   struct B : A { using A::foo; };
11642   //   template <class T> struct C : A {};
11643   //   template <class T> struct D : C<T> { using B::foo; } // <---
11644   // This is invalid (during instantiation) in C++03 because B::foo
11645   // resolves to the using decl in B, which is not a base class of D<T>.
11646   // We can't diagnose it immediately because C<T> is an unknown
11647   // specialization.  The UsingShadowDecl in D<T> then points directly
11648   // to A::foo, which will look well-formed when we instantiate.
11649   // The right solution is to not collapse the shadow-decl chain.
11650   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11651     DeclContext *OrigDC = Orig->getDeclContext();
11652 
11653     // Handle enums and anonymous structs.
11654     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11655     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11656     while (OrigRec->isAnonymousStructOrUnion())
11657       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11658 
11659     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11660       if (OrigDC == CurContext) {
11661         Diag(Using->getLocation(),
11662              diag::err_using_decl_nested_name_specifier_is_current_class)
11663           << Using->getQualifierLoc().getSourceRange();
11664         Diag(Orig->getLocation(), diag::note_using_decl_target);
11665         Using->setInvalidDecl();
11666         return true;
11667       }
11668 
11669       Diag(Using->getQualifierLoc().getBeginLoc(),
11670            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11671         << Using->getQualifier()
11672         << cast<CXXRecordDecl>(CurContext)
11673         << Using->getQualifierLoc().getSourceRange();
11674       Diag(Orig->getLocation(), diag::note_using_decl_target);
11675       Using->setInvalidDecl();
11676       return true;
11677     }
11678   }
11679 
11680   if (Previous.empty()) return false;
11681 
11682   NamedDecl *Target = Orig;
11683   if (isa<UsingShadowDecl>(Target))
11684     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11685 
11686   // If the target happens to be one of the previous declarations, we
11687   // don't have a conflict.
11688   //
11689   // FIXME: but we might be increasing its access, in which case we
11690   // should redeclare it.
11691   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11692   bool FoundEquivalentDecl = false;
11693   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11694          I != E; ++I) {
11695     NamedDecl *D = (*I)->getUnderlyingDecl();
11696     // We can have UsingDecls in our Previous results because we use the same
11697     // LookupResult for checking whether the UsingDecl itself is a valid
11698     // redeclaration.
11699     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11700       continue;
11701 
11702     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11703       // C++ [class.mem]p19:
11704       //   If T is the name of a class, then [every named member other than
11705       //   a non-static data member] shall have a name different from T
11706       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11707           !isa<IndirectFieldDecl>(Target) &&
11708           !isa<UnresolvedUsingValueDecl>(Target) &&
11709           DiagnoseClassNameShadow(
11710               CurContext,
11711               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11712         return true;
11713     }
11714 
11715     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11716       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11717         PrevShadow = Shadow;
11718       FoundEquivalentDecl = true;
11719     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11720       // We don't conflict with an existing using shadow decl of an equivalent
11721       // declaration, but we're not a redeclaration of it.
11722       FoundEquivalentDecl = true;
11723     }
11724 
11725     if (isVisible(D))
11726       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11727   }
11728 
11729   if (FoundEquivalentDecl)
11730     return false;
11731 
11732   if (FunctionDecl *FD = Target->getAsFunction()) {
11733     NamedDecl *OldDecl = nullptr;
11734     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11735                           /*IsForUsingDecl*/ true)) {
11736     case Ovl_Overload:
11737       return false;
11738 
11739     case Ovl_NonFunction:
11740       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11741       break;
11742 
11743     // We found a decl with the exact signature.
11744     case Ovl_Match:
11745       // If we're in a record, we want to hide the target, so we
11746       // return true (without a diagnostic) to tell the caller not to
11747       // build a shadow decl.
11748       if (CurContext->isRecord())
11749         return true;
11750 
11751       // If we're not in a record, this is an error.
11752       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11753       break;
11754     }
11755 
11756     Diag(Target->getLocation(), diag::note_using_decl_target);
11757     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11758     Using->setInvalidDecl();
11759     return true;
11760   }
11761 
11762   // Target is not a function.
11763 
11764   if (isa<TagDecl>(Target)) {
11765     // No conflict between a tag and a non-tag.
11766     if (!Tag) return false;
11767 
11768     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11769     Diag(Target->getLocation(), diag::note_using_decl_target);
11770     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11771     Using->setInvalidDecl();
11772     return true;
11773   }
11774 
11775   // No conflict between a tag and a non-tag.
11776   if (!NonTag) return false;
11777 
11778   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11779   Diag(Target->getLocation(), diag::note_using_decl_target);
11780   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11781   Using->setInvalidDecl();
11782   return true;
11783 }
11784 
11785 /// Determine whether a direct base class is a virtual base class.
11786 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11787   if (!Derived->getNumVBases())
11788     return false;
11789   for (auto &B : Derived->bases())
11790     if (B.getType()->getAsCXXRecordDecl() == Base)
11791       return B.isVirtual();
11792   llvm_unreachable("not a direct base class");
11793 }
11794 
11795 /// Builds a shadow declaration corresponding to a 'using' declaration.
11796 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11797                                             UsingDecl *UD,
11798                                             NamedDecl *Orig,
11799                                             UsingShadowDecl *PrevDecl) {
11800   // If we resolved to another shadow declaration, just coalesce them.
11801   NamedDecl *Target = Orig;
11802   if (isa<UsingShadowDecl>(Target)) {
11803     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11804     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11805   }
11806 
11807   NamedDecl *NonTemplateTarget = Target;
11808   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11809     NonTemplateTarget = TargetTD->getTemplatedDecl();
11810 
11811   UsingShadowDecl *Shadow;
11812   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11813     bool IsVirtualBase =
11814         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11815                             UD->getQualifier()->getAsRecordDecl());
11816     Shadow = ConstructorUsingShadowDecl::Create(
11817         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11818   } else {
11819     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11820                                      Target);
11821   }
11822   UD->addShadowDecl(Shadow);
11823 
11824   Shadow->setAccess(UD->getAccess());
11825   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11826     Shadow->setInvalidDecl();
11827 
11828   Shadow->setPreviousDecl(PrevDecl);
11829 
11830   if (S)
11831     PushOnScopeChains(Shadow, S);
11832   else
11833     CurContext->addDecl(Shadow);
11834 
11835 
11836   return Shadow;
11837 }
11838 
11839 /// Hides a using shadow declaration.  This is required by the current
11840 /// using-decl implementation when a resolvable using declaration in a
11841 /// class is followed by a declaration which would hide or override
11842 /// one or more of the using decl's targets; for example:
11843 ///
11844 ///   struct Base { void foo(int); };
11845 ///   struct Derived : Base {
11846 ///     using Base::foo;
11847 ///     void foo(int);
11848 ///   };
11849 ///
11850 /// The governing language is C++03 [namespace.udecl]p12:
11851 ///
11852 ///   When a using-declaration brings names from a base class into a
11853 ///   derived class scope, member functions in the derived class
11854 ///   override and/or hide member functions with the same name and
11855 ///   parameter types in a base class (rather than conflicting).
11856 ///
11857 /// There are two ways to implement this:
11858 ///   (1) optimistically create shadow decls when they're not hidden
11859 ///       by existing declarations, or
11860 ///   (2) don't create any shadow decls (or at least don't make them
11861 ///       visible) until we've fully parsed/instantiated the class.
11862 /// The problem with (1) is that we might have to retroactively remove
11863 /// a shadow decl, which requires several O(n) operations because the
11864 /// decl structures are (very reasonably) not designed for removal.
11865 /// (2) avoids this but is very fiddly and phase-dependent.
11866 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11867   if (Shadow->getDeclName().getNameKind() ==
11868         DeclarationName::CXXConversionFunctionName)
11869     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11870 
11871   // Remove it from the DeclContext...
11872   Shadow->getDeclContext()->removeDecl(Shadow);
11873 
11874   // ...and the scope, if applicable...
11875   if (S) {
11876     S->RemoveDecl(Shadow);
11877     IdResolver.RemoveDecl(Shadow);
11878   }
11879 
11880   // ...and the using decl.
11881   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11882 
11883   // TODO: complain somehow if Shadow was used.  It shouldn't
11884   // be possible for this to happen, because...?
11885 }
11886 
11887 /// Find the base specifier for a base class with the given type.
11888 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11889                                                 QualType DesiredBase,
11890                                                 bool &AnyDependentBases) {
11891   // Check whether the named type is a direct base class.
11892   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11893     .getUnqualifiedType();
11894   for (auto &Base : Derived->bases()) {
11895     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11896     if (CanonicalDesiredBase == BaseType)
11897       return &Base;
11898     if (BaseType->isDependentType())
11899       AnyDependentBases = true;
11900   }
11901   return nullptr;
11902 }
11903 
11904 namespace {
11905 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11906 public:
11907   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11908                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11909       : HasTypenameKeyword(HasTypenameKeyword),
11910         IsInstantiation(IsInstantiation), OldNNS(NNS),
11911         RequireMemberOf(RequireMemberOf) {}
11912 
11913   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11914     NamedDecl *ND = Candidate.getCorrectionDecl();
11915 
11916     // Keywords are not valid here.
11917     if (!ND || isa<NamespaceDecl>(ND))
11918       return false;
11919 
11920     // Completely unqualified names are invalid for a 'using' declaration.
11921     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11922       return false;
11923 
11924     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11925     // reject.
11926 
11927     if (RequireMemberOf) {
11928       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11929       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11930         // No-one ever wants a using-declaration to name an injected-class-name
11931         // of a base class, unless they're declaring an inheriting constructor.
11932         ASTContext &Ctx = ND->getASTContext();
11933         if (!Ctx.getLangOpts().CPlusPlus11)
11934           return false;
11935         QualType FoundType = Ctx.getRecordType(FoundRecord);
11936 
11937         // Check that the injected-class-name is named as a member of its own
11938         // type; we don't want to suggest 'using Derived::Base;', since that
11939         // means something else.
11940         NestedNameSpecifier *Specifier =
11941             Candidate.WillReplaceSpecifier()
11942                 ? Candidate.getCorrectionSpecifier()
11943                 : OldNNS;
11944         if (!Specifier->getAsType() ||
11945             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11946           return false;
11947 
11948         // Check that this inheriting constructor declaration actually names a
11949         // direct base class of the current class.
11950         bool AnyDependentBases = false;
11951         if (!findDirectBaseWithType(RequireMemberOf,
11952                                     Ctx.getRecordType(FoundRecord),
11953                                     AnyDependentBases) &&
11954             !AnyDependentBases)
11955           return false;
11956       } else {
11957         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11958         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11959           return false;
11960 
11961         // FIXME: Check that the base class member is accessible?
11962       }
11963     } else {
11964       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11965       if (FoundRecord && FoundRecord->isInjectedClassName())
11966         return false;
11967     }
11968 
11969     if (isa<TypeDecl>(ND))
11970       return HasTypenameKeyword || !IsInstantiation;
11971 
11972     return !HasTypenameKeyword;
11973   }
11974 
11975   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11976     return std::make_unique<UsingValidatorCCC>(*this);
11977   }
11978 
11979 private:
11980   bool HasTypenameKeyword;
11981   bool IsInstantiation;
11982   NestedNameSpecifier *OldNNS;
11983   CXXRecordDecl *RequireMemberOf;
11984 };
11985 } // end anonymous namespace
11986 
11987 /// Builds a using declaration.
11988 ///
11989 /// \param IsInstantiation - Whether this call arises from an
11990 ///   instantiation of an unresolved using declaration.  We treat
11991 ///   the lookup differently for these declarations.
11992 NamedDecl *Sema::BuildUsingDeclaration(
11993     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11994     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11995     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11996     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11997   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11998   SourceLocation IdentLoc = NameInfo.getLoc();
11999   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12000 
12001   // FIXME: We ignore attributes for now.
12002 
12003   // For an inheriting constructor declaration, the name of the using
12004   // declaration is the name of a constructor in this class, not in the
12005   // base class.
12006   DeclarationNameInfo UsingName = NameInfo;
12007   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12008     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12009       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12010           Context.getCanonicalType(Context.getRecordType(RD))));
12011 
12012   // Do the redeclaration lookup in the current scope.
12013   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12014                         ForVisibleRedeclaration);
12015   Previous.setHideTags(false);
12016   if (S) {
12017     LookupName(Previous, S);
12018 
12019     // It is really dumb that we have to do this.
12020     LookupResult::Filter F = Previous.makeFilter();
12021     while (F.hasNext()) {
12022       NamedDecl *D = F.next();
12023       if (!isDeclInScope(D, CurContext, S))
12024         F.erase();
12025       // If we found a local extern declaration that's not ordinarily visible,
12026       // and this declaration is being added to a non-block scope, ignore it.
12027       // We're only checking for scope conflicts here, not also for violations
12028       // of the linkage rules.
12029       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12030                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12031         F.erase();
12032     }
12033     F.done();
12034   } else {
12035     assert(IsInstantiation && "no scope in non-instantiation");
12036     if (CurContext->isRecord())
12037       LookupQualifiedName(Previous, CurContext);
12038     else {
12039       // No redeclaration check is needed here; in non-member contexts we
12040       // diagnosed all possible conflicts with other using-declarations when
12041       // building the template:
12042       //
12043       // For a dependent non-type using declaration, the only valid case is
12044       // if we instantiate to a single enumerator. We check for conflicts
12045       // between shadow declarations we introduce, and we check in the template
12046       // definition for conflicts between a non-type using declaration and any
12047       // other declaration, which together covers all cases.
12048       //
12049       // A dependent typename using declaration will never successfully
12050       // instantiate, since it will always name a class member, so we reject
12051       // that in the template definition.
12052     }
12053   }
12054 
12055   // Check for invalid redeclarations.
12056   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12057                                   SS, IdentLoc, Previous))
12058     return nullptr;
12059 
12060   // Check for bad qualifiers.
12061   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12062                               IdentLoc))
12063     return nullptr;
12064 
12065   DeclContext *LookupContext = computeDeclContext(SS);
12066   NamedDecl *D;
12067   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12068   if (!LookupContext || EllipsisLoc.isValid()) {
12069     if (HasTypenameKeyword) {
12070       // FIXME: not all declaration name kinds are legal here
12071       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12072                                               UsingLoc, TypenameLoc,
12073                                               QualifierLoc,
12074                                               IdentLoc, NameInfo.getName(),
12075                                               EllipsisLoc);
12076     } else {
12077       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12078                                            QualifierLoc, NameInfo, EllipsisLoc);
12079     }
12080     D->setAccess(AS);
12081     CurContext->addDecl(D);
12082     return D;
12083   }
12084 
12085   auto Build = [&](bool Invalid) {
12086     UsingDecl *UD =
12087         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12088                           UsingName, HasTypenameKeyword);
12089     UD->setAccess(AS);
12090     CurContext->addDecl(UD);
12091     UD->setInvalidDecl(Invalid);
12092     return UD;
12093   };
12094   auto BuildInvalid = [&]{ return Build(true); };
12095   auto BuildValid = [&]{ return Build(false); };
12096 
12097   if (RequireCompleteDeclContext(SS, LookupContext))
12098     return BuildInvalid();
12099 
12100   // Look up the target name.
12101   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12102 
12103   // Unlike most lookups, we don't always want to hide tag
12104   // declarations: tag names are visible through the using declaration
12105   // even if hidden by ordinary names, *except* in a dependent context
12106   // where it's important for the sanity of two-phase lookup.
12107   if (!IsInstantiation)
12108     R.setHideTags(false);
12109 
12110   // For the purposes of this lookup, we have a base object type
12111   // equal to that of the current context.
12112   if (CurContext->isRecord()) {
12113     R.setBaseObjectType(
12114                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12115   }
12116 
12117   LookupQualifiedName(R, LookupContext);
12118 
12119   // Try to correct typos if possible. If constructor name lookup finds no
12120   // results, that means the named class has no explicit constructors, and we
12121   // suppressed declaring implicit ones (probably because it's dependent or
12122   // invalid).
12123   if (R.empty() &&
12124       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12125     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12126     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12127     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12128     auto *II = NameInfo.getName().getAsIdentifierInfo();
12129     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12130         CurContext->isStdNamespace() &&
12131         isa<TranslationUnitDecl>(LookupContext) &&
12132         getSourceManager().isInSystemHeader(UsingLoc))
12133       return nullptr;
12134     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12135                           dyn_cast<CXXRecordDecl>(CurContext));
12136     if (TypoCorrection Corrected =
12137             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12138                         CTK_ErrorRecovery)) {
12139       // We reject candidates where DroppedSpecifier == true, hence the
12140       // literal '0' below.
12141       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12142                                 << NameInfo.getName() << LookupContext << 0
12143                                 << SS.getRange());
12144 
12145       // If we picked a correction with no attached Decl we can't do anything
12146       // useful with it, bail out.
12147       NamedDecl *ND = Corrected.getCorrectionDecl();
12148       if (!ND)
12149         return BuildInvalid();
12150 
12151       // If we corrected to an inheriting constructor, handle it as one.
12152       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12153       if (RD && RD->isInjectedClassName()) {
12154         // The parent of the injected class name is the class itself.
12155         RD = cast<CXXRecordDecl>(RD->getParent());
12156 
12157         // Fix up the information we'll use to build the using declaration.
12158         if (Corrected.WillReplaceSpecifier()) {
12159           NestedNameSpecifierLocBuilder Builder;
12160           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12161                               QualifierLoc.getSourceRange());
12162           QualifierLoc = Builder.getWithLocInContext(Context);
12163         }
12164 
12165         // In this case, the name we introduce is the name of a derived class
12166         // constructor.
12167         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12168         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12169             Context.getCanonicalType(Context.getRecordType(CurClass))));
12170         UsingName.setNamedTypeInfo(nullptr);
12171         for (auto *Ctor : LookupConstructors(RD))
12172           R.addDecl(Ctor);
12173         R.resolveKind();
12174       } else {
12175         // FIXME: Pick up all the declarations if we found an overloaded
12176         // function.
12177         UsingName.setName(ND->getDeclName());
12178         R.addDecl(ND);
12179       }
12180     } else {
12181       Diag(IdentLoc, diag::err_no_member)
12182         << NameInfo.getName() << LookupContext << SS.getRange();
12183       return BuildInvalid();
12184     }
12185   }
12186 
12187   if (R.isAmbiguous())
12188     return BuildInvalid();
12189 
12190   if (HasTypenameKeyword) {
12191     // If we asked for a typename and got a non-type decl, error out.
12192     if (!R.getAsSingle<TypeDecl>()) {
12193       Diag(IdentLoc, diag::err_using_typename_non_type);
12194       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12195         Diag((*I)->getUnderlyingDecl()->getLocation(),
12196              diag::note_using_decl_target);
12197       return BuildInvalid();
12198     }
12199   } else {
12200     // If we asked for a non-typename and we got a type, error out,
12201     // but only if this is an instantiation of an unresolved using
12202     // decl.  Otherwise just silently find the type name.
12203     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12204       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12205       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12206       return BuildInvalid();
12207     }
12208   }
12209 
12210   // C++14 [namespace.udecl]p6:
12211   // A using-declaration shall not name a namespace.
12212   if (R.getAsSingle<NamespaceDecl>()) {
12213     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12214       << SS.getRange();
12215     return BuildInvalid();
12216   }
12217 
12218   // C++14 [namespace.udecl]p7:
12219   // A using-declaration shall not name a scoped enumerator.
12220   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12221     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12222       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12223         << SS.getRange();
12224       return BuildInvalid();
12225     }
12226   }
12227 
12228   UsingDecl *UD = BuildValid();
12229 
12230   // Some additional rules apply to inheriting constructors.
12231   if (UsingName.getName().getNameKind() ==
12232         DeclarationName::CXXConstructorName) {
12233     // Suppress access diagnostics; the access check is instead performed at the
12234     // point of use for an inheriting constructor.
12235     R.suppressDiagnostics();
12236     if (CheckInheritingConstructorUsingDecl(UD))
12237       return UD;
12238   }
12239 
12240   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12241     UsingShadowDecl *PrevDecl = nullptr;
12242     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12243       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12244   }
12245 
12246   return UD;
12247 }
12248 
12249 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12250                                     ArrayRef<NamedDecl *> Expansions) {
12251   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12252          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12253          isa<UsingPackDecl>(InstantiatedFrom));
12254 
12255   auto *UPD =
12256       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12257   UPD->setAccess(InstantiatedFrom->getAccess());
12258   CurContext->addDecl(UPD);
12259   return UPD;
12260 }
12261 
12262 /// Additional checks for a using declaration referring to a constructor name.
12263 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12264   assert(!UD->hasTypename() && "expecting a constructor name");
12265 
12266   const Type *SourceType = UD->getQualifier()->getAsType();
12267   assert(SourceType &&
12268          "Using decl naming constructor doesn't have type in scope spec.");
12269   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12270 
12271   // Check whether the named type is a direct base class.
12272   bool AnyDependentBases = false;
12273   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12274                                       AnyDependentBases);
12275   if (!Base && !AnyDependentBases) {
12276     Diag(UD->getUsingLoc(),
12277          diag::err_using_decl_constructor_not_in_direct_base)
12278       << UD->getNameInfo().getSourceRange()
12279       << QualType(SourceType, 0) << TargetClass;
12280     UD->setInvalidDecl();
12281     return true;
12282   }
12283 
12284   if (Base)
12285     Base->setInheritConstructors();
12286 
12287   return false;
12288 }
12289 
12290 /// Checks that the given using declaration is not an invalid
12291 /// redeclaration.  Note that this is checking only for the using decl
12292 /// itself, not for any ill-formedness among the UsingShadowDecls.
12293 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12294                                        bool HasTypenameKeyword,
12295                                        const CXXScopeSpec &SS,
12296                                        SourceLocation NameLoc,
12297                                        const LookupResult &Prev) {
12298   NestedNameSpecifier *Qual = SS.getScopeRep();
12299 
12300   // C++03 [namespace.udecl]p8:
12301   // C++0x [namespace.udecl]p10:
12302   //   A using-declaration is a declaration and can therefore be used
12303   //   repeatedly where (and only where) multiple declarations are
12304   //   allowed.
12305   //
12306   // That's in non-member contexts.
12307   if (!CurContext->getRedeclContext()->isRecord()) {
12308     // A dependent qualifier outside a class can only ever resolve to an
12309     // enumeration type. Therefore it conflicts with any other non-type
12310     // declaration in the same scope.
12311     // FIXME: How should we check for dependent type-type conflicts at block
12312     // scope?
12313     if (Qual->isDependent() && !HasTypenameKeyword) {
12314       for (auto *D : Prev) {
12315         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12316           bool OldCouldBeEnumerator =
12317               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12318           Diag(NameLoc,
12319                OldCouldBeEnumerator ? diag::err_redefinition
12320                                     : diag::err_redefinition_different_kind)
12321               << Prev.getLookupName();
12322           Diag(D->getLocation(), diag::note_previous_definition);
12323           return true;
12324         }
12325       }
12326     }
12327     return false;
12328   }
12329 
12330   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12331     NamedDecl *D = *I;
12332 
12333     bool DTypename;
12334     NestedNameSpecifier *DQual;
12335     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12336       DTypename = UD->hasTypename();
12337       DQual = UD->getQualifier();
12338     } else if (UnresolvedUsingValueDecl *UD
12339                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12340       DTypename = false;
12341       DQual = UD->getQualifier();
12342     } else if (UnresolvedUsingTypenameDecl *UD
12343                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12344       DTypename = true;
12345       DQual = UD->getQualifier();
12346     } else continue;
12347 
12348     // using decls differ if one says 'typename' and the other doesn't.
12349     // FIXME: non-dependent using decls?
12350     if (HasTypenameKeyword != DTypename) continue;
12351 
12352     // using decls differ if they name different scopes (but note that
12353     // template instantiation can cause this check to trigger when it
12354     // didn't before instantiation).
12355     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12356         Context.getCanonicalNestedNameSpecifier(DQual))
12357       continue;
12358 
12359     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12360     Diag(D->getLocation(), diag::note_using_decl) << 1;
12361     return true;
12362   }
12363 
12364   return false;
12365 }
12366 
12367 
12368 /// Checks that the given nested-name qualifier used in a using decl
12369 /// in the current context is appropriately related to the current
12370 /// scope.  If an error is found, diagnoses it and returns true.
12371 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12372                                    bool HasTypename,
12373                                    const CXXScopeSpec &SS,
12374                                    const DeclarationNameInfo &NameInfo,
12375                                    SourceLocation NameLoc) {
12376   DeclContext *NamedContext = computeDeclContext(SS);
12377 
12378   if (!CurContext->isRecord()) {
12379     // C++03 [namespace.udecl]p3:
12380     // C++0x [namespace.udecl]p8:
12381     //   A using-declaration for a class member shall be a member-declaration.
12382 
12383     // If we weren't able to compute a valid scope, it might validly be a
12384     // dependent class scope or a dependent enumeration unscoped scope. If
12385     // we have a 'typename' keyword, the scope must resolve to a class type.
12386     if ((HasTypename && !NamedContext) ||
12387         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12388       auto *RD = NamedContext
12389                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12390                      : nullptr;
12391       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12392         RD = nullptr;
12393 
12394       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12395         << SS.getRange();
12396 
12397       // If we have a complete, non-dependent source type, try to suggest a
12398       // way to get the same effect.
12399       if (!RD)
12400         return true;
12401 
12402       // Find what this using-declaration was referring to.
12403       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12404       R.setHideTags(false);
12405       R.suppressDiagnostics();
12406       LookupQualifiedName(R, RD);
12407 
12408       if (R.getAsSingle<TypeDecl>()) {
12409         if (getLangOpts().CPlusPlus11) {
12410           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12411           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12412             << 0 // alias declaration
12413             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12414                                           NameInfo.getName().getAsString() +
12415                                               " = ");
12416         } else {
12417           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12418           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12419           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12420             << 1 // typedef declaration
12421             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12422             << FixItHint::CreateInsertion(
12423                    InsertLoc, " " + NameInfo.getName().getAsString());
12424         }
12425       } else if (R.getAsSingle<VarDecl>()) {
12426         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12427         // repeating the type of the static data member here.
12428         FixItHint FixIt;
12429         if (getLangOpts().CPlusPlus11) {
12430           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12431           FixIt = FixItHint::CreateReplacement(
12432               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12433         }
12434 
12435         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12436           << 2 // reference declaration
12437           << FixIt;
12438       } else if (R.getAsSingle<EnumConstantDecl>()) {
12439         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12440         // repeating the type of the enumeration here, and we can't do so if
12441         // the type is anonymous.
12442         FixItHint FixIt;
12443         if (getLangOpts().CPlusPlus11) {
12444           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12445           FixIt = FixItHint::CreateReplacement(
12446               UsingLoc,
12447               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12448         }
12449 
12450         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12451           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12452           << FixIt;
12453       }
12454       return true;
12455     }
12456 
12457     // Otherwise, this might be valid.
12458     return false;
12459   }
12460 
12461   // The current scope is a record.
12462 
12463   // If the named context is dependent, we can't decide much.
12464   if (!NamedContext) {
12465     // FIXME: in C++0x, we can diagnose if we can prove that the
12466     // nested-name-specifier does not refer to a base class, which is
12467     // still possible in some cases.
12468 
12469     // Otherwise we have to conservatively report that things might be
12470     // okay.
12471     return false;
12472   }
12473 
12474   if (!NamedContext->isRecord()) {
12475     // Ideally this would point at the last name in the specifier,
12476     // but we don't have that level of source info.
12477     Diag(SS.getRange().getBegin(),
12478          diag::err_using_decl_nested_name_specifier_is_not_class)
12479       << SS.getScopeRep() << SS.getRange();
12480     return true;
12481   }
12482 
12483   if (!NamedContext->isDependentContext() &&
12484       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12485     return true;
12486 
12487   if (getLangOpts().CPlusPlus11) {
12488     // C++11 [namespace.udecl]p3:
12489     //   In a using-declaration used as a member-declaration, the
12490     //   nested-name-specifier shall name a base class of the class
12491     //   being defined.
12492 
12493     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12494                                  cast<CXXRecordDecl>(NamedContext))) {
12495       if (CurContext == NamedContext) {
12496         Diag(NameLoc,
12497              diag::err_using_decl_nested_name_specifier_is_current_class)
12498           << SS.getRange();
12499         return true;
12500       }
12501 
12502       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12503         Diag(SS.getRange().getBegin(),
12504              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12505           << SS.getScopeRep()
12506           << cast<CXXRecordDecl>(CurContext)
12507           << SS.getRange();
12508       }
12509       return true;
12510     }
12511 
12512     return false;
12513   }
12514 
12515   // C++03 [namespace.udecl]p4:
12516   //   A using-declaration used as a member-declaration shall refer
12517   //   to a member of a base class of the class being defined [etc.].
12518 
12519   // Salient point: SS doesn't have to name a base class as long as
12520   // lookup only finds members from base classes.  Therefore we can
12521   // diagnose here only if we can prove that that can't happen,
12522   // i.e. if the class hierarchies provably don't intersect.
12523 
12524   // TODO: it would be nice if "definitely valid" results were cached
12525   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12526   // need to be repeated.
12527 
12528   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12529   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12530     Bases.insert(Base);
12531     return true;
12532   };
12533 
12534   // Collect all bases. Return false if we find a dependent base.
12535   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12536     return false;
12537 
12538   // Returns true if the base is dependent or is one of the accumulated base
12539   // classes.
12540   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12541     return !Bases.count(Base);
12542   };
12543 
12544   // Return false if the class has a dependent base or if it or one
12545   // of its bases is present in the base set of the current context.
12546   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12547       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12548     return false;
12549 
12550   Diag(SS.getRange().getBegin(),
12551        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12552     << SS.getScopeRep()
12553     << cast<CXXRecordDecl>(CurContext)
12554     << SS.getRange();
12555 
12556   return true;
12557 }
12558 
12559 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12560                                   MultiTemplateParamsArg TemplateParamLists,
12561                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12562                                   const ParsedAttributesView &AttrList,
12563                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12564   // Skip up to the relevant declaration scope.
12565   while (S->isTemplateParamScope())
12566     S = S->getParent();
12567   assert((S->getFlags() & Scope::DeclScope) &&
12568          "got alias-declaration outside of declaration scope");
12569 
12570   if (Type.isInvalid())
12571     return nullptr;
12572 
12573   bool Invalid = false;
12574   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12575   TypeSourceInfo *TInfo = nullptr;
12576   GetTypeFromParser(Type.get(), &TInfo);
12577 
12578   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12579     return nullptr;
12580 
12581   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12582                                       UPPC_DeclarationType)) {
12583     Invalid = true;
12584     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12585                                              TInfo->getTypeLoc().getBeginLoc());
12586   }
12587 
12588   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12589                         TemplateParamLists.size()
12590                             ? forRedeclarationInCurContext()
12591                             : ForVisibleRedeclaration);
12592   LookupName(Previous, S);
12593 
12594   // Warn about shadowing the name of a template parameter.
12595   if (Previous.isSingleResult() &&
12596       Previous.getFoundDecl()->isTemplateParameter()) {
12597     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12598     Previous.clear();
12599   }
12600 
12601   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12602          "name in alias declaration must be an identifier");
12603   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12604                                                Name.StartLocation,
12605                                                Name.Identifier, TInfo);
12606 
12607   NewTD->setAccess(AS);
12608 
12609   if (Invalid)
12610     NewTD->setInvalidDecl();
12611 
12612   ProcessDeclAttributeList(S, NewTD, AttrList);
12613   AddPragmaAttributes(S, NewTD);
12614 
12615   CheckTypedefForVariablyModifiedType(S, NewTD);
12616   Invalid |= NewTD->isInvalidDecl();
12617 
12618   bool Redeclaration = false;
12619 
12620   NamedDecl *NewND;
12621   if (TemplateParamLists.size()) {
12622     TypeAliasTemplateDecl *OldDecl = nullptr;
12623     TemplateParameterList *OldTemplateParams = nullptr;
12624 
12625     if (TemplateParamLists.size() != 1) {
12626       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12627         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12628          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12629     }
12630     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12631 
12632     // Check that we can declare a template here.
12633     if (CheckTemplateDeclScope(S, TemplateParams))
12634       return nullptr;
12635 
12636     // Only consider previous declarations in the same scope.
12637     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12638                          /*ExplicitInstantiationOrSpecialization*/false);
12639     if (!Previous.empty()) {
12640       Redeclaration = true;
12641 
12642       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12643       if (!OldDecl && !Invalid) {
12644         Diag(UsingLoc, diag::err_redefinition_different_kind)
12645           << Name.Identifier;
12646 
12647         NamedDecl *OldD = Previous.getRepresentativeDecl();
12648         if (OldD->getLocation().isValid())
12649           Diag(OldD->getLocation(), diag::note_previous_definition);
12650 
12651         Invalid = true;
12652       }
12653 
12654       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12655         if (TemplateParameterListsAreEqual(TemplateParams,
12656                                            OldDecl->getTemplateParameters(),
12657                                            /*Complain=*/true,
12658                                            TPL_TemplateMatch))
12659           OldTemplateParams =
12660               OldDecl->getMostRecentDecl()->getTemplateParameters();
12661         else
12662           Invalid = true;
12663 
12664         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12665         if (!Invalid &&
12666             !Context.hasSameType(OldTD->getUnderlyingType(),
12667                                  NewTD->getUnderlyingType())) {
12668           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12669           // but we can't reasonably accept it.
12670           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12671             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12672           if (OldTD->getLocation().isValid())
12673             Diag(OldTD->getLocation(), diag::note_previous_definition);
12674           Invalid = true;
12675         }
12676       }
12677     }
12678 
12679     // Merge any previous default template arguments into our parameters,
12680     // and check the parameter list.
12681     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12682                                    TPC_TypeAliasTemplate))
12683       return nullptr;
12684 
12685     TypeAliasTemplateDecl *NewDecl =
12686       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12687                                     Name.Identifier, TemplateParams,
12688                                     NewTD);
12689     NewTD->setDescribedAliasTemplate(NewDecl);
12690 
12691     NewDecl->setAccess(AS);
12692 
12693     if (Invalid)
12694       NewDecl->setInvalidDecl();
12695     else if (OldDecl) {
12696       NewDecl->setPreviousDecl(OldDecl);
12697       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12698     }
12699 
12700     NewND = NewDecl;
12701   } else {
12702     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12703       setTagNameForLinkagePurposes(TD, NewTD);
12704       handleTagNumbering(TD, S);
12705     }
12706     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12707     NewND = NewTD;
12708   }
12709 
12710   PushOnScopeChains(NewND, S);
12711   ActOnDocumentableDecl(NewND);
12712   return NewND;
12713 }
12714 
12715 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12716                                    SourceLocation AliasLoc,
12717                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12718                                    SourceLocation IdentLoc,
12719                                    IdentifierInfo *Ident) {
12720 
12721   // Lookup the namespace name.
12722   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12723   LookupParsedName(R, S, &SS);
12724 
12725   if (R.isAmbiguous())
12726     return nullptr;
12727 
12728   if (R.empty()) {
12729     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12730       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12731       return nullptr;
12732     }
12733   }
12734   assert(!R.isAmbiguous() && !R.empty());
12735   NamedDecl *ND = R.getRepresentativeDecl();
12736 
12737   // Check if we have a previous declaration with the same name.
12738   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12739                      ForVisibleRedeclaration);
12740   LookupName(PrevR, S);
12741 
12742   // Check we're not shadowing a template parameter.
12743   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12744     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12745     PrevR.clear();
12746   }
12747 
12748   // Filter out any other lookup result from an enclosing scope.
12749   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12750                        /*AllowInlineNamespace*/false);
12751 
12752   // Find the previous declaration and check that we can redeclare it.
12753   NamespaceAliasDecl *Prev = nullptr;
12754   if (PrevR.isSingleResult()) {
12755     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12756     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12757       // We already have an alias with the same name that points to the same
12758       // namespace; check that it matches.
12759       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12760         Prev = AD;
12761       } else if (isVisible(PrevDecl)) {
12762         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12763           << Alias;
12764         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12765           << AD->getNamespace();
12766         return nullptr;
12767       }
12768     } else if (isVisible(PrevDecl)) {
12769       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12770                             ? diag::err_redefinition
12771                             : diag::err_redefinition_different_kind;
12772       Diag(AliasLoc, DiagID) << Alias;
12773       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12774       return nullptr;
12775     }
12776   }
12777 
12778   // The use of a nested name specifier may trigger deprecation warnings.
12779   DiagnoseUseOfDecl(ND, IdentLoc);
12780 
12781   NamespaceAliasDecl *AliasDecl =
12782     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12783                                Alias, SS.getWithLocInContext(Context),
12784                                IdentLoc, ND);
12785   if (Prev)
12786     AliasDecl->setPreviousDecl(Prev);
12787 
12788   PushOnScopeChains(AliasDecl, S);
12789   return AliasDecl;
12790 }
12791 
12792 namespace {
12793 struct SpecialMemberExceptionSpecInfo
12794     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12795   SourceLocation Loc;
12796   Sema::ImplicitExceptionSpecification ExceptSpec;
12797 
12798   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12799                                  Sema::CXXSpecialMember CSM,
12800                                  Sema::InheritedConstructorInfo *ICI,
12801                                  SourceLocation Loc)
12802       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12803 
12804   bool visitBase(CXXBaseSpecifier *Base);
12805   bool visitField(FieldDecl *FD);
12806 
12807   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12808                            unsigned Quals);
12809 
12810   void visitSubobjectCall(Subobject Subobj,
12811                           Sema::SpecialMemberOverloadResult SMOR);
12812 };
12813 }
12814 
12815 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12816   auto *RT = Base->getType()->getAs<RecordType>();
12817   if (!RT)
12818     return false;
12819 
12820   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12821   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12822   if (auto *BaseCtor = SMOR.getMethod()) {
12823     visitSubobjectCall(Base, BaseCtor);
12824     return false;
12825   }
12826 
12827   visitClassSubobject(BaseClass, Base, 0);
12828   return false;
12829 }
12830 
12831 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12832   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12833     Expr *E = FD->getInClassInitializer();
12834     if (!E)
12835       // FIXME: It's a little wasteful to build and throw away a
12836       // CXXDefaultInitExpr here.
12837       // FIXME: We should have a single context note pointing at Loc, and
12838       // this location should be MD->getLocation() instead, since that's
12839       // the location where we actually use the default init expression.
12840       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12841     if (E)
12842       ExceptSpec.CalledExpr(E);
12843   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12844                             ->getAs<RecordType>()) {
12845     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12846                         FD->getType().getCVRQualifiers());
12847   }
12848   return false;
12849 }
12850 
12851 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12852                                                          Subobject Subobj,
12853                                                          unsigned Quals) {
12854   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12855   bool IsMutable = Field && Field->isMutable();
12856   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12857 }
12858 
12859 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12860     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12861   // Note, if lookup fails, it doesn't matter what exception specification we
12862   // choose because the special member will be deleted.
12863   if (CXXMethodDecl *MD = SMOR.getMethod())
12864     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12865 }
12866 
12867 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12868   llvm::APSInt Result;
12869   ExprResult Converted = CheckConvertedConstantExpression(
12870       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12871   ExplicitSpec.setExpr(Converted.get());
12872   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12873     ExplicitSpec.setKind(Result.getBoolValue()
12874                              ? ExplicitSpecKind::ResolvedTrue
12875                              : ExplicitSpecKind::ResolvedFalse);
12876     return true;
12877   }
12878   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12879   return false;
12880 }
12881 
12882 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12883   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12884   if (!ExplicitExpr->isTypeDependent())
12885     tryResolveExplicitSpecifier(ES);
12886   return ES;
12887 }
12888 
12889 static Sema::ImplicitExceptionSpecification
12890 ComputeDefaultedSpecialMemberExceptionSpec(
12891     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12892     Sema::InheritedConstructorInfo *ICI) {
12893   ComputingExceptionSpec CES(S, MD, Loc);
12894 
12895   CXXRecordDecl *ClassDecl = MD->getParent();
12896 
12897   // C++ [except.spec]p14:
12898   //   An implicitly declared special member function (Clause 12) shall have an
12899   //   exception-specification. [...]
12900   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12901   if (ClassDecl->isInvalidDecl())
12902     return Info.ExceptSpec;
12903 
12904   // FIXME: If this diagnostic fires, we're probably missing a check for
12905   // attempting to resolve an exception specification before it's known
12906   // at a higher level.
12907   if (S.RequireCompleteType(MD->getLocation(),
12908                             S.Context.getRecordType(ClassDecl),
12909                             diag::err_exception_spec_incomplete_type))
12910     return Info.ExceptSpec;
12911 
12912   // C++1z [except.spec]p7:
12913   //   [Look for exceptions thrown by] a constructor selected [...] to
12914   //   initialize a potentially constructed subobject,
12915   // C++1z [except.spec]p8:
12916   //   The exception specification for an implicitly-declared destructor, or a
12917   //   destructor without a noexcept-specifier, is potentially-throwing if and
12918   //   only if any of the destructors for any of its potentially constructed
12919   //   subojects is potentially throwing.
12920   // FIXME: We respect the first rule but ignore the "potentially constructed"
12921   // in the second rule to resolve a core issue (no number yet) that would have
12922   // us reject:
12923   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12924   //   struct B : A {};
12925   //   struct C : B { void f(); };
12926   // ... due to giving B::~B() a non-throwing exception specification.
12927   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12928                                 : Info.VisitAllBases);
12929 
12930   return Info.ExceptSpec;
12931 }
12932 
12933 namespace {
12934 /// RAII object to register a special member as being currently declared.
12935 struct DeclaringSpecialMember {
12936   Sema &S;
12937   Sema::SpecialMemberDecl D;
12938   Sema::ContextRAII SavedContext;
12939   bool WasAlreadyBeingDeclared;
12940 
12941   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12942       : S(S), D(RD, CSM), SavedContext(S, RD) {
12943     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12944     if (WasAlreadyBeingDeclared)
12945       // This almost never happens, but if it does, ensure that our cache
12946       // doesn't contain a stale result.
12947       S.SpecialMemberCache.clear();
12948     else {
12949       // Register a note to be produced if we encounter an error while
12950       // declaring the special member.
12951       Sema::CodeSynthesisContext Ctx;
12952       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12953       // FIXME: We don't have a location to use here. Using the class's
12954       // location maintains the fiction that we declare all special members
12955       // with the class, but (1) it's not clear that lying about that helps our
12956       // users understand what's going on, and (2) there may be outer contexts
12957       // on the stack (some of which are relevant) and printing them exposes
12958       // our lies.
12959       Ctx.PointOfInstantiation = RD->getLocation();
12960       Ctx.Entity = RD;
12961       Ctx.SpecialMember = CSM;
12962       S.pushCodeSynthesisContext(Ctx);
12963     }
12964   }
12965   ~DeclaringSpecialMember() {
12966     if (!WasAlreadyBeingDeclared) {
12967       S.SpecialMembersBeingDeclared.erase(D);
12968       S.popCodeSynthesisContext();
12969     }
12970   }
12971 
12972   /// Are we already trying to declare this special member?
12973   bool isAlreadyBeingDeclared() const {
12974     return WasAlreadyBeingDeclared;
12975   }
12976 };
12977 }
12978 
12979 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12980   // Look up any existing declarations, but don't trigger declaration of all
12981   // implicit special members with this name.
12982   DeclarationName Name = FD->getDeclName();
12983   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12984                  ForExternalRedeclaration);
12985   for (auto *D : FD->getParent()->lookup(Name))
12986     if (auto *Acceptable = R.getAcceptableDecl(D))
12987       R.addDecl(Acceptable);
12988   R.resolveKind();
12989   R.suppressDiagnostics();
12990 
12991   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12992 }
12993 
12994 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12995                                           QualType ResultTy,
12996                                           ArrayRef<QualType> Args) {
12997   // Build an exception specification pointing back at this constructor.
12998   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12999 
13000   LangAS AS = getDefaultCXXMethodAddrSpace();
13001   if (AS != LangAS::Default) {
13002     EPI.TypeQuals.addAddressSpace(AS);
13003   }
13004 
13005   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13006   SpecialMem->setType(QT);
13007 }
13008 
13009 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13010                                                      CXXRecordDecl *ClassDecl) {
13011   // C++ [class.ctor]p5:
13012   //   A default constructor for a class X is a constructor of class X
13013   //   that can be called without an argument. If there is no
13014   //   user-declared constructor for class X, a default constructor is
13015   //   implicitly declared. An implicitly-declared default constructor
13016   //   is an inline public member of its class.
13017   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13018          "Should not build implicit default constructor!");
13019 
13020   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13021   if (DSM.isAlreadyBeingDeclared())
13022     return nullptr;
13023 
13024   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13025                                                      CXXDefaultConstructor,
13026                                                      false);
13027 
13028   // Create the actual constructor declaration.
13029   CanQualType ClassType
13030     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13031   SourceLocation ClassLoc = ClassDecl->getLocation();
13032   DeclarationName Name
13033     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13034   DeclarationNameInfo NameInfo(Name, ClassLoc);
13035   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13036       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13037       /*TInfo=*/nullptr, ExplicitSpecifier(),
13038       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13039       Constexpr ? ConstexprSpecKind::Constexpr
13040                 : ConstexprSpecKind::Unspecified);
13041   DefaultCon->setAccess(AS_public);
13042   DefaultCon->setDefaulted();
13043 
13044   if (getLangOpts().CUDA) {
13045     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13046                                             DefaultCon,
13047                                             /* ConstRHS */ false,
13048                                             /* Diagnose */ false);
13049   }
13050 
13051   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13052 
13053   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13054   // constructors is easy to compute.
13055   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13056 
13057   // Note that we have declared this constructor.
13058   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13059 
13060   Scope *S = getScopeForContext(ClassDecl);
13061   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13062 
13063   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13064     SetDeclDeleted(DefaultCon, ClassLoc);
13065 
13066   if (S)
13067     PushOnScopeChains(DefaultCon, S, false);
13068   ClassDecl->addDecl(DefaultCon);
13069 
13070   return DefaultCon;
13071 }
13072 
13073 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13074                                             CXXConstructorDecl *Constructor) {
13075   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13076           !Constructor->doesThisDeclarationHaveABody() &&
13077           !Constructor->isDeleted()) &&
13078     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13079   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13080     return;
13081 
13082   CXXRecordDecl *ClassDecl = Constructor->getParent();
13083   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13084 
13085   SynthesizedFunctionScope Scope(*this, Constructor);
13086 
13087   // The exception specification is needed because we are defining the
13088   // function.
13089   ResolveExceptionSpec(CurrentLocation,
13090                        Constructor->getType()->castAs<FunctionProtoType>());
13091   MarkVTableUsed(CurrentLocation, ClassDecl);
13092 
13093   // Add a context note for diagnostics produced after this point.
13094   Scope.addContextNote(CurrentLocation);
13095 
13096   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13097     Constructor->setInvalidDecl();
13098     return;
13099   }
13100 
13101   SourceLocation Loc = Constructor->getEndLoc().isValid()
13102                            ? Constructor->getEndLoc()
13103                            : Constructor->getLocation();
13104   Constructor->setBody(new (Context) CompoundStmt(Loc));
13105   Constructor->markUsed(Context);
13106 
13107   if (ASTMutationListener *L = getASTMutationListener()) {
13108     L->CompletedImplicitDefinition(Constructor);
13109   }
13110 
13111   DiagnoseUninitializedFields(*this, Constructor);
13112 }
13113 
13114 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13115   // Perform any delayed checks on exception specifications.
13116   CheckDelayedMemberExceptionSpecs();
13117 }
13118 
13119 /// Find or create the fake constructor we synthesize to model constructing an
13120 /// object of a derived class via a constructor of a base class.
13121 CXXConstructorDecl *
13122 Sema::findInheritingConstructor(SourceLocation Loc,
13123                                 CXXConstructorDecl *BaseCtor,
13124                                 ConstructorUsingShadowDecl *Shadow) {
13125   CXXRecordDecl *Derived = Shadow->getParent();
13126   SourceLocation UsingLoc = Shadow->getLocation();
13127 
13128   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13129   // For now we use the name of the base class constructor as a member of the
13130   // derived class to indicate a (fake) inherited constructor name.
13131   DeclarationName Name = BaseCtor->getDeclName();
13132 
13133   // Check to see if we already have a fake constructor for this inherited
13134   // constructor call.
13135   for (NamedDecl *Ctor : Derived->lookup(Name))
13136     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13137                                ->getInheritedConstructor()
13138                                .getConstructor(),
13139                            BaseCtor))
13140       return cast<CXXConstructorDecl>(Ctor);
13141 
13142   DeclarationNameInfo NameInfo(Name, UsingLoc);
13143   TypeSourceInfo *TInfo =
13144       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13145   FunctionProtoTypeLoc ProtoLoc =
13146       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13147 
13148   // Check the inherited constructor is valid and find the list of base classes
13149   // from which it was inherited.
13150   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13151 
13152   bool Constexpr =
13153       BaseCtor->isConstexpr() &&
13154       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13155                                         false, BaseCtor, &ICI);
13156 
13157   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13158       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13159       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13160       /*isImplicitlyDeclared=*/true,
13161       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13162       InheritedConstructor(Shadow, BaseCtor),
13163       BaseCtor->getTrailingRequiresClause());
13164   if (Shadow->isInvalidDecl())
13165     DerivedCtor->setInvalidDecl();
13166 
13167   // Build an unevaluated exception specification for this fake constructor.
13168   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13169   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13170   EPI.ExceptionSpec.Type = EST_Unevaluated;
13171   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13172   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13173                                                FPT->getParamTypes(), EPI));
13174 
13175   // Build the parameter declarations.
13176   SmallVector<ParmVarDecl *, 16> ParamDecls;
13177   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13178     TypeSourceInfo *TInfo =
13179         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13180     ParmVarDecl *PD = ParmVarDecl::Create(
13181         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13182         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13183     PD->setScopeInfo(0, I);
13184     PD->setImplicit();
13185     // Ensure attributes are propagated onto parameters (this matters for
13186     // format, pass_object_size, ...).
13187     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13188     ParamDecls.push_back(PD);
13189     ProtoLoc.setParam(I, PD);
13190   }
13191 
13192   // Set up the new constructor.
13193   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13194   DerivedCtor->setAccess(BaseCtor->getAccess());
13195   DerivedCtor->setParams(ParamDecls);
13196   Derived->addDecl(DerivedCtor);
13197 
13198   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13199     SetDeclDeleted(DerivedCtor, UsingLoc);
13200 
13201   return DerivedCtor;
13202 }
13203 
13204 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13205   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13206                                Ctor->getInheritedConstructor().getShadowDecl());
13207   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13208                             /*Diagnose*/true);
13209 }
13210 
13211 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13212                                        CXXConstructorDecl *Constructor) {
13213   CXXRecordDecl *ClassDecl = Constructor->getParent();
13214   assert(Constructor->getInheritedConstructor() &&
13215          !Constructor->doesThisDeclarationHaveABody() &&
13216          !Constructor->isDeleted());
13217   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13218     return;
13219 
13220   // Initializations are performed "as if by a defaulted default constructor",
13221   // so enter the appropriate scope.
13222   SynthesizedFunctionScope Scope(*this, Constructor);
13223 
13224   // The exception specification is needed because we are defining the
13225   // function.
13226   ResolveExceptionSpec(CurrentLocation,
13227                        Constructor->getType()->castAs<FunctionProtoType>());
13228   MarkVTableUsed(CurrentLocation, ClassDecl);
13229 
13230   // Add a context note for diagnostics produced after this point.
13231   Scope.addContextNote(CurrentLocation);
13232 
13233   ConstructorUsingShadowDecl *Shadow =
13234       Constructor->getInheritedConstructor().getShadowDecl();
13235   CXXConstructorDecl *InheritedCtor =
13236       Constructor->getInheritedConstructor().getConstructor();
13237 
13238   // [class.inhctor.init]p1:
13239   //   initialization proceeds as if a defaulted default constructor is used to
13240   //   initialize the D object and each base class subobject from which the
13241   //   constructor was inherited
13242 
13243   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13244   CXXRecordDecl *RD = Shadow->getParent();
13245   SourceLocation InitLoc = Shadow->getLocation();
13246 
13247   // Build explicit initializers for all base classes from which the
13248   // constructor was inherited.
13249   SmallVector<CXXCtorInitializer*, 8> Inits;
13250   for (bool VBase : {false, true}) {
13251     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13252       if (B.isVirtual() != VBase)
13253         continue;
13254 
13255       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13256       if (!BaseRD)
13257         continue;
13258 
13259       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13260       if (!BaseCtor.first)
13261         continue;
13262 
13263       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13264       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13265           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13266 
13267       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13268       Inits.push_back(new (Context) CXXCtorInitializer(
13269           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13270           SourceLocation()));
13271     }
13272   }
13273 
13274   // We now proceed as if for a defaulted default constructor, with the relevant
13275   // initializers replaced.
13276 
13277   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13278     Constructor->setInvalidDecl();
13279     return;
13280   }
13281 
13282   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13283   Constructor->markUsed(Context);
13284 
13285   if (ASTMutationListener *L = getASTMutationListener()) {
13286     L->CompletedImplicitDefinition(Constructor);
13287   }
13288 
13289   DiagnoseUninitializedFields(*this, Constructor);
13290 }
13291 
13292 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13293   // C++ [class.dtor]p2:
13294   //   If a class has no user-declared destructor, a destructor is
13295   //   declared implicitly. An implicitly-declared destructor is an
13296   //   inline public member of its class.
13297   assert(ClassDecl->needsImplicitDestructor());
13298 
13299   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13300   if (DSM.isAlreadyBeingDeclared())
13301     return nullptr;
13302 
13303   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13304                                                      CXXDestructor,
13305                                                      false);
13306 
13307   // Create the actual destructor declaration.
13308   CanQualType ClassType
13309     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13310   SourceLocation ClassLoc = ClassDecl->getLocation();
13311   DeclarationName Name
13312     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13313   DeclarationNameInfo NameInfo(Name, ClassLoc);
13314   CXXDestructorDecl *Destructor =
13315       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13316                                 QualType(), nullptr, /*isInline=*/true,
13317                                 /*isImplicitlyDeclared=*/true,
13318                                 Constexpr ? ConstexprSpecKind::Constexpr
13319                                           : ConstexprSpecKind::Unspecified);
13320   Destructor->setAccess(AS_public);
13321   Destructor->setDefaulted();
13322 
13323   if (getLangOpts().CUDA) {
13324     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13325                                             Destructor,
13326                                             /* ConstRHS */ false,
13327                                             /* Diagnose */ false);
13328   }
13329 
13330   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13331 
13332   // We don't need to use SpecialMemberIsTrivial here; triviality for
13333   // destructors is easy to compute.
13334   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13335   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13336                                 ClassDecl->hasTrivialDestructorForCall());
13337 
13338   // Note that we have declared this destructor.
13339   ++getASTContext().NumImplicitDestructorsDeclared;
13340 
13341   Scope *S = getScopeForContext(ClassDecl);
13342   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13343 
13344   // We can't check whether an implicit destructor is deleted before we complete
13345   // the definition of the class, because its validity depends on the alignment
13346   // of the class. We'll check this from ActOnFields once the class is complete.
13347   if (ClassDecl->isCompleteDefinition() &&
13348       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13349     SetDeclDeleted(Destructor, ClassLoc);
13350 
13351   // Introduce this destructor into its scope.
13352   if (S)
13353     PushOnScopeChains(Destructor, S, false);
13354   ClassDecl->addDecl(Destructor);
13355 
13356   return Destructor;
13357 }
13358 
13359 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13360                                     CXXDestructorDecl *Destructor) {
13361   assert((Destructor->isDefaulted() &&
13362           !Destructor->doesThisDeclarationHaveABody() &&
13363           !Destructor->isDeleted()) &&
13364          "DefineImplicitDestructor - call it for implicit default dtor");
13365   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13366     return;
13367 
13368   CXXRecordDecl *ClassDecl = Destructor->getParent();
13369   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13370 
13371   SynthesizedFunctionScope Scope(*this, Destructor);
13372 
13373   // The exception specification is needed because we are defining the
13374   // function.
13375   ResolveExceptionSpec(CurrentLocation,
13376                        Destructor->getType()->castAs<FunctionProtoType>());
13377   MarkVTableUsed(CurrentLocation, ClassDecl);
13378 
13379   // Add a context note for diagnostics produced after this point.
13380   Scope.addContextNote(CurrentLocation);
13381 
13382   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13383                                          Destructor->getParent());
13384 
13385   if (CheckDestructor(Destructor)) {
13386     Destructor->setInvalidDecl();
13387     return;
13388   }
13389 
13390   SourceLocation Loc = Destructor->getEndLoc().isValid()
13391                            ? Destructor->getEndLoc()
13392                            : Destructor->getLocation();
13393   Destructor->setBody(new (Context) CompoundStmt(Loc));
13394   Destructor->markUsed(Context);
13395 
13396   if (ASTMutationListener *L = getASTMutationListener()) {
13397     L->CompletedImplicitDefinition(Destructor);
13398   }
13399 }
13400 
13401 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13402                                           CXXDestructorDecl *Destructor) {
13403   if (Destructor->isInvalidDecl())
13404     return;
13405 
13406   CXXRecordDecl *ClassDecl = Destructor->getParent();
13407   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13408          "implicit complete dtors unneeded outside MS ABI");
13409   assert(ClassDecl->getNumVBases() > 0 &&
13410          "complete dtor only exists for classes with vbases");
13411 
13412   SynthesizedFunctionScope Scope(*this, Destructor);
13413 
13414   // Add a context note for diagnostics produced after this point.
13415   Scope.addContextNote(CurrentLocation);
13416 
13417   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13418 }
13419 
13420 /// Perform any semantic analysis which needs to be delayed until all
13421 /// pending class member declarations have been parsed.
13422 void Sema::ActOnFinishCXXMemberDecls() {
13423   // If the context is an invalid C++ class, just suppress these checks.
13424   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13425     if (Record->isInvalidDecl()) {
13426       DelayedOverridingExceptionSpecChecks.clear();
13427       DelayedEquivalentExceptionSpecChecks.clear();
13428       return;
13429     }
13430     checkForMultipleExportedDefaultConstructors(*this, Record);
13431   }
13432 }
13433 
13434 void Sema::ActOnFinishCXXNonNestedClass() {
13435   referenceDLLExportedClassMethods();
13436 
13437   if (!DelayedDllExportMemberFunctions.empty()) {
13438     SmallVector<CXXMethodDecl*, 4> WorkList;
13439     std::swap(DelayedDllExportMemberFunctions, WorkList);
13440     for (CXXMethodDecl *M : WorkList) {
13441       DefineDefaultedFunction(*this, M, M->getLocation());
13442 
13443       // Pass the method to the consumer to get emitted. This is not necessary
13444       // for explicit instantiation definitions, as they will get emitted
13445       // anyway.
13446       if (M->getParent()->getTemplateSpecializationKind() !=
13447           TSK_ExplicitInstantiationDefinition)
13448         ActOnFinishInlineFunctionDef(M);
13449     }
13450   }
13451 }
13452 
13453 void Sema::referenceDLLExportedClassMethods() {
13454   if (!DelayedDllExportClasses.empty()) {
13455     // Calling ReferenceDllExportedMembers might cause the current function to
13456     // be called again, so use a local copy of DelayedDllExportClasses.
13457     SmallVector<CXXRecordDecl *, 4> WorkList;
13458     std::swap(DelayedDllExportClasses, WorkList);
13459     for (CXXRecordDecl *Class : WorkList)
13460       ReferenceDllExportedMembers(*this, Class);
13461   }
13462 }
13463 
13464 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13465   assert(getLangOpts().CPlusPlus11 &&
13466          "adjusting dtor exception specs was introduced in c++11");
13467 
13468   if (Destructor->isDependentContext())
13469     return;
13470 
13471   // C++11 [class.dtor]p3:
13472   //   A declaration of a destructor that does not have an exception-
13473   //   specification is implicitly considered to have the same exception-
13474   //   specification as an implicit declaration.
13475   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13476   if (DtorType->hasExceptionSpec())
13477     return;
13478 
13479   // Replace the destructor's type, building off the existing one. Fortunately,
13480   // the only thing of interest in the destructor type is its extended info.
13481   // The return and arguments are fixed.
13482   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13483   EPI.ExceptionSpec.Type = EST_Unevaluated;
13484   EPI.ExceptionSpec.SourceDecl = Destructor;
13485   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13486 
13487   // FIXME: If the destructor has a body that could throw, and the newly created
13488   // spec doesn't allow exceptions, we should emit a warning, because this
13489   // change in behavior can break conforming C++03 programs at runtime.
13490   // However, we don't have a body or an exception specification yet, so it
13491   // needs to be done somewhere else.
13492 }
13493 
13494 namespace {
13495 /// An abstract base class for all helper classes used in building the
13496 //  copy/move operators. These classes serve as factory functions and help us
13497 //  avoid using the same Expr* in the AST twice.
13498 class ExprBuilder {
13499   ExprBuilder(const ExprBuilder&) = delete;
13500   ExprBuilder &operator=(const ExprBuilder&) = delete;
13501 
13502 protected:
13503   static Expr *assertNotNull(Expr *E) {
13504     assert(E && "Expression construction must not fail.");
13505     return E;
13506   }
13507 
13508 public:
13509   ExprBuilder() {}
13510   virtual ~ExprBuilder() {}
13511 
13512   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13513 };
13514 
13515 class RefBuilder: public ExprBuilder {
13516   VarDecl *Var;
13517   QualType VarType;
13518 
13519 public:
13520   Expr *build(Sema &S, SourceLocation Loc) const override {
13521     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13522   }
13523 
13524   RefBuilder(VarDecl *Var, QualType VarType)
13525       : Var(Var), VarType(VarType) {}
13526 };
13527 
13528 class ThisBuilder: public ExprBuilder {
13529 public:
13530   Expr *build(Sema &S, SourceLocation Loc) const override {
13531     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13532   }
13533 };
13534 
13535 class CastBuilder: public ExprBuilder {
13536   const ExprBuilder &Builder;
13537   QualType Type;
13538   ExprValueKind Kind;
13539   const CXXCastPath &Path;
13540 
13541 public:
13542   Expr *build(Sema &S, SourceLocation Loc) const override {
13543     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13544                                              CK_UncheckedDerivedToBase, Kind,
13545                                              &Path).get());
13546   }
13547 
13548   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13549               const CXXCastPath &Path)
13550       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13551 };
13552 
13553 class DerefBuilder: public ExprBuilder {
13554   const ExprBuilder &Builder;
13555 
13556 public:
13557   Expr *build(Sema &S, SourceLocation Loc) const override {
13558     return assertNotNull(
13559         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13560   }
13561 
13562   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13563 };
13564 
13565 class MemberBuilder: public ExprBuilder {
13566   const ExprBuilder &Builder;
13567   QualType Type;
13568   CXXScopeSpec SS;
13569   bool IsArrow;
13570   LookupResult &MemberLookup;
13571 
13572 public:
13573   Expr *build(Sema &S, SourceLocation Loc) const override {
13574     return assertNotNull(S.BuildMemberReferenceExpr(
13575         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13576         nullptr, MemberLookup, nullptr, nullptr).get());
13577   }
13578 
13579   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13580                 LookupResult &MemberLookup)
13581       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13582         MemberLookup(MemberLookup) {}
13583 };
13584 
13585 class MoveCastBuilder: public ExprBuilder {
13586   const ExprBuilder &Builder;
13587 
13588 public:
13589   Expr *build(Sema &S, SourceLocation Loc) const override {
13590     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13591   }
13592 
13593   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13594 };
13595 
13596 class LvalueConvBuilder: public ExprBuilder {
13597   const ExprBuilder &Builder;
13598 
13599 public:
13600   Expr *build(Sema &S, SourceLocation Loc) const override {
13601     return assertNotNull(
13602         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13603   }
13604 
13605   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13606 };
13607 
13608 class SubscriptBuilder: public ExprBuilder {
13609   const ExprBuilder &Base;
13610   const ExprBuilder &Index;
13611 
13612 public:
13613   Expr *build(Sema &S, SourceLocation Loc) const override {
13614     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13615         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13616   }
13617 
13618   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13619       : Base(Base), Index(Index) {}
13620 };
13621 
13622 } // end anonymous namespace
13623 
13624 /// When generating a defaulted copy or move assignment operator, if a field
13625 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13626 /// do so. This optimization only applies for arrays of scalars, and for arrays
13627 /// of class type where the selected copy/move-assignment operator is trivial.
13628 static StmtResult
13629 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13630                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13631   // Compute the size of the memory buffer to be copied.
13632   QualType SizeType = S.Context.getSizeType();
13633   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13634                    S.Context.getTypeSizeInChars(T).getQuantity());
13635 
13636   // Take the address of the field references for "from" and "to". We
13637   // directly construct UnaryOperators here because semantic analysis
13638   // does not permit us to take the address of an xvalue.
13639   Expr *From = FromB.build(S, Loc);
13640   From = UnaryOperator::Create(
13641       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13642       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13643   Expr *To = ToB.build(S, Loc);
13644   To = UnaryOperator::Create(
13645       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13646       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13647 
13648   const Type *E = T->getBaseElementTypeUnsafe();
13649   bool NeedsCollectableMemCpy =
13650       E->isRecordType() &&
13651       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13652 
13653   // Create a reference to the __builtin_objc_memmove_collectable function
13654   StringRef MemCpyName = NeedsCollectableMemCpy ?
13655     "__builtin_objc_memmove_collectable" :
13656     "__builtin_memcpy";
13657   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13658                  Sema::LookupOrdinaryName);
13659   S.LookupName(R, S.TUScope, true);
13660 
13661   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13662   if (!MemCpy)
13663     // Something went horribly wrong earlier, and we will have complained
13664     // about it.
13665     return StmtError();
13666 
13667   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13668                                             VK_RValue, Loc, nullptr);
13669   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13670 
13671   Expr *CallArgs[] = {
13672     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13673   };
13674   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13675                                     Loc, CallArgs, Loc);
13676 
13677   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13678   return Call.getAs<Stmt>();
13679 }
13680 
13681 /// Builds a statement that copies/moves the given entity from \p From to
13682 /// \c To.
13683 ///
13684 /// This routine is used to copy/move the members of a class with an
13685 /// implicitly-declared copy/move assignment operator. When the entities being
13686 /// copied are arrays, this routine builds for loops to copy them.
13687 ///
13688 /// \param S The Sema object used for type-checking.
13689 ///
13690 /// \param Loc The location where the implicit copy/move is being generated.
13691 ///
13692 /// \param T The type of the expressions being copied/moved. Both expressions
13693 /// must have this type.
13694 ///
13695 /// \param To The expression we are copying/moving to.
13696 ///
13697 /// \param From The expression we are copying/moving from.
13698 ///
13699 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13700 /// Otherwise, it's a non-static member subobject.
13701 ///
13702 /// \param Copying Whether we're copying or moving.
13703 ///
13704 /// \param Depth Internal parameter recording the depth of the recursion.
13705 ///
13706 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13707 /// if a memcpy should be used instead.
13708 static StmtResult
13709 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13710                                  const ExprBuilder &To, const ExprBuilder &From,
13711                                  bool CopyingBaseSubobject, bool Copying,
13712                                  unsigned Depth = 0) {
13713   // C++11 [class.copy]p28:
13714   //   Each subobject is assigned in the manner appropriate to its type:
13715   //
13716   //     - if the subobject is of class type, as if by a call to operator= with
13717   //       the subobject as the object expression and the corresponding
13718   //       subobject of x as a single function argument (as if by explicit
13719   //       qualification; that is, ignoring any possible virtual overriding
13720   //       functions in more derived classes);
13721   //
13722   // C++03 [class.copy]p13:
13723   //     - if the subobject is of class type, the copy assignment operator for
13724   //       the class is used (as if by explicit qualification; that is,
13725   //       ignoring any possible virtual overriding functions in more derived
13726   //       classes);
13727   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13728     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13729 
13730     // Look for operator=.
13731     DeclarationName Name
13732       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13733     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13734     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13735 
13736     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13737     // operator.
13738     if (!S.getLangOpts().CPlusPlus11) {
13739       LookupResult::Filter F = OpLookup.makeFilter();
13740       while (F.hasNext()) {
13741         NamedDecl *D = F.next();
13742         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13743           if (Method->isCopyAssignmentOperator() ||
13744               (!Copying && Method->isMoveAssignmentOperator()))
13745             continue;
13746 
13747         F.erase();
13748       }
13749       F.done();
13750     }
13751 
13752     // Suppress the protected check (C++ [class.protected]) for each of the
13753     // assignment operators we found. This strange dance is required when
13754     // we're assigning via a base classes's copy-assignment operator. To
13755     // ensure that we're getting the right base class subobject (without
13756     // ambiguities), we need to cast "this" to that subobject type; to
13757     // ensure that we don't go through the virtual call mechanism, we need
13758     // to qualify the operator= name with the base class (see below). However,
13759     // this means that if the base class has a protected copy assignment
13760     // operator, the protected member access check will fail. So, we
13761     // rewrite "protected" access to "public" access in this case, since we
13762     // know by construction that we're calling from a derived class.
13763     if (CopyingBaseSubobject) {
13764       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13765            L != LEnd; ++L) {
13766         if (L.getAccess() == AS_protected)
13767           L.setAccess(AS_public);
13768       }
13769     }
13770 
13771     // Create the nested-name-specifier that will be used to qualify the
13772     // reference to operator=; this is required to suppress the virtual
13773     // call mechanism.
13774     CXXScopeSpec SS;
13775     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13776     SS.MakeTrivial(S.Context,
13777                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13778                                                CanonicalT),
13779                    Loc);
13780 
13781     // Create the reference to operator=.
13782     ExprResult OpEqualRef
13783       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13784                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13785                                    /*FirstQualifierInScope=*/nullptr,
13786                                    OpLookup,
13787                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13788                                    /*SuppressQualifierCheck=*/true);
13789     if (OpEqualRef.isInvalid())
13790       return StmtError();
13791 
13792     // Build the call to the assignment operator.
13793 
13794     Expr *FromInst = From.build(S, Loc);
13795     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13796                                                   OpEqualRef.getAs<Expr>(),
13797                                                   Loc, FromInst, Loc);
13798     if (Call.isInvalid())
13799       return StmtError();
13800 
13801     // If we built a call to a trivial 'operator=' while copying an array,
13802     // bail out. We'll replace the whole shebang with a memcpy.
13803     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13804     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13805       return StmtResult((Stmt*)nullptr);
13806 
13807     // Convert to an expression-statement, and clean up any produced
13808     // temporaries.
13809     return S.ActOnExprStmt(Call);
13810   }
13811 
13812   //     - if the subobject is of scalar type, the built-in assignment
13813   //       operator is used.
13814   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13815   if (!ArrayTy) {
13816     ExprResult Assignment = S.CreateBuiltinBinOp(
13817         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13818     if (Assignment.isInvalid())
13819       return StmtError();
13820     return S.ActOnExprStmt(Assignment);
13821   }
13822 
13823   //     - if the subobject is an array, each element is assigned, in the
13824   //       manner appropriate to the element type;
13825 
13826   // Construct a loop over the array bounds, e.g.,
13827   //
13828   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13829   //
13830   // that will copy each of the array elements.
13831   QualType SizeType = S.Context.getSizeType();
13832 
13833   // Create the iteration variable.
13834   IdentifierInfo *IterationVarName = nullptr;
13835   {
13836     SmallString<8> Str;
13837     llvm::raw_svector_ostream OS(Str);
13838     OS << "__i" << Depth;
13839     IterationVarName = &S.Context.Idents.get(OS.str());
13840   }
13841   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13842                                           IterationVarName, SizeType,
13843                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13844                                           SC_None);
13845 
13846   // Initialize the iteration variable to zero.
13847   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13848   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13849 
13850   // Creates a reference to the iteration variable.
13851   RefBuilder IterationVarRef(IterationVar, SizeType);
13852   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13853 
13854   // Create the DeclStmt that holds the iteration variable.
13855   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13856 
13857   // Subscript the "from" and "to" expressions with the iteration variable.
13858   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13859   MoveCastBuilder FromIndexMove(FromIndexCopy);
13860   const ExprBuilder *FromIndex;
13861   if (Copying)
13862     FromIndex = &FromIndexCopy;
13863   else
13864     FromIndex = &FromIndexMove;
13865 
13866   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13867 
13868   // Build the copy/move for an individual element of the array.
13869   StmtResult Copy =
13870     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13871                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13872                                      Copying, Depth + 1);
13873   // Bail out if copying fails or if we determined that we should use memcpy.
13874   if (Copy.isInvalid() || !Copy.get())
13875     return Copy;
13876 
13877   // Create the comparison against the array bound.
13878   llvm::APInt Upper
13879     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13880   Expr *Comparison = BinaryOperator::Create(
13881       S.Context, IterationVarRefRVal.build(S, Loc),
13882       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13883       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13884 
13885   // Create the pre-increment of the iteration variable. We can determine
13886   // whether the increment will overflow based on the value of the array
13887   // bound.
13888   Expr *Increment = UnaryOperator::Create(
13889       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13890       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13891 
13892   // Construct the loop that copies all elements of this array.
13893   return S.ActOnForStmt(
13894       Loc, Loc, InitStmt,
13895       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13896       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13897 }
13898 
13899 static StmtResult
13900 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13901                       const ExprBuilder &To, const ExprBuilder &From,
13902                       bool CopyingBaseSubobject, bool Copying) {
13903   // Maybe we should use a memcpy?
13904   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13905       T.isTriviallyCopyableType(S.Context))
13906     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13907 
13908   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13909                                                      CopyingBaseSubobject,
13910                                                      Copying, 0));
13911 
13912   // If we ended up picking a trivial assignment operator for an array of a
13913   // non-trivially-copyable class type, just emit a memcpy.
13914   if (!Result.isInvalid() && !Result.get())
13915     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13916 
13917   return Result;
13918 }
13919 
13920 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13921   // Note: The following rules are largely analoguous to the copy
13922   // constructor rules. Note that virtual bases are not taken into account
13923   // for determining the argument type of the operator. Note also that
13924   // operators taking an object instead of a reference are allowed.
13925   assert(ClassDecl->needsImplicitCopyAssignment());
13926 
13927   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13928   if (DSM.isAlreadyBeingDeclared())
13929     return nullptr;
13930 
13931   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13932   LangAS AS = getDefaultCXXMethodAddrSpace();
13933   if (AS != LangAS::Default)
13934     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13935   QualType RetType = Context.getLValueReferenceType(ArgType);
13936   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13937   if (Const)
13938     ArgType = ArgType.withConst();
13939 
13940   ArgType = Context.getLValueReferenceType(ArgType);
13941 
13942   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13943                                                      CXXCopyAssignment,
13944                                                      Const);
13945 
13946   //   An implicitly-declared copy assignment operator is an inline public
13947   //   member of its class.
13948   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13949   SourceLocation ClassLoc = ClassDecl->getLocation();
13950   DeclarationNameInfo NameInfo(Name, ClassLoc);
13951   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13952       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13953       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13954       /*isInline=*/true,
13955       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
13956       SourceLocation());
13957   CopyAssignment->setAccess(AS_public);
13958   CopyAssignment->setDefaulted();
13959   CopyAssignment->setImplicit();
13960 
13961   if (getLangOpts().CUDA) {
13962     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13963                                             CopyAssignment,
13964                                             /* ConstRHS */ Const,
13965                                             /* Diagnose */ false);
13966   }
13967 
13968   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13969 
13970   // Add the parameter to the operator.
13971   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13972                                                ClassLoc, ClassLoc,
13973                                                /*Id=*/nullptr, ArgType,
13974                                                /*TInfo=*/nullptr, SC_None,
13975                                                nullptr);
13976   CopyAssignment->setParams(FromParam);
13977 
13978   CopyAssignment->setTrivial(
13979     ClassDecl->needsOverloadResolutionForCopyAssignment()
13980       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13981       : ClassDecl->hasTrivialCopyAssignment());
13982 
13983   // Note that we have added this copy-assignment operator.
13984   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13985 
13986   Scope *S = getScopeForContext(ClassDecl);
13987   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13988 
13989   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13990     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13991     SetDeclDeleted(CopyAssignment, ClassLoc);
13992   }
13993 
13994   if (S)
13995     PushOnScopeChains(CopyAssignment, S, false);
13996   ClassDecl->addDecl(CopyAssignment);
13997 
13998   return CopyAssignment;
13999 }
14000 
14001 /// Diagnose an implicit copy operation for a class which is odr-used, but
14002 /// which is deprecated because the class has a user-declared copy constructor,
14003 /// copy assignment operator, or destructor.
14004 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14005   assert(CopyOp->isImplicit());
14006 
14007   CXXRecordDecl *RD = CopyOp->getParent();
14008   CXXMethodDecl *UserDeclaredOperation = nullptr;
14009 
14010   // In Microsoft mode, assignment operations don't affect constructors and
14011   // vice versa.
14012   if (RD->hasUserDeclaredDestructor()) {
14013     UserDeclaredOperation = RD->getDestructor();
14014   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14015              RD->hasUserDeclaredCopyConstructor() &&
14016              !S.getLangOpts().MSVCCompat) {
14017     // Find any user-declared copy constructor.
14018     for (auto *I : RD->ctors()) {
14019       if (I->isCopyConstructor()) {
14020         UserDeclaredOperation = I;
14021         break;
14022       }
14023     }
14024     assert(UserDeclaredOperation);
14025   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14026              RD->hasUserDeclaredCopyAssignment() &&
14027              !S.getLangOpts().MSVCCompat) {
14028     // Find any user-declared move assignment operator.
14029     for (auto *I : RD->methods()) {
14030       if (I->isCopyAssignmentOperator()) {
14031         UserDeclaredOperation = I;
14032         break;
14033       }
14034     }
14035     assert(UserDeclaredOperation);
14036   }
14037 
14038   if (UserDeclaredOperation) {
14039     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14040     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14041     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14042     unsigned DiagID =
14043         (UDOIsUserProvided && UDOIsDestructor)
14044             ? diag::warn_deprecated_copy_with_user_provided_dtor
14045         : (UDOIsUserProvided && !UDOIsDestructor)
14046             ? diag::warn_deprecated_copy_with_user_provided_copy
14047         : (!UDOIsUserProvided && UDOIsDestructor)
14048             ? diag::warn_deprecated_copy_with_dtor
14049             : diag::warn_deprecated_copy;
14050     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14051         << RD << IsCopyAssignment;
14052   }
14053 }
14054 
14055 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14056                                         CXXMethodDecl *CopyAssignOperator) {
14057   assert((CopyAssignOperator->isDefaulted() &&
14058           CopyAssignOperator->isOverloadedOperator() &&
14059           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14060           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14061           !CopyAssignOperator->isDeleted()) &&
14062          "DefineImplicitCopyAssignment called for wrong function");
14063   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14064     return;
14065 
14066   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14067   if (ClassDecl->isInvalidDecl()) {
14068     CopyAssignOperator->setInvalidDecl();
14069     return;
14070   }
14071 
14072   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14073 
14074   // The exception specification is needed because we are defining the
14075   // function.
14076   ResolveExceptionSpec(CurrentLocation,
14077                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14078 
14079   // Add a context note for diagnostics produced after this point.
14080   Scope.addContextNote(CurrentLocation);
14081 
14082   // C++11 [class.copy]p18:
14083   //   The [definition of an implicitly declared copy assignment operator] is
14084   //   deprecated if the class has a user-declared copy constructor or a
14085   //   user-declared destructor.
14086   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14087     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14088 
14089   // C++0x [class.copy]p30:
14090   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14091   //   for a non-union class X performs memberwise copy assignment of its
14092   //   subobjects. The direct base classes of X are assigned first, in the
14093   //   order of their declaration in the base-specifier-list, and then the
14094   //   immediate non-static data members of X are assigned, in the order in
14095   //   which they were declared in the class definition.
14096 
14097   // The statements that form the synthesized function body.
14098   SmallVector<Stmt*, 8> Statements;
14099 
14100   // The parameter for the "other" object, which we are copying from.
14101   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14102   Qualifiers OtherQuals = Other->getType().getQualifiers();
14103   QualType OtherRefType = Other->getType();
14104   if (const LValueReferenceType *OtherRef
14105                                 = OtherRefType->getAs<LValueReferenceType>()) {
14106     OtherRefType = OtherRef->getPointeeType();
14107     OtherQuals = OtherRefType.getQualifiers();
14108   }
14109 
14110   // Our location for everything implicitly-generated.
14111   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14112                            ? CopyAssignOperator->getEndLoc()
14113                            : CopyAssignOperator->getLocation();
14114 
14115   // Builds a DeclRefExpr for the "other" object.
14116   RefBuilder OtherRef(Other, OtherRefType);
14117 
14118   // Builds the "this" pointer.
14119   ThisBuilder This;
14120 
14121   // Assign base classes.
14122   bool Invalid = false;
14123   for (auto &Base : ClassDecl->bases()) {
14124     // Form the assignment:
14125     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14126     QualType BaseType = Base.getType().getUnqualifiedType();
14127     if (!BaseType->isRecordType()) {
14128       Invalid = true;
14129       continue;
14130     }
14131 
14132     CXXCastPath BasePath;
14133     BasePath.push_back(&Base);
14134 
14135     // Construct the "from" expression, which is an implicit cast to the
14136     // appropriately-qualified base type.
14137     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14138                      VK_LValue, BasePath);
14139 
14140     // Dereference "this".
14141     DerefBuilder DerefThis(This);
14142     CastBuilder To(DerefThis,
14143                    Context.getQualifiedType(
14144                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14145                    VK_LValue, BasePath);
14146 
14147     // Build the copy.
14148     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14149                                             To, From,
14150                                             /*CopyingBaseSubobject=*/true,
14151                                             /*Copying=*/true);
14152     if (Copy.isInvalid()) {
14153       CopyAssignOperator->setInvalidDecl();
14154       return;
14155     }
14156 
14157     // Success! Record the copy.
14158     Statements.push_back(Copy.getAs<Expr>());
14159   }
14160 
14161   // Assign non-static members.
14162   for (auto *Field : ClassDecl->fields()) {
14163     // FIXME: We should form some kind of AST representation for the implied
14164     // memcpy in a union copy operation.
14165     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14166       continue;
14167 
14168     if (Field->isInvalidDecl()) {
14169       Invalid = true;
14170       continue;
14171     }
14172 
14173     // Check for members of reference type; we can't copy those.
14174     if (Field->getType()->isReferenceType()) {
14175       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14176         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14177       Diag(Field->getLocation(), diag::note_declared_at);
14178       Invalid = true;
14179       continue;
14180     }
14181 
14182     // Check for members of const-qualified, non-class type.
14183     QualType BaseType = Context.getBaseElementType(Field->getType());
14184     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14185       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14186         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14187       Diag(Field->getLocation(), diag::note_declared_at);
14188       Invalid = true;
14189       continue;
14190     }
14191 
14192     // Suppress assigning zero-width bitfields.
14193     if (Field->isZeroLengthBitField(Context))
14194       continue;
14195 
14196     QualType FieldType = Field->getType().getNonReferenceType();
14197     if (FieldType->isIncompleteArrayType()) {
14198       assert(ClassDecl->hasFlexibleArrayMember() &&
14199              "Incomplete array type is not valid");
14200       continue;
14201     }
14202 
14203     // Build references to the field in the object we're copying from and to.
14204     CXXScopeSpec SS; // Intentionally empty
14205     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14206                               LookupMemberName);
14207     MemberLookup.addDecl(Field);
14208     MemberLookup.resolveKind();
14209 
14210     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14211 
14212     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14213 
14214     // Build the copy of this field.
14215     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14216                                             To, From,
14217                                             /*CopyingBaseSubobject=*/false,
14218                                             /*Copying=*/true);
14219     if (Copy.isInvalid()) {
14220       CopyAssignOperator->setInvalidDecl();
14221       return;
14222     }
14223 
14224     // Success! Record the copy.
14225     Statements.push_back(Copy.getAs<Stmt>());
14226   }
14227 
14228   if (!Invalid) {
14229     // Add a "return *this;"
14230     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14231 
14232     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14233     if (Return.isInvalid())
14234       Invalid = true;
14235     else
14236       Statements.push_back(Return.getAs<Stmt>());
14237   }
14238 
14239   if (Invalid) {
14240     CopyAssignOperator->setInvalidDecl();
14241     return;
14242   }
14243 
14244   StmtResult Body;
14245   {
14246     CompoundScopeRAII CompoundScope(*this);
14247     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14248                              /*isStmtExpr=*/false);
14249     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14250   }
14251   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14252   CopyAssignOperator->markUsed(Context);
14253 
14254   if (ASTMutationListener *L = getASTMutationListener()) {
14255     L->CompletedImplicitDefinition(CopyAssignOperator);
14256   }
14257 }
14258 
14259 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14260   assert(ClassDecl->needsImplicitMoveAssignment());
14261 
14262   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14263   if (DSM.isAlreadyBeingDeclared())
14264     return nullptr;
14265 
14266   // Note: The following rules are largely analoguous to the move
14267   // constructor rules.
14268 
14269   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14270   LangAS AS = getDefaultCXXMethodAddrSpace();
14271   if (AS != LangAS::Default)
14272     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14273   QualType RetType = Context.getLValueReferenceType(ArgType);
14274   ArgType = Context.getRValueReferenceType(ArgType);
14275 
14276   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14277                                                      CXXMoveAssignment,
14278                                                      false);
14279 
14280   //   An implicitly-declared move assignment operator is an inline public
14281   //   member of its class.
14282   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14283   SourceLocation ClassLoc = ClassDecl->getLocation();
14284   DeclarationNameInfo NameInfo(Name, ClassLoc);
14285   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14286       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14287       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14288       /*isInline=*/true,
14289       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14290       SourceLocation());
14291   MoveAssignment->setAccess(AS_public);
14292   MoveAssignment->setDefaulted();
14293   MoveAssignment->setImplicit();
14294 
14295   if (getLangOpts().CUDA) {
14296     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14297                                             MoveAssignment,
14298                                             /* ConstRHS */ false,
14299                                             /* Diagnose */ false);
14300   }
14301 
14302   // Build an exception specification pointing back at this member.
14303   FunctionProtoType::ExtProtoInfo EPI =
14304       getImplicitMethodEPI(*this, MoveAssignment);
14305   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14306 
14307   // Add the parameter to the operator.
14308   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14309                                                ClassLoc, ClassLoc,
14310                                                /*Id=*/nullptr, ArgType,
14311                                                /*TInfo=*/nullptr, SC_None,
14312                                                nullptr);
14313   MoveAssignment->setParams(FromParam);
14314 
14315   MoveAssignment->setTrivial(
14316     ClassDecl->needsOverloadResolutionForMoveAssignment()
14317       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14318       : ClassDecl->hasTrivialMoveAssignment());
14319 
14320   // Note that we have added this copy-assignment operator.
14321   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14322 
14323   Scope *S = getScopeForContext(ClassDecl);
14324   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14325 
14326   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14327     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14328     SetDeclDeleted(MoveAssignment, ClassLoc);
14329   }
14330 
14331   if (S)
14332     PushOnScopeChains(MoveAssignment, S, false);
14333   ClassDecl->addDecl(MoveAssignment);
14334 
14335   return MoveAssignment;
14336 }
14337 
14338 /// Check if we're implicitly defining a move assignment operator for a class
14339 /// with virtual bases. Such a move assignment might move-assign the virtual
14340 /// base multiple times.
14341 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14342                                                SourceLocation CurrentLocation) {
14343   assert(!Class->isDependentContext() && "should not define dependent move");
14344 
14345   // Only a virtual base could get implicitly move-assigned multiple times.
14346   // Only a non-trivial move assignment can observe this. We only want to
14347   // diagnose if we implicitly define an assignment operator that assigns
14348   // two base classes, both of which move-assign the same virtual base.
14349   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14350       Class->getNumBases() < 2)
14351     return;
14352 
14353   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14354   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14355   VBaseMap VBases;
14356 
14357   for (auto &BI : Class->bases()) {
14358     Worklist.push_back(&BI);
14359     while (!Worklist.empty()) {
14360       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14361       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14362 
14363       // If the base has no non-trivial move assignment operators,
14364       // we don't care about moves from it.
14365       if (!Base->hasNonTrivialMoveAssignment())
14366         continue;
14367 
14368       // If there's nothing virtual here, skip it.
14369       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14370         continue;
14371 
14372       // If we're not actually going to call a move assignment for this base,
14373       // or the selected move assignment is trivial, skip it.
14374       Sema::SpecialMemberOverloadResult SMOR =
14375         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14376                               /*ConstArg*/false, /*VolatileArg*/false,
14377                               /*RValueThis*/true, /*ConstThis*/false,
14378                               /*VolatileThis*/false);
14379       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14380           !SMOR.getMethod()->isMoveAssignmentOperator())
14381         continue;
14382 
14383       if (BaseSpec->isVirtual()) {
14384         // We're going to move-assign this virtual base, and its move
14385         // assignment operator is not trivial. If this can happen for
14386         // multiple distinct direct bases of Class, diagnose it. (If it
14387         // only happens in one base, we'll diagnose it when synthesizing
14388         // that base class's move assignment operator.)
14389         CXXBaseSpecifier *&Existing =
14390             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14391                 .first->second;
14392         if (Existing && Existing != &BI) {
14393           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14394             << Class << Base;
14395           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14396               << (Base->getCanonicalDecl() ==
14397                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14398               << Base << Existing->getType() << Existing->getSourceRange();
14399           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14400               << (Base->getCanonicalDecl() ==
14401                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14402               << Base << BI.getType() << BaseSpec->getSourceRange();
14403 
14404           // Only diagnose each vbase once.
14405           Existing = nullptr;
14406         }
14407       } else {
14408         // Only walk over bases that have defaulted move assignment operators.
14409         // We assume that any user-provided move assignment operator handles
14410         // the multiple-moves-of-vbase case itself somehow.
14411         if (!SMOR.getMethod()->isDefaulted())
14412           continue;
14413 
14414         // We're going to move the base classes of Base. Add them to the list.
14415         for (auto &BI : Base->bases())
14416           Worklist.push_back(&BI);
14417       }
14418     }
14419   }
14420 }
14421 
14422 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14423                                         CXXMethodDecl *MoveAssignOperator) {
14424   assert((MoveAssignOperator->isDefaulted() &&
14425           MoveAssignOperator->isOverloadedOperator() &&
14426           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14427           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14428           !MoveAssignOperator->isDeleted()) &&
14429          "DefineImplicitMoveAssignment called for wrong function");
14430   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14431     return;
14432 
14433   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14434   if (ClassDecl->isInvalidDecl()) {
14435     MoveAssignOperator->setInvalidDecl();
14436     return;
14437   }
14438 
14439   // C++0x [class.copy]p28:
14440   //   The implicitly-defined or move assignment operator for a non-union class
14441   //   X performs memberwise move assignment of its subobjects. The direct base
14442   //   classes of X are assigned first, in the order of their declaration in the
14443   //   base-specifier-list, and then the immediate non-static data members of X
14444   //   are assigned, in the order in which they were declared in the class
14445   //   definition.
14446 
14447   // Issue a warning if our implicit move assignment operator will move
14448   // from a virtual base more than once.
14449   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14450 
14451   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14452 
14453   // The exception specification is needed because we are defining the
14454   // function.
14455   ResolveExceptionSpec(CurrentLocation,
14456                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14457 
14458   // Add a context note for diagnostics produced after this point.
14459   Scope.addContextNote(CurrentLocation);
14460 
14461   // The statements that form the synthesized function body.
14462   SmallVector<Stmt*, 8> Statements;
14463 
14464   // The parameter for the "other" object, which we are move from.
14465   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14466   QualType OtherRefType =
14467       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14468 
14469   // Our location for everything implicitly-generated.
14470   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14471                            ? MoveAssignOperator->getEndLoc()
14472                            : MoveAssignOperator->getLocation();
14473 
14474   // Builds a reference to the "other" object.
14475   RefBuilder OtherRef(Other, OtherRefType);
14476   // Cast to rvalue.
14477   MoveCastBuilder MoveOther(OtherRef);
14478 
14479   // Builds the "this" pointer.
14480   ThisBuilder This;
14481 
14482   // Assign base classes.
14483   bool Invalid = false;
14484   for (auto &Base : ClassDecl->bases()) {
14485     // C++11 [class.copy]p28:
14486     //   It is unspecified whether subobjects representing virtual base classes
14487     //   are assigned more than once by the implicitly-defined copy assignment
14488     //   operator.
14489     // FIXME: Do not assign to a vbase that will be assigned by some other base
14490     // class. For a move-assignment, this can result in the vbase being moved
14491     // multiple times.
14492 
14493     // Form the assignment:
14494     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14495     QualType BaseType = Base.getType().getUnqualifiedType();
14496     if (!BaseType->isRecordType()) {
14497       Invalid = true;
14498       continue;
14499     }
14500 
14501     CXXCastPath BasePath;
14502     BasePath.push_back(&Base);
14503 
14504     // Construct the "from" expression, which is an implicit cast to the
14505     // appropriately-qualified base type.
14506     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14507 
14508     // Dereference "this".
14509     DerefBuilder DerefThis(This);
14510 
14511     // Implicitly cast "this" to the appropriately-qualified base type.
14512     CastBuilder To(DerefThis,
14513                    Context.getQualifiedType(
14514                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14515                    VK_LValue, BasePath);
14516 
14517     // Build the move.
14518     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14519                                             To, From,
14520                                             /*CopyingBaseSubobject=*/true,
14521                                             /*Copying=*/false);
14522     if (Move.isInvalid()) {
14523       MoveAssignOperator->setInvalidDecl();
14524       return;
14525     }
14526 
14527     // Success! Record the move.
14528     Statements.push_back(Move.getAs<Expr>());
14529   }
14530 
14531   // Assign non-static members.
14532   for (auto *Field : ClassDecl->fields()) {
14533     // FIXME: We should form some kind of AST representation for the implied
14534     // memcpy in a union copy operation.
14535     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14536       continue;
14537 
14538     if (Field->isInvalidDecl()) {
14539       Invalid = true;
14540       continue;
14541     }
14542 
14543     // Check for members of reference type; we can't move those.
14544     if (Field->getType()->isReferenceType()) {
14545       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14546         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14547       Diag(Field->getLocation(), diag::note_declared_at);
14548       Invalid = true;
14549       continue;
14550     }
14551 
14552     // Check for members of const-qualified, non-class type.
14553     QualType BaseType = Context.getBaseElementType(Field->getType());
14554     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14555       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14556         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14557       Diag(Field->getLocation(), diag::note_declared_at);
14558       Invalid = true;
14559       continue;
14560     }
14561 
14562     // Suppress assigning zero-width bitfields.
14563     if (Field->isZeroLengthBitField(Context))
14564       continue;
14565 
14566     QualType FieldType = Field->getType().getNonReferenceType();
14567     if (FieldType->isIncompleteArrayType()) {
14568       assert(ClassDecl->hasFlexibleArrayMember() &&
14569              "Incomplete array type is not valid");
14570       continue;
14571     }
14572 
14573     // Build references to the field in the object we're copying from and to.
14574     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14575                               LookupMemberName);
14576     MemberLookup.addDecl(Field);
14577     MemberLookup.resolveKind();
14578     MemberBuilder From(MoveOther, OtherRefType,
14579                        /*IsArrow=*/false, MemberLookup);
14580     MemberBuilder To(This, getCurrentThisType(),
14581                      /*IsArrow=*/true, MemberLookup);
14582 
14583     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14584         "Member reference with rvalue base must be rvalue except for reference "
14585         "members, which aren't allowed for move assignment.");
14586 
14587     // Build the move of this field.
14588     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14589                                             To, From,
14590                                             /*CopyingBaseSubobject=*/false,
14591                                             /*Copying=*/false);
14592     if (Move.isInvalid()) {
14593       MoveAssignOperator->setInvalidDecl();
14594       return;
14595     }
14596 
14597     // Success! Record the copy.
14598     Statements.push_back(Move.getAs<Stmt>());
14599   }
14600 
14601   if (!Invalid) {
14602     // Add a "return *this;"
14603     ExprResult ThisObj =
14604         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14605 
14606     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14607     if (Return.isInvalid())
14608       Invalid = true;
14609     else
14610       Statements.push_back(Return.getAs<Stmt>());
14611   }
14612 
14613   if (Invalid) {
14614     MoveAssignOperator->setInvalidDecl();
14615     return;
14616   }
14617 
14618   StmtResult Body;
14619   {
14620     CompoundScopeRAII CompoundScope(*this);
14621     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14622                              /*isStmtExpr=*/false);
14623     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14624   }
14625   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14626   MoveAssignOperator->markUsed(Context);
14627 
14628   if (ASTMutationListener *L = getASTMutationListener()) {
14629     L->CompletedImplicitDefinition(MoveAssignOperator);
14630   }
14631 }
14632 
14633 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14634                                                     CXXRecordDecl *ClassDecl) {
14635   // C++ [class.copy]p4:
14636   //   If the class definition does not explicitly declare a copy
14637   //   constructor, one is declared implicitly.
14638   assert(ClassDecl->needsImplicitCopyConstructor());
14639 
14640   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14641   if (DSM.isAlreadyBeingDeclared())
14642     return nullptr;
14643 
14644   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14645   QualType ArgType = ClassType;
14646   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14647   if (Const)
14648     ArgType = ArgType.withConst();
14649 
14650   LangAS AS = getDefaultCXXMethodAddrSpace();
14651   if (AS != LangAS::Default)
14652     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14653 
14654   ArgType = Context.getLValueReferenceType(ArgType);
14655 
14656   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14657                                                      CXXCopyConstructor,
14658                                                      Const);
14659 
14660   DeclarationName Name
14661     = Context.DeclarationNames.getCXXConstructorName(
14662                                            Context.getCanonicalType(ClassType));
14663   SourceLocation ClassLoc = ClassDecl->getLocation();
14664   DeclarationNameInfo NameInfo(Name, ClassLoc);
14665 
14666   //   An implicitly-declared copy constructor is an inline public
14667   //   member of its class.
14668   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14669       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14670       ExplicitSpecifier(),
14671       /*isInline=*/true,
14672       /*isImplicitlyDeclared=*/true,
14673       Constexpr ? ConstexprSpecKind::Constexpr
14674                 : ConstexprSpecKind::Unspecified);
14675   CopyConstructor->setAccess(AS_public);
14676   CopyConstructor->setDefaulted();
14677 
14678   if (getLangOpts().CUDA) {
14679     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14680                                             CopyConstructor,
14681                                             /* ConstRHS */ Const,
14682                                             /* Diagnose */ false);
14683   }
14684 
14685   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14686 
14687   // Add the parameter to the constructor.
14688   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14689                                                ClassLoc, ClassLoc,
14690                                                /*IdentifierInfo=*/nullptr,
14691                                                ArgType, /*TInfo=*/nullptr,
14692                                                SC_None, nullptr);
14693   CopyConstructor->setParams(FromParam);
14694 
14695   CopyConstructor->setTrivial(
14696       ClassDecl->needsOverloadResolutionForCopyConstructor()
14697           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14698           : ClassDecl->hasTrivialCopyConstructor());
14699 
14700   CopyConstructor->setTrivialForCall(
14701       ClassDecl->hasAttr<TrivialABIAttr>() ||
14702       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14703            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14704              TAH_ConsiderTrivialABI)
14705            : ClassDecl->hasTrivialCopyConstructorForCall()));
14706 
14707   // Note that we have declared this constructor.
14708   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14709 
14710   Scope *S = getScopeForContext(ClassDecl);
14711   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14712 
14713   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14714     ClassDecl->setImplicitCopyConstructorIsDeleted();
14715     SetDeclDeleted(CopyConstructor, ClassLoc);
14716   }
14717 
14718   if (S)
14719     PushOnScopeChains(CopyConstructor, S, false);
14720   ClassDecl->addDecl(CopyConstructor);
14721 
14722   return CopyConstructor;
14723 }
14724 
14725 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14726                                          CXXConstructorDecl *CopyConstructor) {
14727   assert((CopyConstructor->isDefaulted() &&
14728           CopyConstructor->isCopyConstructor() &&
14729           !CopyConstructor->doesThisDeclarationHaveABody() &&
14730           !CopyConstructor->isDeleted()) &&
14731          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14732   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14733     return;
14734 
14735   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14736   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14737 
14738   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14739 
14740   // The exception specification is needed because we are defining the
14741   // function.
14742   ResolveExceptionSpec(CurrentLocation,
14743                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14744   MarkVTableUsed(CurrentLocation, ClassDecl);
14745 
14746   // Add a context note for diagnostics produced after this point.
14747   Scope.addContextNote(CurrentLocation);
14748 
14749   // C++11 [class.copy]p7:
14750   //   The [definition of an implicitly declared copy constructor] is
14751   //   deprecated if the class has a user-declared copy assignment operator
14752   //   or a user-declared destructor.
14753   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14754     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14755 
14756   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14757     CopyConstructor->setInvalidDecl();
14758   }  else {
14759     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14760                              ? CopyConstructor->getEndLoc()
14761                              : CopyConstructor->getLocation();
14762     Sema::CompoundScopeRAII CompoundScope(*this);
14763     CopyConstructor->setBody(
14764         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14765     CopyConstructor->markUsed(Context);
14766   }
14767 
14768   if (ASTMutationListener *L = getASTMutationListener()) {
14769     L->CompletedImplicitDefinition(CopyConstructor);
14770   }
14771 }
14772 
14773 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14774                                                     CXXRecordDecl *ClassDecl) {
14775   assert(ClassDecl->needsImplicitMoveConstructor());
14776 
14777   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14778   if (DSM.isAlreadyBeingDeclared())
14779     return nullptr;
14780 
14781   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14782 
14783   QualType ArgType = ClassType;
14784   LangAS AS = getDefaultCXXMethodAddrSpace();
14785   if (AS != LangAS::Default)
14786     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14787   ArgType = Context.getRValueReferenceType(ArgType);
14788 
14789   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14790                                                      CXXMoveConstructor,
14791                                                      false);
14792 
14793   DeclarationName Name
14794     = Context.DeclarationNames.getCXXConstructorName(
14795                                            Context.getCanonicalType(ClassType));
14796   SourceLocation ClassLoc = ClassDecl->getLocation();
14797   DeclarationNameInfo NameInfo(Name, ClassLoc);
14798 
14799   // C++11 [class.copy]p11:
14800   //   An implicitly-declared copy/move constructor is an inline public
14801   //   member of its class.
14802   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14803       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14804       ExplicitSpecifier(),
14805       /*isInline=*/true,
14806       /*isImplicitlyDeclared=*/true,
14807       Constexpr ? ConstexprSpecKind::Constexpr
14808                 : ConstexprSpecKind::Unspecified);
14809   MoveConstructor->setAccess(AS_public);
14810   MoveConstructor->setDefaulted();
14811 
14812   if (getLangOpts().CUDA) {
14813     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14814                                             MoveConstructor,
14815                                             /* ConstRHS */ false,
14816                                             /* Diagnose */ false);
14817   }
14818 
14819   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14820 
14821   // Add the parameter to the constructor.
14822   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14823                                                ClassLoc, ClassLoc,
14824                                                /*IdentifierInfo=*/nullptr,
14825                                                ArgType, /*TInfo=*/nullptr,
14826                                                SC_None, nullptr);
14827   MoveConstructor->setParams(FromParam);
14828 
14829   MoveConstructor->setTrivial(
14830       ClassDecl->needsOverloadResolutionForMoveConstructor()
14831           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14832           : ClassDecl->hasTrivialMoveConstructor());
14833 
14834   MoveConstructor->setTrivialForCall(
14835       ClassDecl->hasAttr<TrivialABIAttr>() ||
14836       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14837            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14838                                     TAH_ConsiderTrivialABI)
14839            : ClassDecl->hasTrivialMoveConstructorForCall()));
14840 
14841   // Note that we have declared this constructor.
14842   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14843 
14844   Scope *S = getScopeForContext(ClassDecl);
14845   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14846 
14847   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14848     ClassDecl->setImplicitMoveConstructorIsDeleted();
14849     SetDeclDeleted(MoveConstructor, ClassLoc);
14850   }
14851 
14852   if (S)
14853     PushOnScopeChains(MoveConstructor, S, false);
14854   ClassDecl->addDecl(MoveConstructor);
14855 
14856   return MoveConstructor;
14857 }
14858 
14859 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14860                                          CXXConstructorDecl *MoveConstructor) {
14861   assert((MoveConstructor->isDefaulted() &&
14862           MoveConstructor->isMoveConstructor() &&
14863           !MoveConstructor->doesThisDeclarationHaveABody() &&
14864           !MoveConstructor->isDeleted()) &&
14865          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14866   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14867     return;
14868 
14869   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14870   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14871 
14872   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14873 
14874   // The exception specification is needed because we are defining the
14875   // function.
14876   ResolveExceptionSpec(CurrentLocation,
14877                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14878   MarkVTableUsed(CurrentLocation, ClassDecl);
14879 
14880   // Add a context note for diagnostics produced after this point.
14881   Scope.addContextNote(CurrentLocation);
14882 
14883   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14884     MoveConstructor->setInvalidDecl();
14885   } else {
14886     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14887                              ? MoveConstructor->getEndLoc()
14888                              : MoveConstructor->getLocation();
14889     Sema::CompoundScopeRAII CompoundScope(*this);
14890     MoveConstructor->setBody(ActOnCompoundStmt(
14891         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14892     MoveConstructor->markUsed(Context);
14893   }
14894 
14895   if (ASTMutationListener *L = getASTMutationListener()) {
14896     L->CompletedImplicitDefinition(MoveConstructor);
14897   }
14898 }
14899 
14900 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14901   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14902 }
14903 
14904 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14905                             SourceLocation CurrentLocation,
14906                             CXXConversionDecl *Conv) {
14907   SynthesizedFunctionScope Scope(*this, Conv);
14908   assert(!Conv->getReturnType()->isUndeducedType());
14909 
14910   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
14911   CallingConv CC =
14912       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
14913 
14914   CXXRecordDecl *Lambda = Conv->getParent();
14915   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14916   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
14917 
14918   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14919     CallOp = InstantiateFunctionDeclaration(
14920         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14921     if (!CallOp)
14922       return;
14923 
14924     Invoker = InstantiateFunctionDeclaration(
14925         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14926     if (!Invoker)
14927       return;
14928   }
14929 
14930   if (CallOp->isInvalidDecl())
14931     return;
14932 
14933   // Mark the call operator referenced (and add to pending instantiations
14934   // if necessary).
14935   // For both the conversion and static-invoker template specializations
14936   // we construct their body's in this function, so no need to add them
14937   // to the PendingInstantiations.
14938   MarkFunctionReferenced(CurrentLocation, CallOp);
14939 
14940   // Fill in the __invoke function with a dummy implementation. IR generation
14941   // will fill in the actual details. Update its type in case it contained
14942   // an 'auto'.
14943   Invoker->markUsed(Context);
14944   Invoker->setReferenced();
14945   Invoker->setType(Conv->getReturnType()->getPointeeType());
14946   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14947 
14948   // Construct the body of the conversion function { return __invoke; }.
14949   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14950                                        VK_LValue, Conv->getLocation());
14951   assert(FunctionRef && "Can't refer to __invoke function?");
14952   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14953   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14954                                      Conv->getLocation()));
14955   Conv->markUsed(Context);
14956   Conv->setReferenced();
14957 
14958   if (ASTMutationListener *L = getASTMutationListener()) {
14959     L->CompletedImplicitDefinition(Conv);
14960     L->CompletedImplicitDefinition(Invoker);
14961   }
14962 }
14963 
14964 
14965 
14966 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14967        SourceLocation CurrentLocation,
14968        CXXConversionDecl *Conv)
14969 {
14970   assert(!Conv->getParent()->isGenericLambda());
14971 
14972   SynthesizedFunctionScope Scope(*this, Conv);
14973 
14974   // Copy-initialize the lambda object as needed to capture it.
14975   Expr *This = ActOnCXXThis(CurrentLocation).get();
14976   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14977 
14978   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14979                                                         Conv->getLocation(),
14980                                                         Conv, DerefThis);
14981 
14982   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14983   // behavior.  Note that only the general conversion function does this
14984   // (since it's unusable otherwise); in the case where we inline the
14985   // block literal, it has block literal lifetime semantics.
14986   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14987     BuildBlock = ImplicitCastExpr::Create(
14988         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14989         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14990 
14991   if (BuildBlock.isInvalid()) {
14992     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14993     Conv->setInvalidDecl();
14994     return;
14995   }
14996 
14997   // Create the return statement that returns the block from the conversion
14998   // function.
14999   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15000   if (Return.isInvalid()) {
15001     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15002     Conv->setInvalidDecl();
15003     return;
15004   }
15005 
15006   // Set the body of the conversion function.
15007   Stmt *ReturnS = Return.get();
15008   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15009                                      Conv->getLocation()));
15010   Conv->markUsed(Context);
15011 
15012   // We're done; notify the mutation listener, if any.
15013   if (ASTMutationListener *L = getASTMutationListener()) {
15014     L->CompletedImplicitDefinition(Conv);
15015   }
15016 }
15017 
15018 /// Determine whether the given list arguments contains exactly one
15019 /// "real" (non-default) argument.
15020 static bool hasOneRealArgument(MultiExprArg Args) {
15021   switch (Args.size()) {
15022   case 0:
15023     return false;
15024 
15025   default:
15026     if (!Args[1]->isDefaultArgument())
15027       return false;
15028 
15029     LLVM_FALLTHROUGH;
15030   case 1:
15031     return !Args[0]->isDefaultArgument();
15032   }
15033 
15034   return false;
15035 }
15036 
15037 ExprResult
15038 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15039                             NamedDecl *FoundDecl,
15040                             CXXConstructorDecl *Constructor,
15041                             MultiExprArg ExprArgs,
15042                             bool HadMultipleCandidates,
15043                             bool IsListInitialization,
15044                             bool IsStdInitListInitialization,
15045                             bool RequiresZeroInit,
15046                             unsigned ConstructKind,
15047                             SourceRange ParenRange) {
15048   bool Elidable = false;
15049 
15050   // C++0x [class.copy]p34:
15051   //   When certain criteria are met, an implementation is allowed to
15052   //   omit the copy/move construction of a class object, even if the
15053   //   copy/move constructor and/or destructor for the object have
15054   //   side effects. [...]
15055   //     - when a temporary class object that has not been bound to a
15056   //       reference (12.2) would be copied/moved to a class object
15057   //       with the same cv-unqualified type, the copy/move operation
15058   //       can be omitted by constructing the temporary object
15059   //       directly into the target of the omitted copy/move
15060   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15061       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15062     Expr *SubExpr = ExprArgs[0];
15063     Elidable = SubExpr->isTemporaryObject(
15064         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15065   }
15066 
15067   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15068                                FoundDecl, Constructor,
15069                                Elidable, ExprArgs, HadMultipleCandidates,
15070                                IsListInitialization,
15071                                IsStdInitListInitialization, RequiresZeroInit,
15072                                ConstructKind, ParenRange);
15073 }
15074 
15075 ExprResult
15076 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15077                             NamedDecl *FoundDecl,
15078                             CXXConstructorDecl *Constructor,
15079                             bool Elidable,
15080                             MultiExprArg ExprArgs,
15081                             bool HadMultipleCandidates,
15082                             bool IsListInitialization,
15083                             bool IsStdInitListInitialization,
15084                             bool RequiresZeroInit,
15085                             unsigned ConstructKind,
15086                             SourceRange ParenRange) {
15087   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15088     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15089     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15090       return ExprError();
15091   }
15092 
15093   return BuildCXXConstructExpr(
15094       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15095       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15096       RequiresZeroInit, ConstructKind, ParenRange);
15097 }
15098 
15099 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15100 /// including handling of its default argument expressions.
15101 ExprResult
15102 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15103                             CXXConstructorDecl *Constructor,
15104                             bool Elidable,
15105                             MultiExprArg ExprArgs,
15106                             bool HadMultipleCandidates,
15107                             bool IsListInitialization,
15108                             bool IsStdInitListInitialization,
15109                             bool RequiresZeroInit,
15110                             unsigned ConstructKind,
15111                             SourceRange ParenRange) {
15112   assert(declaresSameEntity(
15113              Constructor->getParent(),
15114              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15115          "given constructor for wrong type");
15116   MarkFunctionReferenced(ConstructLoc, Constructor);
15117   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15118     return ExprError();
15119   if (getLangOpts().SYCLIsDevice &&
15120       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15121     return ExprError();
15122 
15123   return CheckForImmediateInvocation(
15124       CXXConstructExpr::Create(
15125           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15126           HadMultipleCandidates, IsListInitialization,
15127           IsStdInitListInitialization, RequiresZeroInit,
15128           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15129           ParenRange),
15130       Constructor);
15131 }
15132 
15133 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15134   assert(Field->hasInClassInitializer());
15135 
15136   // If we already have the in-class initializer nothing needs to be done.
15137   if (Field->getInClassInitializer())
15138     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15139 
15140   // If we might have already tried and failed to instantiate, don't try again.
15141   if (Field->isInvalidDecl())
15142     return ExprError();
15143 
15144   // Maybe we haven't instantiated the in-class initializer. Go check the
15145   // pattern FieldDecl to see if it has one.
15146   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15147 
15148   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15149     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15150     DeclContext::lookup_result Lookup =
15151         ClassPattern->lookup(Field->getDeclName());
15152 
15153     FieldDecl *Pattern = nullptr;
15154     for (auto L : Lookup) {
15155       if (isa<FieldDecl>(L)) {
15156         Pattern = cast<FieldDecl>(L);
15157         break;
15158       }
15159     }
15160     assert(Pattern && "We must have set the Pattern!");
15161 
15162     if (!Pattern->hasInClassInitializer() ||
15163         InstantiateInClassInitializer(Loc, Field, Pattern,
15164                                       getTemplateInstantiationArgs(Field))) {
15165       // Don't diagnose this again.
15166       Field->setInvalidDecl();
15167       return ExprError();
15168     }
15169     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15170   }
15171 
15172   // DR1351:
15173   //   If the brace-or-equal-initializer of a non-static data member
15174   //   invokes a defaulted default constructor of its class or of an
15175   //   enclosing class in a potentially evaluated subexpression, the
15176   //   program is ill-formed.
15177   //
15178   // This resolution is unworkable: the exception specification of the
15179   // default constructor can be needed in an unevaluated context, in
15180   // particular, in the operand of a noexcept-expression, and we can be
15181   // unable to compute an exception specification for an enclosed class.
15182   //
15183   // Any attempt to resolve the exception specification of a defaulted default
15184   // constructor before the initializer is lexically complete will ultimately
15185   // come here at which point we can diagnose it.
15186   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15187   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15188       << OutermostClass << Field;
15189   Diag(Field->getEndLoc(),
15190        diag::note_default_member_initializer_not_yet_parsed);
15191   // Recover by marking the field invalid, unless we're in a SFINAE context.
15192   if (!isSFINAEContext())
15193     Field->setInvalidDecl();
15194   return ExprError();
15195 }
15196 
15197 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15198   if (VD->isInvalidDecl()) return;
15199   // If initializing the variable failed, don't also diagnose problems with
15200   // the desctructor, they're likely related.
15201   if (VD->getInit() && VD->getInit()->containsErrors())
15202     return;
15203 
15204   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15205   if (ClassDecl->isInvalidDecl()) return;
15206   if (ClassDecl->hasIrrelevantDestructor()) return;
15207   if (ClassDecl->isDependentContext()) return;
15208 
15209   if (VD->isNoDestroy(getASTContext()))
15210     return;
15211 
15212   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15213 
15214   // If this is an array, we'll require the destructor during initialization, so
15215   // we can skip over this. We still want to emit exit-time destructor warnings
15216   // though.
15217   if (!VD->getType()->isArrayType()) {
15218     MarkFunctionReferenced(VD->getLocation(), Destructor);
15219     CheckDestructorAccess(VD->getLocation(), Destructor,
15220                           PDiag(diag::err_access_dtor_var)
15221                               << VD->getDeclName() << VD->getType());
15222     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15223   }
15224 
15225   if (Destructor->isTrivial()) return;
15226 
15227   // If the destructor is constexpr, check whether the variable has constant
15228   // destruction now.
15229   if (Destructor->isConstexpr()) {
15230     bool HasConstantInit = false;
15231     if (VD->getInit() && !VD->getInit()->isValueDependent())
15232       HasConstantInit = VD->evaluateValue();
15233     SmallVector<PartialDiagnosticAt, 8> Notes;
15234     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15235         HasConstantInit) {
15236       Diag(VD->getLocation(),
15237            diag::err_constexpr_var_requires_const_destruction) << VD;
15238       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15239         Diag(Notes[I].first, Notes[I].second);
15240     }
15241   }
15242 
15243   if (!VD->hasGlobalStorage()) return;
15244 
15245   // Emit warning for non-trivial dtor in global scope (a real global,
15246   // class-static, function-static).
15247   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15248 
15249   // TODO: this should be re-enabled for static locals by !CXAAtExit
15250   if (!VD->isStaticLocal())
15251     Diag(VD->getLocation(), diag::warn_global_destructor);
15252 }
15253 
15254 /// Given a constructor and the set of arguments provided for the
15255 /// constructor, convert the arguments and add any required default arguments
15256 /// to form a proper call to this constructor.
15257 ///
15258 /// \returns true if an error occurred, false otherwise.
15259 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15260                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15261                                    SourceLocation Loc,
15262                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15263                                    bool AllowExplicit,
15264                                    bool IsListInitialization) {
15265   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15266   unsigned NumArgs = ArgsPtr.size();
15267   Expr **Args = ArgsPtr.data();
15268 
15269   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15270   unsigned NumParams = Proto->getNumParams();
15271 
15272   // If too few arguments are available, we'll fill in the rest with defaults.
15273   if (NumArgs < NumParams)
15274     ConvertedArgs.reserve(NumParams);
15275   else
15276     ConvertedArgs.reserve(NumArgs);
15277 
15278   VariadicCallType CallType =
15279     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15280   SmallVector<Expr *, 8> AllArgs;
15281   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15282                                         Proto, 0,
15283                                         llvm::makeArrayRef(Args, NumArgs),
15284                                         AllArgs,
15285                                         CallType, AllowExplicit,
15286                                         IsListInitialization);
15287   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15288 
15289   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15290 
15291   CheckConstructorCall(Constructor, DeclInitType,
15292                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15293                        Proto, Loc);
15294 
15295   return Invalid;
15296 }
15297 
15298 static inline bool
15299 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15300                                        const FunctionDecl *FnDecl) {
15301   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15302   if (isa<NamespaceDecl>(DC)) {
15303     return SemaRef.Diag(FnDecl->getLocation(),
15304                         diag::err_operator_new_delete_declared_in_namespace)
15305       << FnDecl->getDeclName();
15306   }
15307 
15308   if (isa<TranslationUnitDecl>(DC) &&
15309       FnDecl->getStorageClass() == SC_Static) {
15310     return SemaRef.Diag(FnDecl->getLocation(),
15311                         diag::err_operator_new_delete_declared_static)
15312       << FnDecl->getDeclName();
15313   }
15314 
15315   return false;
15316 }
15317 
15318 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15319                                              const PointerType *PtrTy) {
15320   auto &Ctx = SemaRef.Context;
15321   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15322   PtrQuals.removeAddressSpace();
15323   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15324       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15325 }
15326 
15327 static inline bool
15328 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15329                             CanQualType ExpectedResultType,
15330                             CanQualType ExpectedFirstParamType,
15331                             unsigned DependentParamTypeDiag,
15332                             unsigned InvalidParamTypeDiag) {
15333   QualType ResultType =
15334       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15335 
15336   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15337     // The operator is valid on any address space for OpenCL.
15338     // Drop address space from actual and expected result types.
15339     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15340       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15341 
15342     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15343       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15344   }
15345 
15346   // Check that the result type is what we expect.
15347   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15348     // Reject even if the type is dependent; an operator delete function is
15349     // required to have a non-dependent result type.
15350     return SemaRef.Diag(
15351                FnDecl->getLocation(),
15352                ResultType->isDependentType()
15353                    ? diag::err_operator_new_delete_dependent_result_type
15354                    : diag::err_operator_new_delete_invalid_result_type)
15355            << FnDecl->getDeclName() << ExpectedResultType;
15356   }
15357 
15358   // A function template must have at least 2 parameters.
15359   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15360     return SemaRef.Diag(FnDecl->getLocation(),
15361                       diag::err_operator_new_delete_template_too_few_parameters)
15362         << FnDecl->getDeclName();
15363 
15364   // The function decl must have at least 1 parameter.
15365   if (FnDecl->getNumParams() == 0)
15366     return SemaRef.Diag(FnDecl->getLocation(),
15367                         diag::err_operator_new_delete_too_few_parameters)
15368       << FnDecl->getDeclName();
15369 
15370   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15371   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15372     // The operator is valid on any address space for OpenCL.
15373     // Drop address space from actual and expected first parameter types.
15374     if (const auto *PtrTy =
15375             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15376       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15377 
15378     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15379       ExpectedFirstParamType =
15380           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15381   }
15382 
15383   // Check that the first parameter type is what we expect.
15384   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15385       ExpectedFirstParamType) {
15386     // The first parameter type is not allowed to be dependent. As a tentative
15387     // DR resolution, we allow a dependent parameter type if it is the right
15388     // type anyway, to allow destroying operator delete in class templates.
15389     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15390                                                    ? DependentParamTypeDiag
15391                                                    : InvalidParamTypeDiag)
15392            << FnDecl->getDeclName() << ExpectedFirstParamType;
15393   }
15394 
15395   return false;
15396 }
15397 
15398 static bool
15399 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15400   // C++ [basic.stc.dynamic.allocation]p1:
15401   //   A program is ill-formed if an allocation function is declared in a
15402   //   namespace scope other than global scope or declared static in global
15403   //   scope.
15404   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15405     return true;
15406 
15407   CanQualType SizeTy =
15408     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15409 
15410   // C++ [basic.stc.dynamic.allocation]p1:
15411   //  The return type shall be void*. The first parameter shall have type
15412   //  std::size_t.
15413   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15414                                   SizeTy,
15415                                   diag::err_operator_new_dependent_param_type,
15416                                   diag::err_operator_new_param_type))
15417     return true;
15418 
15419   // C++ [basic.stc.dynamic.allocation]p1:
15420   //  The first parameter shall not have an associated default argument.
15421   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15422     return SemaRef.Diag(FnDecl->getLocation(),
15423                         diag::err_operator_new_default_arg)
15424       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15425 
15426   return false;
15427 }
15428 
15429 static bool
15430 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15431   // C++ [basic.stc.dynamic.deallocation]p1:
15432   //   A program is ill-formed if deallocation functions are declared in a
15433   //   namespace scope other than global scope or declared static in global
15434   //   scope.
15435   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15436     return true;
15437 
15438   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15439 
15440   // C++ P0722:
15441   //   Within a class C, the first parameter of a destroying operator delete
15442   //   shall be of type C *. The first parameter of any other deallocation
15443   //   function shall be of type void *.
15444   CanQualType ExpectedFirstParamType =
15445       MD && MD->isDestroyingOperatorDelete()
15446           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15447                 SemaRef.Context.getRecordType(MD->getParent())))
15448           : SemaRef.Context.VoidPtrTy;
15449 
15450   // C++ [basic.stc.dynamic.deallocation]p2:
15451   //   Each deallocation function shall return void
15452   if (CheckOperatorNewDeleteTypes(
15453           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15454           diag::err_operator_delete_dependent_param_type,
15455           diag::err_operator_delete_param_type))
15456     return true;
15457 
15458   // C++ P0722:
15459   //   A destroying operator delete shall be a usual deallocation function.
15460   if (MD && !MD->getParent()->isDependentContext() &&
15461       MD->isDestroyingOperatorDelete() &&
15462       !SemaRef.isUsualDeallocationFunction(MD)) {
15463     SemaRef.Diag(MD->getLocation(),
15464                  diag::err_destroying_operator_delete_not_usual);
15465     return true;
15466   }
15467 
15468   return false;
15469 }
15470 
15471 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15472 /// of this overloaded operator is well-formed. If so, returns false;
15473 /// otherwise, emits appropriate diagnostics and returns true.
15474 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15475   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15476          "Expected an overloaded operator declaration");
15477 
15478   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15479 
15480   // C++ [over.oper]p5:
15481   //   The allocation and deallocation functions, operator new,
15482   //   operator new[], operator delete and operator delete[], are
15483   //   described completely in 3.7.3. The attributes and restrictions
15484   //   found in the rest of this subclause do not apply to them unless
15485   //   explicitly stated in 3.7.3.
15486   if (Op == OO_Delete || Op == OO_Array_Delete)
15487     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15488 
15489   if (Op == OO_New || Op == OO_Array_New)
15490     return CheckOperatorNewDeclaration(*this, FnDecl);
15491 
15492   // C++ [over.oper]p6:
15493   //   An operator function shall either be a non-static member
15494   //   function or be a non-member function and have at least one
15495   //   parameter whose type is a class, a reference to a class, an
15496   //   enumeration, or a reference to an enumeration.
15497   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15498     if (MethodDecl->isStatic())
15499       return Diag(FnDecl->getLocation(),
15500                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15501   } else {
15502     bool ClassOrEnumParam = false;
15503     for (auto Param : FnDecl->parameters()) {
15504       QualType ParamType = Param->getType().getNonReferenceType();
15505       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15506           ParamType->isEnumeralType()) {
15507         ClassOrEnumParam = true;
15508         break;
15509       }
15510     }
15511 
15512     if (!ClassOrEnumParam)
15513       return Diag(FnDecl->getLocation(),
15514                   diag::err_operator_overload_needs_class_or_enum)
15515         << FnDecl->getDeclName();
15516   }
15517 
15518   // C++ [over.oper]p8:
15519   //   An operator function cannot have default arguments (8.3.6),
15520   //   except where explicitly stated below.
15521   //
15522   // Only the function-call operator allows default arguments
15523   // (C++ [over.call]p1).
15524   if (Op != OO_Call) {
15525     for (auto Param : FnDecl->parameters()) {
15526       if (Param->hasDefaultArg())
15527         return Diag(Param->getLocation(),
15528                     diag::err_operator_overload_default_arg)
15529           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15530     }
15531   }
15532 
15533   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15534     { false, false, false }
15535 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15536     , { Unary, Binary, MemberOnly }
15537 #include "clang/Basic/OperatorKinds.def"
15538   };
15539 
15540   bool CanBeUnaryOperator = OperatorUses[Op][0];
15541   bool CanBeBinaryOperator = OperatorUses[Op][1];
15542   bool MustBeMemberOperator = OperatorUses[Op][2];
15543 
15544   // C++ [over.oper]p8:
15545   //   [...] Operator functions cannot have more or fewer parameters
15546   //   than the number required for the corresponding operator, as
15547   //   described in the rest of this subclause.
15548   unsigned NumParams = FnDecl->getNumParams()
15549                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15550   if (Op != OO_Call &&
15551       ((NumParams == 1 && !CanBeUnaryOperator) ||
15552        (NumParams == 2 && !CanBeBinaryOperator) ||
15553        (NumParams < 1) || (NumParams > 2))) {
15554     // We have the wrong number of parameters.
15555     unsigned ErrorKind;
15556     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15557       ErrorKind = 2;  // 2 -> unary or binary.
15558     } else if (CanBeUnaryOperator) {
15559       ErrorKind = 0;  // 0 -> unary
15560     } else {
15561       assert(CanBeBinaryOperator &&
15562              "All non-call overloaded operators are unary or binary!");
15563       ErrorKind = 1;  // 1 -> binary
15564     }
15565 
15566     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15567       << FnDecl->getDeclName() << NumParams << ErrorKind;
15568   }
15569 
15570   // Overloaded operators other than operator() cannot be variadic.
15571   if (Op != OO_Call &&
15572       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15573     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15574       << FnDecl->getDeclName();
15575   }
15576 
15577   // Some operators must be non-static member functions.
15578   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15579     return Diag(FnDecl->getLocation(),
15580                 diag::err_operator_overload_must_be_member)
15581       << FnDecl->getDeclName();
15582   }
15583 
15584   // C++ [over.inc]p1:
15585   //   The user-defined function called operator++ implements the
15586   //   prefix and postfix ++ operator. If this function is a member
15587   //   function with no parameters, or a non-member function with one
15588   //   parameter of class or enumeration type, it defines the prefix
15589   //   increment operator ++ for objects of that type. If the function
15590   //   is a member function with one parameter (which shall be of type
15591   //   int) or a non-member function with two parameters (the second
15592   //   of which shall be of type int), it defines the postfix
15593   //   increment operator ++ for objects of that type.
15594   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15595     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15596     QualType ParamType = LastParam->getType();
15597 
15598     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15599         !ParamType->isDependentType())
15600       return Diag(LastParam->getLocation(),
15601                   diag::err_operator_overload_post_incdec_must_be_int)
15602         << LastParam->getType() << (Op == OO_MinusMinus);
15603   }
15604 
15605   return false;
15606 }
15607 
15608 static bool
15609 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15610                                           FunctionTemplateDecl *TpDecl) {
15611   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15612 
15613   // Must have one or two template parameters.
15614   if (TemplateParams->size() == 1) {
15615     NonTypeTemplateParmDecl *PmDecl =
15616         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15617 
15618     // The template parameter must be a char parameter pack.
15619     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15620         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15621       return false;
15622 
15623     // C++20 [over.literal]p5:
15624     //   A string literal operator template is a literal operator template
15625     //   whose template-parameter-list comprises a single non-type
15626     //   template-parameter of class type.
15627     //
15628     // As a DR resolution, we also allow placeholders for deduced class
15629     // template specializations.
15630     if (SemaRef.getLangOpts().CPlusPlus20 &&
15631         !PmDecl->isTemplateParameterPack() &&
15632         (PmDecl->getType()->isRecordType() ||
15633          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15634       return false;
15635   } else if (TemplateParams->size() == 2) {
15636     TemplateTypeParmDecl *PmType =
15637         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15638     NonTypeTemplateParmDecl *PmArgs =
15639         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15640 
15641     // The second template parameter must be a parameter pack with the
15642     // first template parameter as its type.
15643     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15644         PmArgs->isTemplateParameterPack()) {
15645       const TemplateTypeParmType *TArgs =
15646           PmArgs->getType()->getAs<TemplateTypeParmType>();
15647       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15648           TArgs->getIndex() == PmType->getIndex()) {
15649         if (!SemaRef.inTemplateInstantiation())
15650           SemaRef.Diag(TpDecl->getLocation(),
15651                        diag::ext_string_literal_operator_template);
15652         return false;
15653       }
15654     }
15655   }
15656 
15657   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15658                diag::err_literal_operator_template)
15659       << TpDecl->getTemplateParameters()->getSourceRange();
15660   return true;
15661 }
15662 
15663 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15664 /// of this literal operator function is well-formed. If so, returns
15665 /// false; otherwise, emits appropriate diagnostics and returns true.
15666 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15667   if (isa<CXXMethodDecl>(FnDecl)) {
15668     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15669       << FnDecl->getDeclName();
15670     return true;
15671   }
15672 
15673   if (FnDecl->isExternC()) {
15674     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15675     if (const LinkageSpecDecl *LSD =
15676             FnDecl->getDeclContext()->getExternCContext())
15677       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15678     return true;
15679   }
15680 
15681   // This might be the definition of a literal operator template.
15682   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15683 
15684   // This might be a specialization of a literal operator template.
15685   if (!TpDecl)
15686     TpDecl = FnDecl->getPrimaryTemplate();
15687 
15688   // template <char...> type operator "" name() and
15689   // template <class T, T...> type operator "" name() are the only valid
15690   // template signatures, and the only valid signatures with no parameters.
15691   //
15692   // C++20 also allows template <SomeClass T> type operator "" name().
15693   if (TpDecl) {
15694     if (FnDecl->param_size() != 0) {
15695       Diag(FnDecl->getLocation(),
15696            diag::err_literal_operator_template_with_params);
15697       return true;
15698     }
15699 
15700     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15701       return true;
15702 
15703   } else if (FnDecl->param_size() == 1) {
15704     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15705 
15706     QualType ParamType = Param->getType().getUnqualifiedType();
15707 
15708     // Only unsigned long long int, long double, any character type, and const
15709     // char * are allowed as the only parameters.
15710     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15711         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15712         Context.hasSameType(ParamType, Context.CharTy) ||
15713         Context.hasSameType(ParamType, Context.WideCharTy) ||
15714         Context.hasSameType(ParamType, Context.Char8Ty) ||
15715         Context.hasSameType(ParamType, Context.Char16Ty) ||
15716         Context.hasSameType(ParamType, Context.Char32Ty)) {
15717     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15718       QualType InnerType = Ptr->getPointeeType();
15719 
15720       // Pointer parameter must be a const char *.
15721       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15722                                 Context.CharTy) &&
15723             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15724         Diag(Param->getSourceRange().getBegin(),
15725              diag::err_literal_operator_param)
15726             << ParamType << "'const char *'" << Param->getSourceRange();
15727         return true;
15728       }
15729 
15730     } else if (ParamType->isRealFloatingType()) {
15731       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15732           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15733       return true;
15734 
15735     } else if (ParamType->isIntegerType()) {
15736       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15737           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15738       return true;
15739 
15740     } else {
15741       Diag(Param->getSourceRange().getBegin(),
15742            diag::err_literal_operator_invalid_param)
15743           << ParamType << Param->getSourceRange();
15744       return true;
15745     }
15746 
15747   } else if (FnDecl->param_size() == 2) {
15748     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15749 
15750     // First, verify that the first parameter is correct.
15751 
15752     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15753 
15754     // Two parameter function must have a pointer to const as a
15755     // first parameter; let's strip those qualifiers.
15756     const PointerType *PT = FirstParamType->getAs<PointerType>();
15757 
15758     if (!PT) {
15759       Diag((*Param)->getSourceRange().getBegin(),
15760            diag::err_literal_operator_param)
15761           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15762       return true;
15763     }
15764 
15765     QualType PointeeType = PT->getPointeeType();
15766     // First parameter must be const
15767     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15768       Diag((*Param)->getSourceRange().getBegin(),
15769            diag::err_literal_operator_param)
15770           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15771       return true;
15772     }
15773 
15774     QualType InnerType = PointeeType.getUnqualifiedType();
15775     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15776     // const char32_t* are allowed as the first parameter to a two-parameter
15777     // function
15778     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15779           Context.hasSameType(InnerType, Context.WideCharTy) ||
15780           Context.hasSameType(InnerType, Context.Char8Ty) ||
15781           Context.hasSameType(InnerType, Context.Char16Ty) ||
15782           Context.hasSameType(InnerType, Context.Char32Ty))) {
15783       Diag((*Param)->getSourceRange().getBegin(),
15784            diag::err_literal_operator_param)
15785           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15786       return true;
15787     }
15788 
15789     // Move on to the second and final parameter.
15790     ++Param;
15791 
15792     // The second parameter must be a std::size_t.
15793     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15794     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15795       Diag((*Param)->getSourceRange().getBegin(),
15796            diag::err_literal_operator_param)
15797           << SecondParamType << Context.getSizeType()
15798           << (*Param)->getSourceRange();
15799       return true;
15800     }
15801   } else {
15802     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15803     return true;
15804   }
15805 
15806   // Parameters are good.
15807 
15808   // A parameter-declaration-clause containing a default argument is not
15809   // equivalent to any of the permitted forms.
15810   for (auto Param : FnDecl->parameters()) {
15811     if (Param->hasDefaultArg()) {
15812       Diag(Param->getDefaultArgRange().getBegin(),
15813            diag::err_literal_operator_default_argument)
15814         << Param->getDefaultArgRange();
15815       break;
15816     }
15817   }
15818 
15819   StringRef LiteralName
15820     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15821   if (LiteralName[0] != '_' &&
15822       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15823     // C++11 [usrlit.suffix]p1:
15824     //   Literal suffix identifiers that do not start with an underscore
15825     //   are reserved for future standardization.
15826     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15827       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15828   }
15829 
15830   return false;
15831 }
15832 
15833 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15834 /// linkage specification, including the language and (if present)
15835 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15836 /// language string literal. LBraceLoc, if valid, provides the location of
15837 /// the '{' brace. Otherwise, this linkage specification does not
15838 /// have any braces.
15839 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15840                                            Expr *LangStr,
15841                                            SourceLocation LBraceLoc) {
15842   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15843   if (!Lit->isAscii()) {
15844     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15845       << LangStr->getSourceRange();
15846     return nullptr;
15847   }
15848 
15849   StringRef Lang = Lit->getString();
15850   LinkageSpecDecl::LanguageIDs Language;
15851   if (Lang == "C")
15852     Language = LinkageSpecDecl::lang_c;
15853   else if (Lang == "C++")
15854     Language = LinkageSpecDecl::lang_cxx;
15855   else {
15856     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15857       << LangStr->getSourceRange();
15858     return nullptr;
15859   }
15860 
15861   // FIXME: Add all the various semantics of linkage specifications
15862 
15863   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15864                                                LangStr->getExprLoc(), Language,
15865                                                LBraceLoc.isValid());
15866   CurContext->addDecl(D);
15867   PushDeclContext(S, D);
15868   return D;
15869 }
15870 
15871 /// ActOnFinishLinkageSpecification - Complete the definition of
15872 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15873 /// valid, it's the position of the closing '}' brace in a linkage
15874 /// specification that uses braces.
15875 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15876                                             Decl *LinkageSpec,
15877                                             SourceLocation RBraceLoc) {
15878   if (RBraceLoc.isValid()) {
15879     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15880     LSDecl->setRBraceLoc(RBraceLoc);
15881   }
15882   PopDeclContext();
15883   return LinkageSpec;
15884 }
15885 
15886 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15887                                   const ParsedAttributesView &AttrList,
15888                                   SourceLocation SemiLoc) {
15889   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15890   // Attribute declarations appertain to empty declaration so we handle
15891   // them here.
15892   ProcessDeclAttributeList(S, ED, AttrList);
15893 
15894   CurContext->addDecl(ED);
15895   return ED;
15896 }
15897 
15898 /// Perform semantic analysis for the variable declaration that
15899 /// occurs within a C++ catch clause, returning the newly-created
15900 /// variable.
15901 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15902                                          TypeSourceInfo *TInfo,
15903                                          SourceLocation StartLoc,
15904                                          SourceLocation Loc,
15905                                          IdentifierInfo *Name) {
15906   bool Invalid = false;
15907   QualType ExDeclType = TInfo->getType();
15908 
15909   // Arrays and functions decay.
15910   if (ExDeclType->isArrayType())
15911     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15912   else if (ExDeclType->isFunctionType())
15913     ExDeclType = Context.getPointerType(ExDeclType);
15914 
15915   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15916   // The exception-declaration shall not denote a pointer or reference to an
15917   // incomplete type, other than [cv] void*.
15918   // N2844 forbids rvalue references.
15919   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15920     Diag(Loc, diag::err_catch_rvalue_ref);
15921     Invalid = true;
15922   }
15923 
15924   if (ExDeclType->isVariablyModifiedType()) {
15925     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15926     Invalid = true;
15927   }
15928 
15929   QualType BaseType = ExDeclType;
15930   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15931   unsigned DK = diag::err_catch_incomplete;
15932   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15933     BaseType = Ptr->getPointeeType();
15934     Mode = 1;
15935     DK = diag::err_catch_incomplete_ptr;
15936   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15937     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15938     BaseType = Ref->getPointeeType();
15939     Mode = 2;
15940     DK = diag::err_catch_incomplete_ref;
15941   }
15942   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15943       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15944     Invalid = true;
15945 
15946   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15947     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15948     Invalid = true;
15949   }
15950 
15951   if (!Invalid && !ExDeclType->isDependentType() &&
15952       RequireNonAbstractType(Loc, ExDeclType,
15953                              diag::err_abstract_type_in_decl,
15954                              AbstractVariableType))
15955     Invalid = true;
15956 
15957   // Only the non-fragile NeXT runtime currently supports C++ catches
15958   // of ObjC types, and no runtime supports catching ObjC types by value.
15959   if (!Invalid && getLangOpts().ObjC) {
15960     QualType T = ExDeclType;
15961     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15962       T = RT->getPointeeType();
15963 
15964     if (T->isObjCObjectType()) {
15965       Diag(Loc, diag::err_objc_object_catch);
15966       Invalid = true;
15967     } else if (T->isObjCObjectPointerType()) {
15968       // FIXME: should this be a test for macosx-fragile specifically?
15969       if (getLangOpts().ObjCRuntime.isFragile())
15970         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15971     }
15972   }
15973 
15974   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15975                                     ExDeclType, TInfo, SC_None);
15976   ExDecl->setExceptionVariable(true);
15977 
15978   // In ARC, infer 'retaining' for variables of retainable type.
15979   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15980     Invalid = true;
15981 
15982   if (!Invalid && !ExDeclType->isDependentType()) {
15983     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15984       // Insulate this from anything else we might currently be parsing.
15985       EnterExpressionEvaluationContext scope(
15986           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15987 
15988       // C++ [except.handle]p16:
15989       //   The object declared in an exception-declaration or, if the
15990       //   exception-declaration does not specify a name, a temporary (12.2) is
15991       //   copy-initialized (8.5) from the exception object. [...]
15992       //   The object is destroyed when the handler exits, after the destruction
15993       //   of any automatic objects initialized within the handler.
15994       //
15995       // We just pretend to initialize the object with itself, then make sure
15996       // it can be destroyed later.
15997       QualType initType = Context.getExceptionObjectType(ExDeclType);
15998 
15999       InitializedEntity entity =
16000         InitializedEntity::InitializeVariable(ExDecl);
16001       InitializationKind initKind =
16002         InitializationKind::CreateCopy(Loc, SourceLocation());
16003 
16004       Expr *opaqueValue =
16005         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16006       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16007       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16008       if (result.isInvalid())
16009         Invalid = true;
16010       else {
16011         // If the constructor used was non-trivial, set this as the
16012         // "initializer".
16013         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16014         if (!construct->getConstructor()->isTrivial()) {
16015           Expr *init = MaybeCreateExprWithCleanups(construct);
16016           ExDecl->setInit(init);
16017         }
16018 
16019         // And make sure it's destructable.
16020         FinalizeVarWithDestructor(ExDecl, recordType);
16021       }
16022     }
16023   }
16024 
16025   if (Invalid)
16026     ExDecl->setInvalidDecl();
16027 
16028   return ExDecl;
16029 }
16030 
16031 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16032 /// handler.
16033 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16034   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16035   bool Invalid = D.isInvalidType();
16036 
16037   // Check for unexpanded parameter packs.
16038   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16039                                       UPPC_ExceptionType)) {
16040     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16041                                              D.getIdentifierLoc());
16042     Invalid = true;
16043   }
16044 
16045   IdentifierInfo *II = D.getIdentifier();
16046   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16047                                              LookupOrdinaryName,
16048                                              ForVisibleRedeclaration)) {
16049     // The scope should be freshly made just for us. There is just no way
16050     // it contains any previous declaration, except for function parameters in
16051     // a function-try-block's catch statement.
16052     assert(!S->isDeclScope(PrevDecl));
16053     if (isDeclInScope(PrevDecl, CurContext, S)) {
16054       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16055         << D.getIdentifier();
16056       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16057       Invalid = true;
16058     } else if (PrevDecl->isTemplateParameter())
16059       // Maybe we will complain about the shadowed template parameter.
16060       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16061   }
16062 
16063   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16064     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16065       << D.getCXXScopeSpec().getRange();
16066     Invalid = true;
16067   }
16068 
16069   VarDecl *ExDecl = BuildExceptionDeclaration(
16070       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16071   if (Invalid)
16072     ExDecl->setInvalidDecl();
16073 
16074   // Add the exception declaration into this scope.
16075   if (II)
16076     PushOnScopeChains(ExDecl, S);
16077   else
16078     CurContext->addDecl(ExDecl);
16079 
16080   ProcessDeclAttributes(S, ExDecl, D);
16081   return ExDecl;
16082 }
16083 
16084 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16085                                          Expr *AssertExpr,
16086                                          Expr *AssertMessageExpr,
16087                                          SourceLocation RParenLoc) {
16088   StringLiteral *AssertMessage =
16089       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16090 
16091   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16092     return nullptr;
16093 
16094   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16095                                       AssertMessage, RParenLoc, false);
16096 }
16097 
16098 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16099                                          Expr *AssertExpr,
16100                                          StringLiteral *AssertMessage,
16101                                          SourceLocation RParenLoc,
16102                                          bool Failed) {
16103   assert(AssertExpr != nullptr && "Expected non-null condition");
16104   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16105       !Failed) {
16106     // In a static_assert-declaration, the constant-expression shall be a
16107     // constant expression that can be contextually converted to bool.
16108     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16109     if (Converted.isInvalid())
16110       Failed = true;
16111 
16112     ExprResult FullAssertExpr =
16113         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16114                             /*DiscardedValue*/ false,
16115                             /*IsConstexpr*/ true);
16116     if (FullAssertExpr.isInvalid())
16117       Failed = true;
16118     else
16119       AssertExpr = FullAssertExpr.get();
16120 
16121     llvm::APSInt Cond;
16122     if (!Failed && VerifyIntegerConstantExpression(
16123                        AssertExpr, &Cond,
16124                        diag::err_static_assert_expression_is_not_constant)
16125                        .isInvalid())
16126       Failed = true;
16127 
16128     if (!Failed && !Cond) {
16129       SmallString<256> MsgBuffer;
16130       llvm::raw_svector_ostream Msg(MsgBuffer);
16131       if (AssertMessage)
16132         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16133 
16134       Expr *InnerCond = nullptr;
16135       std::string InnerCondDescription;
16136       std::tie(InnerCond, InnerCondDescription) =
16137         findFailedBooleanCondition(Converted.get());
16138       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16139         // Drill down into concept specialization expressions to see why they
16140         // weren't satisfied.
16141         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16142           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16143         ConstraintSatisfaction Satisfaction;
16144         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16145           DiagnoseUnsatisfiedConstraint(Satisfaction);
16146       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16147                            && !isa<IntegerLiteral>(InnerCond)) {
16148         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16149           << InnerCondDescription << !AssertMessage
16150           << Msg.str() << InnerCond->getSourceRange();
16151       } else {
16152         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16153           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16154       }
16155       Failed = true;
16156     }
16157   } else {
16158     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16159                                                     /*DiscardedValue*/false,
16160                                                     /*IsConstexpr*/true);
16161     if (FullAssertExpr.isInvalid())
16162       Failed = true;
16163     else
16164       AssertExpr = FullAssertExpr.get();
16165   }
16166 
16167   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16168                                         AssertExpr, AssertMessage, RParenLoc,
16169                                         Failed);
16170 
16171   CurContext->addDecl(Decl);
16172   return Decl;
16173 }
16174 
16175 /// Perform semantic analysis of the given friend type declaration.
16176 ///
16177 /// \returns A friend declaration that.
16178 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16179                                       SourceLocation FriendLoc,
16180                                       TypeSourceInfo *TSInfo) {
16181   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16182 
16183   QualType T = TSInfo->getType();
16184   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16185 
16186   // C++03 [class.friend]p2:
16187   //   An elaborated-type-specifier shall be used in a friend declaration
16188   //   for a class.*
16189   //
16190   //   * The class-key of the elaborated-type-specifier is required.
16191   if (!CodeSynthesisContexts.empty()) {
16192     // Do not complain about the form of friend template types during any kind
16193     // of code synthesis. For template instantiation, we will have complained
16194     // when the template was defined.
16195   } else {
16196     if (!T->isElaboratedTypeSpecifier()) {
16197       // If we evaluated the type to a record type, suggest putting
16198       // a tag in front.
16199       if (const RecordType *RT = T->getAs<RecordType>()) {
16200         RecordDecl *RD = RT->getDecl();
16201 
16202         SmallString<16> InsertionText(" ");
16203         InsertionText += RD->getKindName();
16204 
16205         Diag(TypeRange.getBegin(),
16206              getLangOpts().CPlusPlus11 ?
16207                diag::warn_cxx98_compat_unelaborated_friend_type :
16208                diag::ext_unelaborated_friend_type)
16209           << (unsigned) RD->getTagKind()
16210           << T
16211           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16212                                         InsertionText);
16213       } else {
16214         Diag(FriendLoc,
16215              getLangOpts().CPlusPlus11 ?
16216                diag::warn_cxx98_compat_nonclass_type_friend :
16217                diag::ext_nonclass_type_friend)
16218           << T
16219           << TypeRange;
16220       }
16221     } else if (T->getAs<EnumType>()) {
16222       Diag(FriendLoc,
16223            getLangOpts().CPlusPlus11 ?
16224              diag::warn_cxx98_compat_enum_friend :
16225              diag::ext_enum_friend)
16226         << T
16227         << TypeRange;
16228     }
16229 
16230     // C++11 [class.friend]p3:
16231     //   A friend declaration that does not declare a function shall have one
16232     //   of the following forms:
16233     //     friend elaborated-type-specifier ;
16234     //     friend simple-type-specifier ;
16235     //     friend typename-specifier ;
16236     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16237       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16238   }
16239 
16240   //   If the type specifier in a friend declaration designates a (possibly
16241   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16242   //   the friend declaration is ignored.
16243   return FriendDecl::Create(Context, CurContext,
16244                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16245                             FriendLoc);
16246 }
16247 
16248 /// Handle a friend tag declaration where the scope specifier was
16249 /// templated.
16250 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16251                                     unsigned TagSpec, SourceLocation TagLoc,
16252                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16253                                     SourceLocation NameLoc,
16254                                     const ParsedAttributesView &Attr,
16255                                     MultiTemplateParamsArg TempParamLists) {
16256   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16257 
16258   bool IsMemberSpecialization = false;
16259   bool Invalid = false;
16260 
16261   if (TemplateParameterList *TemplateParams =
16262           MatchTemplateParametersToScopeSpecifier(
16263               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16264               IsMemberSpecialization, Invalid)) {
16265     if (TemplateParams->size() > 0) {
16266       // This is a declaration of a class template.
16267       if (Invalid)
16268         return nullptr;
16269 
16270       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16271                                 NameLoc, Attr, TemplateParams, AS_public,
16272                                 /*ModulePrivateLoc=*/SourceLocation(),
16273                                 FriendLoc, TempParamLists.size() - 1,
16274                                 TempParamLists.data()).get();
16275     } else {
16276       // The "template<>" header is extraneous.
16277       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16278         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16279       IsMemberSpecialization = true;
16280     }
16281   }
16282 
16283   if (Invalid) return nullptr;
16284 
16285   bool isAllExplicitSpecializations = true;
16286   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16287     if (TempParamLists[I]->size()) {
16288       isAllExplicitSpecializations = false;
16289       break;
16290     }
16291   }
16292 
16293   // FIXME: don't ignore attributes.
16294 
16295   // If it's explicit specializations all the way down, just forget
16296   // about the template header and build an appropriate non-templated
16297   // friend.  TODO: for source fidelity, remember the headers.
16298   if (isAllExplicitSpecializations) {
16299     if (SS.isEmpty()) {
16300       bool Owned = false;
16301       bool IsDependent = false;
16302       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16303                       Attr, AS_public,
16304                       /*ModulePrivateLoc=*/SourceLocation(),
16305                       MultiTemplateParamsArg(), Owned, IsDependent,
16306                       /*ScopedEnumKWLoc=*/SourceLocation(),
16307                       /*ScopedEnumUsesClassTag=*/false,
16308                       /*UnderlyingType=*/TypeResult(),
16309                       /*IsTypeSpecifier=*/false,
16310                       /*IsTemplateParamOrArg=*/false);
16311     }
16312 
16313     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16314     ElaboratedTypeKeyword Keyword
16315       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16316     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16317                                    *Name, NameLoc);
16318     if (T.isNull())
16319       return nullptr;
16320 
16321     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16322     if (isa<DependentNameType>(T)) {
16323       DependentNameTypeLoc TL =
16324           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16325       TL.setElaboratedKeywordLoc(TagLoc);
16326       TL.setQualifierLoc(QualifierLoc);
16327       TL.setNameLoc(NameLoc);
16328     } else {
16329       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16330       TL.setElaboratedKeywordLoc(TagLoc);
16331       TL.setQualifierLoc(QualifierLoc);
16332       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16333     }
16334 
16335     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16336                                             TSI, FriendLoc, TempParamLists);
16337     Friend->setAccess(AS_public);
16338     CurContext->addDecl(Friend);
16339     return Friend;
16340   }
16341 
16342   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16343 
16344 
16345 
16346   // Handle the case of a templated-scope friend class.  e.g.
16347   //   template <class T> class A<T>::B;
16348   // FIXME: we don't support these right now.
16349   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16350     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16351   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16352   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16353   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16354   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16355   TL.setElaboratedKeywordLoc(TagLoc);
16356   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16357   TL.setNameLoc(NameLoc);
16358 
16359   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16360                                           TSI, FriendLoc, TempParamLists);
16361   Friend->setAccess(AS_public);
16362   Friend->setUnsupportedFriend(true);
16363   CurContext->addDecl(Friend);
16364   return Friend;
16365 }
16366 
16367 /// Handle a friend type declaration.  This works in tandem with
16368 /// ActOnTag.
16369 ///
16370 /// Notes on friend class templates:
16371 ///
16372 /// We generally treat friend class declarations as if they were
16373 /// declaring a class.  So, for example, the elaborated type specifier
16374 /// in a friend declaration is required to obey the restrictions of a
16375 /// class-head (i.e. no typedefs in the scope chain), template
16376 /// parameters are required to match up with simple template-ids, &c.
16377 /// However, unlike when declaring a template specialization, it's
16378 /// okay to refer to a template specialization without an empty
16379 /// template parameter declaration, e.g.
16380 ///   friend class A<T>::B<unsigned>;
16381 /// We permit this as a special case; if there are any template
16382 /// parameters present at all, require proper matching, i.e.
16383 ///   template <> template \<class T> friend class A<int>::B;
16384 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16385                                 MultiTemplateParamsArg TempParams) {
16386   SourceLocation Loc = DS.getBeginLoc();
16387 
16388   assert(DS.isFriendSpecified());
16389   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16390 
16391   // C++ [class.friend]p3:
16392   // A friend declaration that does not declare a function shall have one of
16393   // the following forms:
16394   //     friend elaborated-type-specifier ;
16395   //     friend simple-type-specifier ;
16396   //     friend typename-specifier ;
16397   //
16398   // Any declaration with a type qualifier does not have that form. (It's
16399   // legal to specify a qualified type as a friend, you just can't write the
16400   // keywords.)
16401   if (DS.getTypeQualifiers()) {
16402     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16403       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16404     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16405       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16406     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16407       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16408     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16409       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16410     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16411       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16412   }
16413 
16414   // Try to convert the decl specifier to a type.  This works for
16415   // friend templates because ActOnTag never produces a ClassTemplateDecl
16416   // for a TUK_Friend.
16417   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16418   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16419   QualType T = TSI->getType();
16420   if (TheDeclarator.isInvalidType())
16421     return nullptr;
16422 
16423   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16424     return nullptr;
16425 
16426   // This is definitely an error in C++98.  It's probably meant to
16427   // be forbidden in C++0x, too, but the specification is just
16428   // poorly written.
16429   //
16430   // The problem is with declarations like the following:
16431   //   template <T> friend A<T>::foo;
16432   // where deciding whether a class C is a friend or not now hinges
16433   // on whether there exists an instantiation of A that causes
16434   // 'foo' to equal C.  There are restrictions on class-heads
16435   // (which we declare (by fiat) elaborated friend declarations to
16436   // be) that makes this tractable.
16437   //
16438   // FIXME: handle "template <> friend class A<T>;", which
16439   // is possibly well-formed?  Who even knows?
16440   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16441     Diag(Loc, diag::err_tagless_friend_type_template)
16442       << DS.getSourceRange();
16443     return nullptr;
16444   }
16445 
16446   // C++98 [class.friend]p1: A friend of a class is a function
16447   //   or class that is not a member of the class . . .
16448   // This is fixed in DR77, which just barely didn't make the C++03
16449   // deadline.  It's also a very silly restriction that seriously
16450   // affects inner classes and which nobody else seems to implement;
16451   // thus we never diagnose it, not even in -pedantic.
16452   //
16453   // But note that we could warn about it: it's always useless to
16454   // friend one of your own members (it's not, however, worthless to
16455   // friend a member of an arbitrary specialization of your template).
16456 
16457   Decl *D;
16458   if (!TempParams.empty())
16459     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16460                                    TempParams,
16461                                    TSI,
16462                                    DS.getFriendSpecLoc());
16463   else
16464     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16465 
16466   if (!D)
16467     return nullptr;
16468 
16469   D->setAccess(AS_public);
16470   CurContext->addDecl(D);
16471 
16472   return D;
16473 }
16474 
16475 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16476                                         MultiTemplateParamsArg TemplateParams) {
16477   const DeclSpec &DS = D.getDeclSpec();
16478 
16479   assert(DS.isFriendSpecified());
16480   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16481 
16482   SourceLocation Loc = D.getIdentifierLoc();
16483   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16484 
16485   // C++ [class.friend]p1
16486   //   A friend of a class is a function or class....
16487   // Note that this sees through typedefs, which is intended.
16488   // It *doesn't* see through dependent types, which is correct
16489   // according to [temp.arg.type]p3:
16490   //   If a declaration acquires a function type through a
16491   //   type dependent on a template-parameter and this causes
16492   //   a declaration that does not use the syntactic form of a
16493   //   function declarator to have a function type, the program
16494   //   is ill-formed.
16495   if (!TInfo->getType()->isFunctionType()) {
16496     Diag(Loc, diag::err_unexpected_friend);
16497 
16498     // It might be worthwhile to try to recover by creating an
16499     // appropriate declaration.
16500     return nullptr;
16501   }
16502 
16503   // C++ [namespace.memdef]p3
16504   //  - If a friend declaration in a non-local class first declares a
16505   //    class or function, the friend class or function is a member
16506   //    of the innermost enclosing namespace.
16507   //  - The name of the friend is not found by simple name lookup
16508   //    until a matching declaration is provided in that namespace
16509   //    scope (either before or after the class declaration granting
16510   //    friendship).
16511   //  - If a friend function is called, its name may be found by the
16512   //    name lookup that considers functions from namespaces and
16513   //    classes associated with the types of the function arguments.
16514   //  - When looking for a prior declaration of a class or a function
16515   //    declared as a friend, scopes outside the innermost enclosing
16516   //    namespace scope are not considered.
16517 
16518   CXXScopeSpec &SS = D.getCXXScopeSpec();
16519   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16520   assert(NameInfo.getName());
16521 
16522   // Check for unexpanded parameter packs.
16523   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16524       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16525       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16526     return nullptr;
16527 
16528   // The context we found the declaration in, or in which we should
16529   // create the declaration.
16530   DeclContext *DC;
16531   Scope *DCScope = S;
16532   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16533                         ForExternalRedeclaration);
16534 
16535   // There are five cases here.
16536   //   - There's no scope specifier and we're in a local class. Only look
16537   //     for functions declared in the immediately-enclosing block scope.
16538   // We recover from invalid scope qualifiers as if they just weren't there.
16539   FunctionDecl *FunctionContainingLocalClass = nullptr;
16540   if ((SS.isInvalid() || !SS.isSet()) &&
16541       (FunctionContainingLocalClass =
16542            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16543     // C++11 [class.friend]p11:
16544     //   If a friend declaration appears in a local class and the name
16545     //   specified is an unqualified name, a prior declaration is
16546     //   looked up without considering scopes that are outside the
16547     //   innermost enclosing non-class scope. For a friend function
16548     //   declaration, if there is no prior declaration, the program is
16549     //   ill-formed.
16550 
16551     // Find the innermost enclosing non-class scope. This is the block
16552     // scope containing the local class definition (or for a nested class,
16553     // the outer local class).
16554     DCScope = S->getFnParent();
16555 
16556     // Look up the function name in the scope.
16557     Previous.clear(LookupLocalFriendName);
16558     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16559 
16560     if (!Previous.empty()) {
16561       // All possible previous declarations must have the same context:
16562       // either they were declared at block scope or they are members of
16563       // one of the enclosing local classes.
16564       DC = Previous.getRepresentativeDecl()->getDeclContext();
16565     } else {
16566       // This is ill-formed, but provide the context that we would have
16567       // declared the function in, if we were permitted to, for error recovery.
16568       DC = FunctionContainingLocalClass;
16569     }
16570     adjustContextForLocalExternDecl(DC);
16571 
16572     // C++ [class.friend]p6:
16573     //   A function can be defined in a friend declaration of a class if and
16574     //   only if the class is a non-local class (9.8), the function name is
16575     //   unqualified, and the function has namespace scope.
16576     if (D.isFunctionDefinition()) {
16577       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16578     }
16579 
16580   //   - There's no scope specifier, in which case we just go to the
16581   //     appropriate scope and look for a function or function template
16582   //     there as appropriate.
16583   } else if (SS.isInvalid() || !SS.isSet()) {
16584     // C++11 [namespace.memdef]p3:
16585     //   If the name in a friend declaration is neither qualified nor
16586     //   a template-id and the declaration is a function or an
16587     //   elaborated-type-specifier, the lookup to determine whether
16588     //   the entity has been previously declared shall not consider
16589     //   any scopes outside the innermost enclosing namespace.
16590     bool isTemplateId =
16591         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16592 
16593     // Find the appropriate context according to the above.
16594     DC = CurContext;
16595 
16596     // Skip class contexts.  If someone can cite chapter and verse
16597     // for this behavior, that would be nice --- it's what GCC and
16598     // EDG do, and it seems like a reasonable intent, but the spec
16599     // really only says that checks for unqualified existing
16600     // declarations should stop at the nearest enclosing namespace,
16601     // not that they should only consider the nearest enclosing
16602     // namespace.
16603     while (DC->isRecord())
16604       DC = DC->getParent();
16605 
16606     DeclContext *LookupDC = DC;
16607     while (LookupDC->isTransparentContext())
16608       LookupDC = LookupDC->getParent();
16609 
16610     while (true) {
16611       LookupQualifiedName(Previous, LookupDC);
16612 
16613       if (!Previous.empty()) {
16614         DC = LookupDC;
16615         break;
16616       }
16617 
16618       if (isTemplateId) {
16619         if (isa<TranslationUnitDecl>(LookupDC)) break;
16620       } else {
16621         if (LookupDC->isFileContext()) break;
16622       }
16623       LookupDC = LookupDC->getParent();
16624     }
16625 
16626     DCScope = getScopeForDeclContext(S, DC);
16627 
16628   //   - There's a non-dependent scope specifier, in which case we
16629   //     compute it and do a previous lookup there for a function
16630   //     or function template.
16631   } else if (!SS.getScopeRep()->isDependent()) {
16632     DC = computeDeclContext(SS);
16633     if (!DC) return nullptr;
16634 
16635     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16636 
16637     LookupQualifiedName(Previous, DC);
16638 
16639     // C++ [class.friend]p1: A friend of a class is a function or
16640     //   class that is not a member of the class . . .
16641     if (DC->Equals(CurContext))
16642       Diag(DS.getFriendSpecLoc(),
16643            getLangOpts().CPlusPlus11 ?
16644              diag::warn_cxx98_compat_friend_is_member :
16645              diag::err_friend_is_member);
16646 
16647     if (D.isFunctionDefinition()) {
16648       // C++ [class.friend]p6:
16649       //   A function can be defined in a friend declaration of a class if and
16650       //   only if the class is a non-local class (9.8), the function name is
16651       //   unqualified, and the function has namespace scope.
16652       //
16653       // FIXME: We should only do this if the scope specifier names the
16654       // innermost enclosing namespace; otherwise the fixit changes the
16655       // meaning of the code.
16656       SemaDiagnosticBuilder DB
16657         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16658 
16659       DB << SS.getScopeRep();
16660       if (DC->isFileContext())
16661         DB << FixItHint::CreateRemoval(SS.getRange());
16662       SS.clear();
16663     }
16664 
16665   //   - There's a scope specifier that does not match any template
16666   //     parameter lists, in which case we use some arbitrary context,
16667   //     create a method or method template, and wait for instantiation.
16668   //   - There's a scope specifier that does match some template
16669   //     parameter lists, which we don't handle right now.
16670   } else {
16671     if (D.isFunctionDefinition()) {
16672       // C++ [class.friend]p6:
16673       //   A function can be defined in a friend declaration of a class if and
16674       //   only if the class is a non-local class (9.8), the function name is
16675       //   unqualified, and the function has namespace scope.
16676       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16677         << SS.getScopeRep();
16678     }
16679 
16680     DC = CurContext;
16681     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16682   }
16683 
16684   if (!DC->isRecord()) {
16685     int DiagArg = -1;
16686     switch (D.getName().getKind()) {
16687     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16688     case UnqualifiedIdKind::IK_ConstructorName:
16689       DiagArg = 0;
16690       break;
16691     case UnqualifiedIdKind::IK_DestructorName:
16692       DiagArg = 1;
16693       break;
16694     case UnqualifiedIdKind::IK_ConversionFunctionId:
16695       DiagArg = 2;
16696       break;
16697     case UnqualifiedIdKind::IK_DeductionGuideName:
16698       DiagArg = 3;
16699       break;
16700     case UnqualifiedIdKind::IK_Identifier:
16701     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16702     case UnqualifiedIdKind::IK_LiteralOperatorId:
16703     case UnqualifiedIdKind::IK_OperatorFunctionId:
16704     case UnqualifiedIdKind::IK_TemplateId:
16705       break;
16706     }
16707     // This implies that it has to be an operator or function.
16708     if (DiagArg >= 0) {
16709       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16710       return nullptr;
16711     }
16712   }
16713 
16714   // FIXME: This is an egregious hack to cope with cases where the scope stack
16715   // does not contain the declaration context, i.e., in an out-of-line
16716   // definition of a class.
16717   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16718   if (!DCScope) {
16719     FakeDCScope.setEntity(DC);
16720     DCScope = &FakeDCScope;
16721   }
16722 
16723   bool AddToScope = true;
16724   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16725                                           TemplateParams, AddToScope);
16726   if (!ND) return nullptr;
16727 
16728   assert(ND->getLexicalDeclContext() == CurContext);
16729 
16730   // If we performed typo correction, we might have added a scope specifier
16731   // and changed the decl context.
16732   DC = ND->getDeclContext();
16733 
16734   // Add the function declaration to the appropriate lookup tables,
16735   // adjusting the redeclarations list as necessary.  We don't
16736   // want to do this yet if the friending class is dependent.
16737   //
16738   // Also update the scope-based lookup if the target context's
16739   // lookup context is in lexical scope.
16740   if (!CurContext->isDependentContext()) {
16741     DC = DC->getRedeclContext();
16742     DC->makeDeclVisibleInContext(ND);
16743     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16744       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16745   }
16746 
16747   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16748                                        D.getIdentifierLoc(), ND,
16749                                        DS.getFriendSpecLoc());
16750   FrD->setAccess(AS_public);
16751   CurContext->addDecl(FrD);
16752 
16753   if (ND->isInvalidDecl()) {
16754     FrD->setInvalidDecl();
16755   } else {
16756     if (DC->isRecord()) CheckFriendAccess(ND);
16757 
16758     FunctionDecl *FD;
16759     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16760       FD = FTD->getTemplatedDecl();
16761     else
16762       FD = cast<FunctionDecl>(ND);
16763 
16764     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16765     // default argument expression, that declaration shall be a definition
16766     // and shall be the only declaration of the function or function
16767     // template in the translation unit.
16768     if (functionDeclHasDefaultArgument(FD)) {
16769       // We can't look at FD->getPreviousDecl() because it may not have been set
16770       // if we're in a dependent context. If the function is known to be a
16771       // redeclaration, we will have narrowed Previous down to the right decl.
16772       if (D.isRedeclaration()) {
16773         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16774         Diag(Previous.getRepresentativeDecl()->getLocation(),
16775              diag::note_previous_declaration);
16776       } else if (!D.isFunctionDefinition())
16777         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16778     }
16779 
16780     // Mark templated-scope function declarations as unsupported.
16781     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16782       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16783         << SS.getScopeRep() << SS.getRange()
16784         << cast<CXXRecordDecl>(CurContext);
16785       FrD->setUnsupportedFriend(true);
16786     }
16787   }
16788 
16789   warnOnReservedIdentifier(ND);
16790 
16791   return ND;
16792 }
16793 
16794 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16795   AdjustDeclIfTemplate(Dcl);
16796 
16797   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16798   if (!Fn) {
16799     Diag(DelLoc, diag::err_deleted_non_function);
16800     return;
16801   }
16802 
16803   // Deleted function does not have a body.
16804   Fn->setWillHaveBody(false);
16805 
16806   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16807     // Don't consider the implicit declaration we generate for explicit
16808     // specializations. FIXME: Do not generate these implicit declarations.
16809     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16810          Prev->getPreviousDecl()) &&
16811         !Prev->isDefined()) {
16812       Diag(DelLoc, diag::err_deleted_decl_not_first);
16813       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16814            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16815                               : diag::note_previous_declaration);
16816       // We can't recover from this; the declaration might have already
16817       // been used.
16818       Fn->setInvalidDecl();
16819       return;
16820     }
16821 
16822     // To maintain the invariant that functions are only deleted on their first
16823     // declaration, mark the implicitly-instantiated declaration of the
16824     // explicitly-specialized function as deleted instead of marking the
16825     // instantiated redeclaration.
16826     Fn = Fn->getCanonicalDecl();
16827   }
16828 
16829   // dllimport/dllexport cannot be deleted.
16830   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16831     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16832     Fn->setInvalidDecl();
16833   }
16834 
16835   // C++11 [basic.start.main]p3:
16836   //   A program that defines main as deleted [...] is ill-formed.
16837   if (Fn->isMain())
16838     Diag(DelLoc, diag::err_deleted_main);
16839 
16840   // C++11 [dcl.fct.def.delete]p4:
16841   //  A deleted function is implicitly inline.
16842   Fn->setImplicitlyInline();
16843   Fn->setDeletedAsWritten();
16844 }
16845 
16846 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16847   if (!Dcl || Dcl->isInvalidDecl())
16848     return;
16849 
16850   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16851   if (!FD) {
16852     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16853       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16854         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16855         return;
16856       }
16857     }
16858 
16859     Diag(DefaultLoc, diag::err_default_special_members)
16860         << getLangOpts().CPlusPlus20;
16861     return;
16862   }
16863 
16864   // Reject if this can't possibly be a defaultable function.
16865   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16866   if (!DefKind &&
16867       // A dependent function that doesn't locally look defaultable can
16868       // still instantiate to a defaultable function if it's a constructor
16869       // or assignment operator.
16870       (!FD->isDependentContext() ||
16871        (!isa<CXXConstructorDecl>(FD) &&
16872         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16873     Diag(DefaultLoc, diag::err_default_special_members)
16874         << getLangOpts().CPlusPlus20;
16875     return;
16876   }
16877 
16878   if (DefKind.isComparison() &&
16879       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16880     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16881         << (int)DefKind.asComparison();
16882     return;
16883   }
16884 
16885   // Issue compatibility warning. We already warned if the operator is
16886   // 'operator<=>' when parsing the '<=>' token.
16887   if (DefKind.isComparison() &&
16888       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16889     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16890                          ? diag::warn_cxx17_compat_defaulted_comparison
16891                          : diag::ext_defaulted_comparison);
16892   }
16893 
16894   FD->setDefaulted();
16895   FD->setExplicitlyDefaulted();
16896 
16897   // Defer checking functions that are defaulted in a dependent context.
16898   if (FD->isDependentContext())
16899     return;
16900 
16901   // Unset that we will have a body for this function. We might not,
16902   // if it turns out to be trivial, and we don't need this marking now
16903   // that we've marked it as defaulted.
16904   FD->setWillHaveBody(false);
16905 
16906   // If this definition appears within the record, do the checking when
16907   // the record is complete. This is always the case for a defaulted
16908   // comparison.
16909   if (DefKind.isComparison())
16910     return;
16911   auto *MD = cast<CXXMethodDecl>(FD);
16912 
16913   const FunctionDecl *Primary = FD;
16914   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16915     // Ask the template instantiation pattern that actually had the
16916     // '= default' on it.
16917     Primary = Pattern;
16918 
16919   // If the method was defaulted on its first declaration, we will have
16920   // already performed the checking in CheckCompletedCXXClass. Such a
16921   // declaration doesn't trigger an implicit definition.
16922   if (Primary->getCanonicalDecl()->isDefaulted())
16923     return;
16924 
16925   // FIXME: Once we support defining comparisons out of class, check for a
16926   // defaulted comparison here.
16927   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16928     MD->setInvalidDecl();
16929   else
16930     DefineDefaultedFunction(*this, MD, DefaultLoc);
16931 }
16932 
16933 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16934   for (Stmt *SubStmt : S->children()) {
16935     if (!SubStmt)
16936       continue;
16937     if (isa<ReturnStmt>(SubStmt))
16938       Self.Diag(SubStmt->getBeginLoc(),
16939                 diag::err_return_in_constructor_handler);
16940     if (!isa<Expr>(SubStmt))
16941       SearchForReturnInStmt(Self, SubStmt);
16942   }
16943 }
16944 
16945 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16946   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16947     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16948     SearchForReturnInStmt(*this, Handler);
16949   }
16950 }
16951 
16952 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16953                                              const CXXMethodDecl *Old) {
16954   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16955   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16956 
16957   if (OldFT->hasExtParameterInfos()) {
16958     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16959       // A parameter of the overriding method should be annotated with noescape
16960       // if the corresponding parameter of the overridden method is annotated.
16961       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16962           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16963         Diag(New->getParamDecl(I)->getLocation(),
16964              diag::warn_overriding_method_missing_noescape);
16965         Diag(Old->getParamDecl(I)->getLocation(),
16966              diag::note_overridden_marked_noescape);
16967       }
16968   }
16969 
16970   // Virtual overrides must have the same code_seg.
16971   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16972   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16973   if ((NewCSA || OldCSA) &&
16974       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16975     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16976     Diag(Old->getLocation(), diag::note_previous_declaration);
16977     return true;
16978   }
16979 
16980   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16981 
16982   // If the calling conventions match, everything is fine
16983   if (NewCC == OldCC)
16984     return false;
16985 
16986   // If the calling conventions mismatch because the new function is static,
16987   // suppress the calling convention mismatch error; the error about static
16988   // function override (err_static_overrides_virtual from
16989   // Sema::CheckFunctionDeclaration) is more clear.
16990   if (New->getStorageClass() == SC_Static)
16991     return false;
16992 
16993   Diag(New->getLocation(),
16994        diag::err_conflicting_overriding_cc_attributes)
16995     << New->getDeclName() << New->getType() << Old->getType();
16996   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16997   return true;
16998 }
16999 
17000 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17001                                              const CXXMethodDecl *Old) {
17002   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17003   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17004 
17005   if (Context.hasSameType(NewTy, OldTy) ||
17006       NewTy->isDependentType() || OldTy->isDependentType())
17007     return false;
17008 
17009   // Check if the return types are covariant
17010   QualType NewClassTy, OldClassTy;
17011 
17012   /// Both types must be pointers or references to classes.
17013   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17014     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17015       NewClassTy = NewPT->getPointeeType();
17016       OldClassTy = OldPT->getPointeeType();
17017     }
17018   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17019     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17020       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17021         NewClassTy = NewRT->getPointeeType();
17022         OldClassTy = OldRT->getPointeeType();
17023       }
17024     }
17025   }
17026 
17027   // The return types aren't either both pointers or references to a class type.
17028   if (NewClassTy.isNull()) {
17029     Diag(New->getLocation(),
17030          diag::err_different_return_type_for_overriding_virtual_function)
17031         << New->getDeclName() << NewTy << OldTy
17032         << New->getReturnTypeSourceRange();
17033     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17034         << Old->getReturnTypeSourceRange();
17035 
17036     return true;
17037   }
17038 
17039   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17040     // C++14 [class.virtual]p8:
17041     //   If the class type in the covariant return type of D::f differs from
17042     //   that of B::f, the class type in the return type of D::f shall be
17043     //   complete at the point of declaration of D::f or shall be the class
17044     //   type D.
17045     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17046       if (!RT->isBeingDefined() &&
17047           RequireCompleteType(New->getLocation(), NewClassTy,
17048                               diag::err_covariant_return_incomplete,
17049                               New->getDeclName()))
17050         return true;
17051     }
17052 
17053     // Check if the new class derives from the old class.
17054     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17055       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17056           << New->getDeclName() << NewTy << OldTy
17057           << New->getReturnTypeSourceRange();
17058       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17059           << Old->getReturnTypeSourceRange();
17060       return true;
17061     }
17062 
17063     // Check if we the conversion from derived to base is valid.
17064     if (CheckDerivedToBaseConversion(
17065             NewClassTy, OldClassTy,
17066             diag::err_covariant_return_inaccessible_base,
17067             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17068             New->getLocation(), New->getReturnTypeSourceRange(),
17069             New->getDeclName(), nullptr)) {
17070       // FIXME: this note won't trigger for delayed access control
17071       // diagnostics, and it's impossible to get an undelayed error
17072       // here from access control during the original parse because
17073       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17074       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17075           << Old->getReturnTypeSourceRange();
17076       return true;
17077     }
17078   }
17079 
17080   // The qualifiers of the return types must be the same.
17081   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17082     Diag(New->getLocation(),
17083          diag::err_covariant_return_type_different_qualifications)
17084         << New->getDeclName() << NewTy << OldTy
17085         << New->getReturnTypeSourceRange();
17086     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17087         << Old->getReturnTypeSourceRange();
17088     return true;
17089   }
17090 
17091 
17092   // The new class type must have the same or less qualifiers as the old type.
17093   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17094     Diag(New->getLocation(),
17095          diag::err_covariant_return_type_class_type_more_qualified)
17096         << New->getDeclName() << NewTy << OldTy
17097         << New->getReturnTypeSourceRange();
17098     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17099         << Old->getReturnTypeSourceRange();
17100     return true;
17101   }
17102 
17103   return false;
17104 }
17105 
17106 /// Mark the given method pure.
17107 ///
17108 /// \param Method the method to be marked pure.
17109 ///
17110 /// \param InitRange the source range that covers the "0" initializer.
17111 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17112   SourceLocation EndLoc = InitRange.getEnd();
17113   if (EndLoc.isValid())
17114     Method->setRangeEnd(EndLoc);
17115 
17116   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17117     Method->setPure();
17118     return false;
17119   }
17120 
17121   if (!Method->isInvalidDecl())
17122     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17123       << Method->getDeclName() << InitRange;
17124   return true;
17125 }
17126 
17127 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17128   if (D->getFriendObjectKind())
17129     Diag(D->getLocation(), diag::err_pure_friend);
17130   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17131     CheckPureMethod(M, ZeroLoc);
17132   else
17133     Diag(D->getLocation(), diag::err_illegal_initializer);
17134 }
17135 
17136 /// Determine whether the given declaration is a global variable or
17137 /// static data member.
17138 static bool isNonlocalVariable(const Decl *D) {
17139   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17140     return Var->hasGlobalStorage();
17141 
17142   return false;
17143 }
17144 
17145 /// Invoked when we are about to parse an initializer for the declaration
17146 /// 'Dcl'.
17147 ///
17148 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17149 /// static data member of class X, names should be looked up in the scope of
17150 /// class X. If the declaration had a scope specifier, a scope will have
17151 /// been created and passed in for this purpose. Otherwise, S will be null.
17152 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17153   // If there is no declaration, there was an error parsing it.
17154   if (!D || D->isInvalidDecl())
17155     return;
17156 
17157   // We will always have a nested name specifier here, but this declaration
17158   // might not be out of line if the specifier names the current namespace:
17159   //   extern int n;
17160   //   int ::n = 0;
17161   if (S && D->isOutOfLine())
17162     EnterDeclaratorContext(S, D->getDeclContext());
17163 
17164   // If we are parsing the initializer for a static data member, push a
17165   // new expression evaluation context that is associated with this static
17166   // data member.
17167   if (isNonlocalVariable(D))
17168     PushExpressionEvaluationContext(
17169         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17170 }
17171 
17172 /// Invoked after we are finished parsing an initializer for the declaration D.
17173 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17174   // If there is no declaration, there was an error parsing it.
17175   if (!D || D->isInvalidDecl())
17176     return;
17177 
17178   if (isNonlocalVariable(D))
17179     PopExpressionEvaluationContext();
17180 
17181   if (S && D->isOutOfLine())
17182     ExitDeclaratorContext(S);
17183 }
17184 
17185 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17186 /// C++ if/switch/while/for statement.
17187 /// e.g: "if (int x = f()) {...}"
17188 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17189   // C++ 6.4p2:
17190   // The declarator shall not specify a function or an array.
17191   // The type-specifier-seq shall not contain typedef and shall not declare a
17192   // new class or enumeration.
17193   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17194          "Parser allowed 'typedef' as storage class of condition decl.");
17195 
17196   Decl *Dcl = ActOnDeclarator(S, D);
17197   if (!Dcl)
17198     return true;
17199 
17200   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17201     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17202       << D.getSourceRange();
17203     return true;
17204   }
17205 
17206   return Dcl;
17207 }
17208 
17209 void Sema::LoadExternalVTableUses() {
17210   if (!ExternalSource)
17211     return;
17212 
17213   SmallVector<ExternalVTableUse, 4> VTables;
17214   ExternalSource->ReadUsedVTables(VTables);
17215   SmallVector<VTableUse, 4> NewUses;
17216   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17217     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17218       = VTablesUsed.find(VTables[I].Record);
17219     // Even if a definition wasn't required before, it may be required now.
17220     if (Pos != VTablesUsed.end()) {
17221       if (!Pos->second && VTables[I].DefinitionRequired)
17222         Pos->second = true;
17223       continue;
17224     }
17225 
17226     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17227     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17228   }
17229 
17230   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17231 }
17232 
17233 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17234                           bool DefinitionRequired) {
17235   // Ignore any vtable uses in unevaluated operands or for classes that do
17236   // not have a vtable.
17237   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17238       CurContext->isDependentContext() || isUnevaluatedContext())
17239     return;
17240   // Do not mark as used if compiling for the device outside of the target
17241   // region.
17242   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17243       !isInOpenMPDeclareTargetContext() &&
17244       !isInOpenMPTargetExecutionDirective()) {
17245     if (!DefinitionRequired)
17246       MarkVirtualMembersReferenced(Loc, Class);
17247     return;
17248   }
17249 
17250   // Try to insert this class into the map.
17251   LoadExternalVTableUses();
17252   Class = Class->getCanonicalDecl();
17253   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17254     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17255   if (!Pos.second) {
17256     // If we already had an entry, check to see if we are promoting this vtable
17257     // to require a definition. If so, we need to reappend to the VTableUses
17258     // list, since we may have already processed the first entry.
17259     if (DefinitionRequired && !Pos.first->second) {
17260       Pos.first->second = true;
17261     } else {
17262       // Otherwise, we can early exit.
17263       return;
17264     }
17265   } else {
17266     // The Microsoft ABI requires that we perform the destructor body
17267     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17268     // the deleting destructor is emitted with the vtable, not with the
17269     // destructor definition as in the Itanium ABI.
17270     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17271       CXXDestructorDecl *DD = Class->getDestructor();
17272       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17273         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17274           // If this is an out-of-line declaration, marking it referenced will
17275           // not do anything. Manually call CheckDestructor to look up operator
17276           // delete().
17277           ContextRAII SavedContext(*this, DD);
17278           CheckDestructor(DD);
17279         } else {
17280           MarkFunctionReferenced(Loc, Class->getDestructor());
17281         }
17282       }
17283     }
17284   }
17285 
17286   // Local classes need to have their virtual members marked
17287   // immediately. For all other classes, we mark their virtual members
17288   // at the end of the translation unit.
17289   if (Class->isLocalClass())
17290     MarkVirtualMembersReferenced(Loc, Class);
17291   else
17292     VTableUses.push_back(std::make_pair(Class, Loc));
17293 }
17294 
17295 bool Sema::DefineUsedVTables() {
17296   LoadExternalVTableUses();
17297   if (VTableUses.empty())
17298     return false;
17299 
17300   // Note: The VTableUses vector could grow as a result of marking
17301   // the members of a class as "used", so we check the size each
17302   // time through the loop and prefer indices (which are stable) to
17303   // iterators (which are not).
17304   bool DefinedAnything = false;
17305   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17306     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17307     if (!Class)
17308       continue;
17309     TemplateSpecializationKind ClassTSK =
17310         Class->getTemplateSpecializationKind();
17311 
17312     SourceLocation Loc = VTableUses[I].second;
17313 
17314     bool DefineVTable = true;
17315 
17316     // If this class has a key function, but that key function is
17317     // defined in another translation unit, we don't need to emit the
17318     // vtable even though we're using it.
17319     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17320     if (KeyFunction && !KeyFunction->hasBody()) {
17321       // The key function is in another translation unit.
17322       DefineVTable = false;
17323       TemplateSpecializationKind TSK =
17324           KeyFunction->getTemplateSpecializationKind();
17325       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17326              TSK != TSK_ImplicitInstantiation &&
17327              "Instantiations don't have key functions");
17328       (void)TSK;
17329     } else if (!KeyFunction) {
17330       // If we have a class with no key function that is the subject
17331       // of an explicit instantiation declaration, suppress the
17332       // vtable; it will live with the explicit instantiation
17333       // definition.
17334       bool IsExplicitInstantiationDeclaration =
17335           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17336       for (auto R : Class->redecls()) {
17337         TemplateSpecializationKind TSK
17338           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17339         if (TSK == TSK_ExplicitInstantiationDeclaration)
17340           IsExplicitInstantiationDeclaration = true;
17341         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17342           IsExplicitInstantiationDeclaration = false;
17343           break;
17344         }
17345       }
17346 
17347       if (IsExplicitInstantiationDeclaration)
17348         DefineVTable = false;
17349     }
17350 
17351     // The exception specifications for all virtual members may be needed even
17352     // if we are not providing an authoritative form of the vtable in this TU.
17353     // We may choose to emit it available_externally anyway.
17354     if (!DefineVTable) {
17355       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17356       continue;
17357     }
17358 
17359     // Mark all of the virtual members of this class as referenced, so
17360     // that we can build a vtable. Then, tell the AST consumer that a
17361     // vtable for this class is required.
17362     DefinedAnything = true;
17363     MarkVirtualMembersReferenced(Loc, Class);
17364     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17365     if (VTablesUsed[Canonical])
17366       Consumer.HandleVTable(Class);
17367 
17368     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17369     // no key function or the key function is inlined. Don't warn in C++ ABIs
17370     // that lack key functions, since the user won't be able to make one.
17371     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17372         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17373       const FunctionDecl *KeyFunctionDef = nullptr;
17374       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17375                            KeyFunctionDef->isInlined())) {
17376         Diag(Class->getLocation(),
17377              ClassTSK == TSK_ExplicitInstantiationDefinition
17378                  ? diag::warn_weak_template_vtable
17379                  : diag::warn_weak_vtable)
17380             << Class;
17381       }
17382     }
17383   }
17384   VTableUses.clear();
17385 
17386   return DefinedAnything;
17387 }
17388 
17389 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17390                                                  const CXXRecordDecl *RD) {
17391   for (const auto *I : RD->methods())
17392     if (I->isVirtual() && !I->isPure())
17393       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17394 }
17395 
17396 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17397                                         const CXXRecordDecl *RD,
17398                                         bool ConstexprOnly) {
17399   // Mark all functions which will appear in RD's vtable as used.
17400   CXXFinalOverriderMap FinalOverriders;
17401   RD->getFinalOverriders(FinalOverriders);
17402   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17403                                             E = FinalOverriders.end();
17404        I != E; ++I) {
17405     for (OverridingMethods::const_iterator OI = I->second.begin(),
17406                                            OE = I->second.end();
17407          OI != OE; ++OI) {
17408       assert(OI->second.size() > 0 && "no final overrider");
17409       CXXMethodDecl *Overrider = OI->second.front().Method;
17410 
17411       // C++ [basic.def.odr]p2:
17412       //   [...] A virtual member function is used if it is not pure. [...]
17413       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17414         MarkFunctionReferenced(Loc, Overrider);
17415     }
17416   }
17417 
17418   // Only classes that have virtual bases need a VTT.
17419   if (RD->getNumVBases() == 0)
17420     return;
17421 
17422   for (const auto &I : RD->bases()) {
17423     const auto *Base =
17424         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17425     if (Base->getNumVBases() == 0)
17426       continue;
17427     MarkVirtualMembersReferenced(Loc, Base);
17428   }
17429 }
17430 
17431 /// SetIvarInitializers - This routine builds initialization ASTs for the
17432 /// Objective-C implementation whose ivars need be initialized.
17433 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17434   if (!getLangOpts().CPlusPlus)
17435     return;
17436   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17437     SmallVector<ObjCIvarDecl*, 8> ivars;
17438     CollectIvarsToConstructOrDestruct(OID, ivars);
17439     if (ivars.empty())
17440       return;
17441     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17442     for (unsigned i = 0; i < ivars.size(); i++) {
17443       FieldDecl *Field = ivars[i];
17444       if (Field->isInvalidDecl())
17445         continue;
17446 
17447       CXXCtorInitializer *Member;
17448       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17449       InitializationKind InitKind =
17450         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17451 
17452       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17453       ExprResult MemberInit =
17454         InitSeq.Perform(*this, InitEntity, InitKind, None);
17455       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17456       // Note, MemberInit could actually come back empty if no initialization
17457       // is required (e.g., because it would call a trivial default constructor)
17458       if (!MemberInit.get() || MemberInit.isInvalid())
17459         continue;
17460 
17461       Member =
17462         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17463                                          SourceLocation(),
17464                                          MemberInit.getAs<Expr>(),
17465                                          SourceLocation());
17466       AllToInit.push_back(Member);
17467 
17468       // Be sure that the destructor is accessible and is marked as referenced.
17469       if (const RecordType *RecordTy =
17470               Context.getBaseElementType(Field->getType())
17471                   ->getAs<RecordType>()) {
17472         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17473         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17474           MarkFunctionReferenced(Field->getLocation(), Destructor);
17475           CheckDestructorAccess(Field->getLocation(), Destructor,
17476                             PDiag(diag::err_access_dtor_ivar)
17477                               << Context.getBaseElementType(Field->getType()));
17478         }
17479       }
17480     }
17481     ObjCImplementation->setIvarInitializers(Context,
17482                                             AllToInit.data(), AllToInit.size());
17483   }
17484 }
17485 
17486 static
17487 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17488                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17489                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17490                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17491                            Sema &S) {
17492   if (Ctor->isInvalidDecl())
17493     return;
17494 
17495   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17496 
17497   // Target may not be determinable yet, for instance if this is a dependent
17498   // call in an uninstantiated template.
17499   if (Target) {
17500     const FunctionDecl *FNTarget = nullptr;
17501     (void)Target->hasBody(FNTarget);
17502     Target = const_cast<CXXConstructorDecl*>(
17503       cast_or_null<CXXConstructorDecl>(FNTarget));
17504   }
17505 
17506   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17507                      // Avoid dereferencing a null pointer here.
17508                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17509 
17510   if (!Current.insert(Canonical).second)
17511     return;
17512 
17513   // We know that beyond here, we aren't chaining into a cycle.
17514   if (!Target || !Target->isDelegatingConstructor() ||
17515       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17516     Valid.insert(Current.begin(), Current.end());
17517     Current.clear();
17518   // We've hit a cycle.
17519   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17520              Current.count(TCanonical)) {
17521     // If we haven't diagnosed this cycle yet, do so now.
17522     if (!Invalid.count(TCanonical)) {
17523       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17524              diag::warn_delegating_ctor_cycle)
17525         << Ctor;
17526 
17527       // Don't add a note for a function delegating directly to itself.
17528       if (TCanonical != Canonical)
17529         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17530 
17531       CXXConstructorDecl *C = Target;
17532       while (C->getCanonicalDecl() != Canonical) {
17533         const FunctionDecl *FNTarget = nullptr;
17534         (void)C->getTargetConstructor()->hasBody(FNTarget);
17535         assert(FNTarget && "Ctor cycle through bodiless function");
17536 
17537         C = const_cast<CXXConstructorDecl*>(
17538           cast<CXXConstructorDecl>(FNTarget));
17539         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17540       }
17541     }
17542 
17543     Invalid.insert(Current.begin(), Current.end());
17544     Current.clear();
17545   } else {
17546     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17547   }
17548 }
17549 
17550 
17551 void Sema::CheckDelegatingCtorCycles() {
17552   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17553 
17554   for (DelegatingCtorDeclsType::iterator
17555          I = DelegatingCtorDecls.begin(ExternalSource),
17556          E = DelegatingCtorDecls.end();
17557        I != E; ++I)
17558     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17559 
17560   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17561     (*CI)->setInvalidDecl();
17562 }
17563 
17564 namespace {
17565   /// AST visitor that finds references to the 'this' expression.
17566   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17567     Sema &S;
17568 
17569   public:
17570     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17571 
17572     bool VisitCXXThisExpr(CXXThisExpr *E) {
17573       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17574         << E->isImplicit();
17575       return false;
17576     }
17577   };
17578 }
17579 
17580 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17581   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17582   if (!TSInfo)
17583     return false;
17584 
17585   TypeLoc TL = TSInfo->getTypeLoc();
17586   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17587   if (!ProtoTL)
17588     return false;
17589 
17590   // C++11 [expr.prim.general]p3:
17591   //   [The expression this] shall not appear before the optional
17592   //   cv-qualifier-seq and it shall not appear within the declaration of a
17593   //   static member function (although its type and value category are defined
17594   //   within a static member function as they are within a non-static member
17595   //   function). [ Note: this is because declaration matching does not occur
17596   //  until the complete declarator is known. - end note ]
17597   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17598   FindCXXThisExpr Finder(*this);
17599 
17600   // If the return type came after the cv-qualifier-seq, check it now.
17601   if (Proto->hasTrailingReturn() &&
17602       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17603     return true;
17604 
17605   // Check the exception specification.
17606   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17607     return true;
17608 
17609   // Check the trailing requires clause
17610   if (Expr *E = Method->getTrailingRequiresClause())
17611     if (!Finder.TraverseStmt(E))
17612       return true;
17613 
17614   return checkThisInStaticMemberFunctionAttributes(Method);
17615 }
17616 
17617 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17618   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17619   if (!TSInfo)
17620     return false;
17621 
17622   TypeLoc TL = TSInfo->getTypeLoc();
17623   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17624   if (!ProtoTL)
17625     return false;
17626 
17627   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17628   FindCXXThisExpr Finder(*this);
17629 
17630   switch (Proto->getExceptionSpecType()) {
17631   case EST_Unparsed:
17632   case EST_Uninstantiated:
17633   case EST_Unevaluated:
17634   case EST_BasicNoexcept:
17635   case EST_NoThrow:
17636   case EST_DynamicNone:
17637   case EST_MSAny:
17638   case EST_None:
17639     break;
17640 
17641   case EST_DependentNoexcept:
17642   case EST_NoexceptFalse:
17643   case EST_NoexceptTrue:
17644     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17645       return true;
17646     LLVM_FALLTHROUGH;
17647 
17648   case EST_Dynamic:
17649     for (const auto &E : Proto->exceptions()) {
17650       if (!Finder.TraverseType(E))
17651         return true;
17652     }
17653     break;
17654   }
17655 
17656   return false;
17657 }
17658 
17659 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17660   FindCXXThisExpr Finder(*this);
17661 
17662   // Check attributes.
17663   for (const auto *A : Method->attrs()) {
17664     // FIXME: This should be emitted by tblgen.
17665     Expr *Arg = nullptr;
17666     ArrayRef<Expr *> Args;
17667     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17668       Arg = G->getArg();
17669     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17670       Arg = G->getArg();
17671     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17672       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17673     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17674       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17675     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17676       Arg = ETLF->getSuccessValue();
17677       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17678     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17679       Arg = STLF->getSuccessValue();
17680       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17681     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17682       Arg = LR->getArg();
17683     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17684       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17685     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17686       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17687     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17688       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17689     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17690       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17691     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17692       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17693 
17694     if (Arg && !Finder.TraverseStmt(Arg))
17695       return true;
17696 
17697     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17698       if (!Finder.TraverseStmt(Args[I]))
17699         return true;
17700     }
17701   }
17702 
17703   return false;
17704 }
17705 
17706 void Sema::checkExceptionSpecification(
17707     bool IsTopLevel, ExceptionSpecificationType EST,
17708     ArrayRef<ParsedType> DynamicExceptions,
17709     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17710     SmallVectorImpl<QualType> &Exceptions,
17711     FunctionProtoType::ExceptionSpecInfo &ESI) {
17712   Exceptions.clear();
17713   ESI.Type = EST;
17714   if (EST == EST_Dynamic) {
17715     Exceptions.reserve(DynamicExceptions.size());
17716     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17717       // FIXME: Preserve type source info.
17718       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17719 
17720       if (IsTopLevel) {
17721         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17722         collectUnexpandedParameterPacks(ET, Unexpanded);
17723         if (!Unexpanded.empty()) {
17724           DiagnoseUnexpandedParameterPacks(
17725               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17726               Unexpanded);
17727           continue;
17728         }
17729       }
17730 
17731       // Check that the type is valid for an exception spec, and
17732       // drop it if not.
17733       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17734         Exceptions.push_back(ET);
17735     }
17736     ESI.Exceptions = Exceptions;
17737     return;
17738   }
17739 
17740   if (isComputedNoexcept(EST)) {
17741     assert((NoexceptExpr->isTypeDependent() ||
17742             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17743             Context.BoolTy) &&
17744            "Parser should have made sure that the expression is boolean");
17745     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17746       ESI.Type = EST_BasicNoexcept;
17747       return;
17748     }
17749 
17750     ESI.NoexceptExpr = NoexceptExpr;
17751     return;
17752   }
17753 }
17754 
17755 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17756              ExceptionSpecificationType EST,
17757              SourceRange SpecificationRange,
17758              ArrayRef<ParsedType> DynamicExceptions,
17759              ArrayRef<SourceRange> DynamicExceptionRanges,
17760              Expr *NoexceptExpr) {
17761   if (!MethodD)
17762     return;
17763 
17764   // Dig out the method we're referring to.
17765   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17766     MethodD = FunTmpl->getTemplatedDecl();
17767 
17768   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17769   if (!Method)
17770     return;
17771 
17772   // Check the exception specification.
17773   llvm::SmallVector<QualType, 4> Exceptions;
17774   FunctionProtoType::ExceptionSpecInfo ESI;
17775   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17776                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17777                               ESI);
17778 
17779   // Update the exception specification on the function type.
17780   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17781 
17782   if (Method->isStatic())
17783     checkThisInStaticMemberFunctionExceptionSpec(Method);
17784 
17785   if (Method->isVirtual()) {
17786     // Check overrides, which we previously had to delay.
17787     for (const CXXMethodDecl *O : Method->overridden_methods())
17788       CheckOverridingFunctionExceptionSpec(Method, O);
17789   }
17790 }
17791 
17792 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17793 ///
17794 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17795                                        SourceLocation DeclStart, Declarator &D,
17796                                        Expr *BitWidth,
17797                                        InClassInitStyle InitStyle,
17798                                        AccessSpecifier AS,
17799                                        const ParsedAttr &MSPropertyAttr) {
17800   IdentifierInfo *II = D.getIdentifier();
17801   if (!II) {
17802     Diag(DeclStart, diag::err_anonymous_property);
17803     return nullptr;
17804   }
17805   SourceLocation Loc = D.getIdentifierLoc();
17806 
17807   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17808   QualType T = TInfo->getType();
17809   if (getLangOpts().CPlusPlus) {
17810     CheckExtraCXXDefaultArguments(D);
17811 
17812     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17813                                         UPPC_DataMemberType)) {
17814       D.setInvalidType();
17815       T = Context.IntTy;
17816       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17817     }
17818   }
17819 
17820   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17821 
17822   if (D.getDeclSpec().isInlineSpecified())
17823     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17824         << getLangOpts().CPlusPlus17;
17825   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17826     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17827          diag::err_invalid_thread)
17828       << DeclSpec::getSpecifierName(TSCS);
17829 
17830   // Check to see if this name was declared as a member previously
17831   NamedDecl *PrevDecl = nullptr;
17832   LookupResult Previous(*this, II, Loc, LookupMemberName,
17833                         ForVisibleRedeclaration);
17834   LookupName(Previous, S);
17835   switch (Previous.getResultKind()) {
17836   case LookupResult::Found:
17837   case LookupResult::FoundUnresolvedValue:
17838     PrevDecl = Previous.getAsSingle<NamedDecl>();
17839     break;
17840 
17841   case LookupResult::FoundOverloaded:
17842     PrevDecl = Previous.getRepresentativeDecl();
17843     break;
17844 
17845   case LookupResult::NotFound:
17846   case LookupResult::NotFoundInCurrentInstantiation:
17847   case LookupResult::Ambiguous:
17848     break;
17849   }
17850 
17851   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17852     // Maybe we will complain about the shadowed template parameter.
17853     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17854     // Just pretend that we didn't see the previous declaration.
17855     PrevDecl = nullptr;
17856   }
17857 
17858   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17859     PrevDecl = nullptr;
17860 
17861   SourceLocation TSSL = D.getBeginLoc();
17862   MSPropertyDecl *NewPD =
17863       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17864                              MSPropertyAttr.getPropertyDataGetter(),
17865                              MSPropertyAttr.getPropertyDataSetter());
17866   ProcessDeclAttributes(TUScope, NewPD, D);
17867   NewPD->setAccess(AS);
17868 
17869   if (NewPD->isInvalidDecl())
17870     Record->setInvalidDecl();
17871 
17872   if (D.getDeclSpec().isModulePrivateSpecified())
17873     NewPD->setModulePrivate();
17874 
17875   if (NewPD->isInvalidDecl() && PrevDecl) {
17876     // Don't introduce NewFD into scope; there's already something
17877     // with the same name in the same scope.
17878   } else if (II) {
17879     PushOnScopeChains(NewPD, S);
17880   } else
17881     Record->addDecl(NewPD);
17882 
17883   return NewPD;
17884 }
17885 
17886 void Sema::ActOnStartFunctionDeclarationDeclarator(
17887     Declarator &Declarator, unsigned TemplateParameterDepth) {
17888   auto &Info = InventedParameterInfos.emplace_back();
17889   TemplateParameterList *ExplicitParams = nullptr;
17890   ArrayRef<TemplateParameterList *> ExplicitLists =
17891       Declarator.getTemplateParameterLists();
17892   if (!ExplicitLists.empty()) {
17893     bool IsMemberSpecialization, IsInvalid;
17894     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17895         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17896         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17897         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17898         /*SuppressDiagnostic=*/true);
17899   }
17900   if (ExplicitParams) {
17901     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17902     for (NamedDecl *Param : *ExplicitParams)
17903       Info.TemplateParams.push_back(Param);
17904     Info.NumExplicitTemplateParams = ExplicitParams->size();
17905   } else {
17906     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17907     Info.NumExplicitTemplateParams = 0;
17908   }
17909 }
17910 
17911 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17912   auto &FSI = InventedParameterInfos.back();
17913   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17914     if (FSI.NumExplicitTemplateParams != 0) {
17915       TemplateParameterList *ExplicitParams =
17916           Declarator.getTemplateParameterLists().back();
17917       Declarator.setInventedTemplateParameterList(
17918           TemplateParameterList::Create(
17919               Context, ExplicitParams->getTemplateLoc(),
17920               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17921               ExplicitParams->getRAngleLoc(),
17922               ExplicitParams->getRequiresClause()));
17923     } else {
17924       Declarator.setInventedTemplateParameterList(
17925           TemplateParameterList::Create(
17926               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17927               SourceLocation(), /*RequiresClause=*/nullptr));
17928     }
17929   }
17930   InventedParameterInfos.pop_back();
17931 }
17932