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/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "clang/Sema/Template.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include <map>
47 #include <set>
48 
49 using namespace clang;
50 
51 //===----------------------------------------------------------------------===//
52 // CheckDefaultArgumentVisitor
53 //===----------------------------------------------------------------------===//
54 
55 namespace {
56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57 /// the default argument of a parameter to determine whether it
58 /// contains any ill-formed subexpressions. For example, this will
59 /// diagnose the use of local variables or parameters within the
60 /// default argument expression.
61 class CheckDefaultArgumentVisitor
62     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63   Sema &S;
64   const Expr *DefaultArg;
65 
66 public:
67   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68       : S(S), DefaultArg(DefaultArg) {}
69 
70   bool VisitExpr(const Expr *Node);
71   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73   bool VisitLambdaExpr(const LambdaExpr *Lambda);
74   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75 };
76 
77 /// VisitExpr - Visit all of the children of this expression.
78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79   bool IsInvalid = false;
80   for (const Stmt *SubStmt : Node->children())
81     IsInvalid |= Visit(SubStmt);
82   return IsInvalid;
83 }
84 
85 /// VisitDeclRefExpr - Visit a reference to a declaration, to
86 /// determine whether this declaration can be used in the default
87 /// argument expression.
88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89   const NamedDecl *Decl = DRE->getDecl();
90   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91     // C++ [dcl.fct.default]p9:
92     //   [...] parameters of a function shall not be used in default
93     //   argument expressions, even if they are not evaluated. [...]
94     //
95     // C++17 [dcl.fct.default]p9 (by CWG 2082):
96     //   [...] A parameter shall not appear as a potentially-evaluated
97     //   expression in a default argument. [...]
98     //
99     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100       return S.Diag(DRE->getBeginLoc(),
101                     diag::err_param_default_argument_references_param)
102              << Param->getDeclName() << DefaultArg->getSourceRange();
103   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104     // C++ [dcl.fct.default]p7:
105     //   Local variables shall not be used in default argument
106     //   expressions.
107     //
108     // C++17 [dcl.fct.default]p7 (by CWG 2082):
109     //   A local variable shall not appear as a potentially-evaluated
110     //   expression in a default argument.
111     //
112     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
114     //
115     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116       return S.Diag(DRE->getBeginLoc(),
117                     diag::err_param_default_argument_references_local)
118              << VDecl->getDeclName() << DefaultArg->getSourceRange();
119   }
120 
121   return false;
122 }
123 
124 /// VisitCXXThisExpr - Visit a C++ "this" expression.
125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126   // C++ [dcl.fct.default]p8:
127   //   The keyword this shall not be used in a default argument of a
128   //   member function.
129   return S.Diag(ThisE->getBeginLoc(),
130                 diag::err_param_default_argument_references_this)
131          << ThisE->getSourceRange();
132 }
133 
134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135     const PseudoObjectExpr *POE) {
136   bool Invalid = false;
137   for (const Expr *E : POE->semantics()) {
138     // Look through bindings.
139     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140       E = OVE->getSourceExpr();
141       assert(E && "pseudo-object binding without source expression?");
142     }
143 
144     Invalid |= Visit(E);
145   }
146   return Invalid;
147 }
148 
149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150   // C++11 [expr.lambda.prim]p13:
151   //   A lambda-expression appearing in a default argument shall not
152   //   implicitly or explicitly capture any entity.
153   if (Lambda->capture_begin() == Lambda->capture_end())
154     return false;
155 
156   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157 }
158 } // namespace
159 
160 void
161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
162                                                  const CXXMethodDecl *Method) {
163   // If we have an MSAny spec already, don't bother.
164   if (!Method || ComputedEST == EST_MSAny)
165     return;
166 
167   const FunctionProtoType *Proto
168     = Method->getType()->getAs<FunctionProtoType>();
169   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170   if (!Proto)
171     return;
172 
173   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174 
175   // If we have a throw-all spec at this point, ignore the function.
176   if (ComputedEST == EST_None)
177     return;
178 
179   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180     EST = EST_BasicNoexcept;
181 
182   switch (EST) {
183   case EST_Unparsed:
184   case EST_Uninstantiated:
185   case EST_Unevaluated:
186     llvm_unreachable("should not see unresolved exception specs here");
187 
188   // If this function can throw any exceptions, make a note of that.
189   case EST_MSAny:
190   case EST_None:
191     // FIXME: Whichever we see last of MSAny and None determines our result.
192     // We should make a consistent, order-independent choice here.
193     ClearExceptions();
194     ComputedEST = EST;
195     return;
196   case EST_NoexceptFalse:
197     ClearExceptions();
198     ComputedEST = EST_None;
199     return;
200   // FIXME: If the call to this decl is using any of its default arguments, we
201   // need to search them for potentially-throwing calls.
202   // If this function has a basic noexcept, it doesn't affect the outcome.
203   case EST_BasicNoexcept:
204   case EST_NoexceptTrue:
205   case EST_NoThrow:
206     return;
207   // If we're still at noexcept(true) and there's a throw() callee,
208   // change to that specification.
209   case EST_DynamicNone:
210     if (ComputedEST == EST_BasicNoexcept)
211       ComputedEST = EST_DynamicNone;
212     return;
213   case EST_DependentNoexcept:
214     llvm_unreachable(
215         "should not generate implicit declarations for dependent cases");
216   case EST_Dynamic:
217     break;
218   }
219   assert(EST == EST_Dynamic && "EST case not considered earlier.");
220   assert(ComputedEST != EST_None &&
221          "Shouldn't collect exceptions when throw-all is guaranteed.");
222   ComputedEST = EST_Dynamic;
223   // Record the exceptions in this function's exception specification.
224   for (const auto &E : Proto->exceptions())
225     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226       Exceptions.push_back(E);
227 }
228 
229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
230   if (!S || ComputedEST == EST_MSAny)
231     return;
232 
233   // FIXME:
234   //
235   // C++0x [except.spec]p14:
236   //   [An] implicit exception-specification specifies the type-id T if and
237   // only if T is allowed by the exception-specification of a function directly
238   // invoked by f's implicit definition; f shall allow all exceptions if any
239   // function it directly invokes allows all exceptions, and f shall allow no
240   // exceptions if every function it directly invokes allows no exceptions.
241   //
242   // Note in particular that if an implicit exception-specification is generated
243   // for a function containing a throw-expression, that specification can still
244   // be noexcept(true).
245   //
246   // Note also that 'directly invoked' is not defined in the standard, and there
247   // is no indication that we should only consider potentially-evaluated calls.
248   //
249   // Ultimately we should implement the intent of the standard: the exception
250   // specification should be the set of exceptions which can be thrown by the
251   // implicit definition. For now, we assume that any non-nothrow expression can
252   // throw any exception.
253 
254   if (Self->canThrow(S))
255     ComputedEST = EST_None;
256 }
257 
258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
259                                              SourceLocation EqualLoc) {
260   if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                           diag::err_typecheck_decl_incomplete_type))
262     return true;
263 
264   // C++ [dcl.fct.default]p5
265   //   A default argument expression is implicitly converted (clause
266   //   4) to the parameter type. The default argument expression has
267   //   the same semantic constraints as the initializer expression in
268   //   a declaration of a variable of the parameter type, using the
269   //   copy-initialization semantics (8.5).
270   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                     Param);
272   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                            EqualLoc);
274   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276   if (Result.isInvalid())
277     return true;
278   Arg = Result.getAs<Expr>();
279 
280   CheckCompletedExpr(Arg, EqualLoc);
281   Arg = MaybeCreateExprWithCleanups(Arg);
282 
283   return Arg;
284 }
285 
286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                    SourceLocation EqualLoc) {
288   // Add the default argument to the parameter
289   Param->setDefaultArg(Arg);
290 
291   // We have already instantiated this parameter; provide each of the
292   // instantiations with the uninstantiated default argument.
293   UnparsedDefaultArgInstantiationsMap::iterator InstPos
294     = UnparsedDefaultArgInstantiations.find(Param);
295   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299     // We're done tracking this parameter's instantiations.
300     UnparsedDefaultArgInstantiations.erase(InstPos);
301   }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                 Expr *DefaultArg) {
310   if (!param || !DefaultArg)
311     return;
312 
313   ParmVarDecl *Param = cast<ParmVarDecl>(param);
314   UnparsedDefaultArgLocs.erase(Param);
315 
316   auto Fail = [&] {
317     Param->setInvalidDecl();
318     Param->setDefaultArg(new (Context) OpaqueValueExpr(
319         EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320   };
321 
322   // Default arguments are only permitted in C++
323   if (!getLangOpts().CPlusPlus) {
324     Diag(EqualLoc, diag::err_param_default_argument)
325       << DefaultArg->getSourceRange();
326     return Fail();
327   }
328 
329   // Check for unexpanded parameter packs.
330   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331     return Fail();
332   }
333 
334   // C++11 [dcl.fct.default]p3
335   //   A default argument expression [...] shall not be specified for a
336   //   parameter pack.
337   if (Param->isParameterPack()) {
338     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339         << DefaultArg->getSourceRange();
340     // Recover by discarding the default argument.
341     Param->setDefaultArg(nullptr);
342     return;
343   }
344 
345   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346   if (Result.isInvalid())
347     return Fail();
348 
349   DefaultArg = Result.getAs<Expr>();
350 
351   // Check that the default argument is well-formed
352   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353   if (DefaultArgChecker.Visit(DefaultArg))
354     return Fail();
355 
356   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                              SourceLocation EqualLoc,
365                                              SourceLocation ArgLoc) {
366   if (!param)
367     return;
368 
369   ParmVarDecl *Param = cast<ParmVarDecl>(param);
370   Param->setUnparsedDefaultArg();
371   UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                           SourceLocation EqualLoc) {
378   if (!param)
379     return;
380 
381   ParmVarDecl *Param = cast<ParmVarDecl>(param);
382   Param->setInvalidDecl();
383   UnparsedDefaultArgLocs.erase(Param);
384   Param->setDefaultArg(new (Context) OpaqueValueExpr(
385       EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386 }
387 
388 /// CheckExtraCXXDefaultArguments - Check for any extra default
389 /// arguments in the declarator, which is not a function declaration
390 /// or definition and therefore is not permitted to have default
391 /// arguments. This routine should be invoked for every declarator
392 /// that is not a function declaration or definition.
393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
394   // C++ [dcl.fct.default]p3
395   //   A default argument expression shall be specified only in the
396   //   parameter-declaration-clause of a function declaration or in a
397   //   template-parameter (14.1). It shall not be specified for a
398   //   parameter pack. If it is specified in a
399   //   parameter-declaration-clause, it shall not occur within a
400   //   declarator or abstract-declarator of a parameter-declaration.
401   bool MightBeFunction = D.isFunctionDeclarationContext();
402   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403     DeclaratorChunk &chunk = D.getTypeObject(i);
404     if (chunk.Kind == DeclaratorChunk::Function) {
405       if (MightBeFunction) {
406         // This is a function declaration. It can have default arguments, but
407         // keep looking in case its return type is a function type with default
408         // arguments.
409         MightBeFunction = false;
410         continue;
411       }
412       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413            ++argIdx) {
414         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415         if (Param->hasUnparsedDefaultArg()) {
416           std::unique_ptr<CachedTokens> Toks =
417               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418           SourceRange SR;
419           if (Toks->size() > 1)
420             SR = SourceRange((*Toks)[1].getLocation(),
421                              Toks->back().getLocation());
422           else
423             SR = UnparsedDefaultArgLocs[Param];
424           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425             << SR;
426         } else if (Param->getDefaultArg()) {
427           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428             << Param->getDefaultArg()->getSourceRange();
429           Param->setDefaultArg(nullptr);
430         }
431       }
432     } else if (chunk.Kind != DeclaratorChunk::Paren) {
433       MightBeFunction = false;
434     }
435   }
436 }
437 
438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
439   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441   });
442 }
443 
444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
445 /// function, once we already know that they have the same
446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447 /// error, false otherwise.
448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
449                                 Scope *S) {
450   bool Invalid = false;
451 
452   // The declaration context corresponding to the scope is the semantic
453   // parent, unless this is a local function declaration, in which case
454   // it is that surrounding function.
455   DeclContext *ScopeDC = New->isLocalExternDecl()
456                              ? New->getLexicalDeclContext()
457                              : New->getDeclContext();
458 
459   // Find the previous declaration for the purpose of default arguments.
460   FunctionDecl *PrevForDefaultArgs = Old;
461   for (/**/; PrevForDefaultArgs;
462        // Don't bother looking back past the latest decl if this is a local
463        // extern declaration; nothing else could work.
464        PrevForDefaultArgs = New->isLocalExternDecl()
465                                 ? nullptr
466                                 : PrevForDefaultArgs->getPreviousDecl()) {
467     // Ignore hidden declarations.
468     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469       continue;
470 
471     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472         !New->isCXXClassMember()) {
473       // Ignore default arguments of old decl if they are not in
474       // the same scope and this is not an out-of-line definition of
475       // a member function.
476       continue;
477     }
478 
479     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480       // If only one of these is a local function declaration, then they are
481       // declared in different scopes, even though isDeclInScope may think
482       // they're in the same scope. (If both are local, the scope check is
483       // sufficient, and if neither is local, then they are in the same scope.)
484       continue;
485     }
486 
487     // We found the right previous declaration.
488     break;
489   }
490 
491   // C++ [dcl.fct.default]p4:
492   //   For non-template functions, default arguments can be added in
493   //   later declarations of a function in the same
494   //   scope. Declarations in different scopes have completely
495   //   distinct sets of default arguments. That is, declarations in
496   //   inner scopes do not acquire default arguments from
497   //   declarations in outer scopes, and vice versa. In a given
498   //   function declaration, all parameters subsequent to a
499   //   parameter with a default argument shall have default
500   //   arguments supplied in this or previous declarations. A
501   //   default argument shall not be redefined by a later
502   //   declaration (not even to the same value).
503   //
504   // C++ [dcl.fct.default]p6:
505   //   Except for member functions of class templates, the default arguments
506   //   in a member function definition that appears outside of the class
507   //   definition are added to the set of default arguments provided by the
508   //   member function declaration in the class definition.
509   for (unsigned p = 0, NumParams = PrevForDefaultArgs
510                                        ? PrevForDefaultArgs->getNumParams()
511                                        : 0;
512        p < NumParams; ++p) {
513     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514     ParmVarDecl *NewParam = New->getParamDecl(p);
515 
516     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
517     bool NewParamHasDfl = NewParam->hasDefaultArg();
518 
519     if (OldParamHasDfl && NewParamHasDfl) {
520       unsigned DiagDefaultParamID =
521         diag::err_param_default_argument_redefinition;
522 
523       // MSVC accepts that default parameters be redefined for member functions
524       // of template class. The new default parameter's value is ignored.
525       Invalid = true;
526       if (getLangOpts().MicrosoftExt) {
527         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528         if (MD && MD->getParent()->getDescribedClassTemplate()) {
529           // Merge the old default argument into the new parameter.
530           NewParam->setHasInheritedDefaultArg();
531           if (OldParam->hasUninstantiatedDefaultArg())
532             NewParam->setUninstantiatedDefaultArg(
533                                       OldParam->getUninstantiatedDefaultArg());
534           else
535             NewParam->setDefaultArg(OldParam->getInit());
536           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537           Invalid = false;
538         }
539       }
540 
541       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542       // hint here. Alternatively, we could walk the type-source information
543       // for NewParam to find the last source location in the type... but it
544       // isn't worth the effort right now. This is the kind of test case that
545       // is hard to get right:
546       //   int f(int);
547       //   void g(int (*fp)(int) = f);
548       //   void g(int (*fp)(int) = &f);
549       Diag(NewParam->getLocation(), DiagDefaultParamID)
550         << NewParam->getDefaultArgRange();
551 
552       // Look for the function declaration where the default argument was
553       // actually written, which may be a declaration prior to Old.
554       for (auto Older = PrevForDefaultArgs;
555            OldParam->hasInheritedDefaultArg(); /**/) {
556         Older = Older->getPreviousDecl();
557         OldParam = Older->getParamDecl(p);
558       }
559 
560       Diag(OldParam->getLocation(), diag::note_previous_definition)
561         << OldParam->getDefaultArgRange();
562     } else if (OldParamHasDfl) {
563       // Merge the old default argument into the new parameter unless the new
564       // function is a friend declaration in a template class. In the latter
565       // case the default arguments will be inherited when the friend
566       // declaration will be instantiated.
567       if (New->getFriendObjectKind() == Decl::FOK_None ||
568           !New->getLexicalDeclContext()->isDependentContext()) {
569         // It's important to use getInit() here;  getDefaultArg()
570         // strips off any top-level ExprWithCleanups.
571         NewParam->setHasInheritedDefaultArg();
572         if (OldParam->hasUnparsedDefaultArg())
573           NewParam->setUnparsedDefaultArg();
574         else if (OldParam->hasUninstantiatedDefaultArg())
575           NewParam->setUninstantiatedDefaultArg(
576                                        OldParam->getUninstantiatedDefaultArg());
577         else
578           NewParam->setDefaultArg(OldParam->getInit());
579       }
580     } else if (NewParamHasDfl) {
581       if (New->getDescribedFunctionTemplate()) {
582         // Paragraph 4, quoted above, only applies to non-template functions.
583         Diag(NewParam->getLocation(),
584              diag::err_param_default_argument_template_redecl)
585           << NewParam->getDefaultArgRange();
586         Diag(PrevForDefaultArgs->getLocation(),
587              diag::note_template_prev_declaration)
588             << false;
589       } else if (New->getTemplateSpecializationKind()
590                    != TSK_ImplicitInstantiation &&
591                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
592         // C++ [temp.expr.spec]p21:
593         //   Default function arguments shall not be specified in a declaration
594         //   or a definition for one of the following explicit specializations:
595         //     - the explicit specialization of a function template;
596         //     - the explicit specialization of a member function template;
597         //     - the explicit specialization of a member function of a class
598         //       template where the class template specialization to which the
599         //       member function specialization belongs is implicitly
600         //       instantiated.
601         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
602           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
603           << New->getDeclName()
604           << NewParam->getDefaultArgRange();
605       } else if (New->getDeclContext()->isDependentContext()) {
606         // C++ [dcl.fct.default]p6 (DR217):
607         //   Default arguments for a member function of a class template shall
608         //   be specified on the initial declaration of the member function
609         //   within the class template.
610         //
611         // Reading the tea leaves a bit in DR217 and its reference to DR205
612         // leads me to the conclusion that one cannot add default function
613         // arguments for an out-of-line definition of a member function of a
614         // dependent type.
615         int WhichKind = 2;
616         if (CXXRecordDecl *Record
617               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618           if (Record->getDescribedClassTemplate())
619             WhichKind = 0;
620           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621             WhichKind = 1;
622           else
623             WhichKind = 2;
624         }
625 
626         Diag(NewParam->getLocation(),
627              diag::err_param_default_argument_member_template_redecl)
628           << WhichKind
629           << NewParam->getDefaultArgRange();
630       }
631     }
632   }
633 
634   // DR1344: If a default argument is added outside a class definition and that
635   // default argument makes the function a special member function, the program
636   // is ill-formed. This can only happen for constructors.
637   if (isa<CXXConstructorDecl>(New) &&
638       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
639     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641     if (NewSM != OldSM) {
642       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643       assert(NewParam->hasDefaultArg());
644       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645         << NewParam->getDefaultArgRange() << NewSM;
646       Diag(Old->getLocation(), diag::note_previous_declaration);
647     }
648   }
649 
650   const FunctionDecl *Def;
651   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652   // template has a constexpr specifier then all its declarations shall
653   // contain the constexpr specifier.
654   if (New->getConstexprKind() != Old->getConstexprKind()) {
655     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656         << New << static_cast<int>(New->getConstexprKind())
657         << static_cast<int>(Old->getConstexprKind());
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
661              Old->isDefined(Def) &&
662              // If a friend function is inlined but does not have 'inline'
663              // specifier, it is a definition. Do not report attribute conflict
664              // in this case, redefinition will be diagnosed later.
665              (New->isInlineSpecified() ||
666               New->getFriendObjectKind() == Decl::FOK_None)) {
667     // C++11 [dcl.fcn.spec]p4:
668     //   If the definition of a function appears in a translation unit before its
669     //   first declaration as inline, the program is ill-formed.
670     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671     Diag(Def->getLocation(), diag::note_previous_definition);
672     Invalid = true;
673   }
674 
675   // C++17 [temp.deduct.guide]p3:
676   //   Two deduction guide declarations in the same translation unit
677   //   for the same class template shall not have equivalent
678   //   parameter-declaration-clauses.
679   if (isa<CXXDeductionGuideDecl>(New) &&
680       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
681     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682     Diag(Old->getLocation(), diag::note_previous_declaration);
683   }
684 
685   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686   // argument expression, that declaration shall be a definition and shall be
687   // the only declaration of the function or function template in the
688   // translation unit.
689   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
690       functionDeclHasDefaultArgument(Old)) {
691     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692     Diag(Old->getLocation(), diag::note_previous_declaration);
693     Invalid = true;
694   }
695 
696   // C++11 [temp.friend]p4 (DR329):
697   //   When a function is defined in a friend function declaration in a class
698   //   template, the function is instantiated when the function is odr-used.
699   //   The same restrictions on multiple declarations and definitions that
700   //   apply to non-template function declarations and definitions also apply
701   //   to these implicit definitions.
702   const FunctionDecl *OldDefinition = nullptr;
703   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
704       Old->isDefined(OldDefinition, true))
705     CheckForFunctionRedefinition(New, OldDefinition);
706 
707   return Invalid;
708 }
709 
710 NamedDecl *
711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
712                                    MultiTemplateParamsArg TemplateParamLists) {
713   assert(D.isDecompositionDeclarator());
714   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
715 
716   // The syntax only allows a decomposition declarator as a simple-declaration,
717   // a for-range-declaration, or a condition in Clang, but we parse it in more
718   // cases than that.
719   if (!D.mayHaveDecompositionDeclarator()) {
720     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721       << Decomp.getSourceRange();
722     return nullptr;
723   }
724 
725   if (!TemplateParamLists.empty()) {
726     // FIXME: There's no rule against this, but there are also no rules that
727     // would actually make it usable, so we reject it for now.
728     Diag(TemplateParamLists.front()->getTemplateLoc(),
729          diag::err_decomp_decl_template);
730     return nullptr;
731   }
732 
733   Diag(Decomp.getLSquareLoc(),
734        !getLangOpts().CPlusPlus17
735            ? diag::ext_decomp_decl
736            : D.getContext() == DeclaratorContext::Condition
737                  ? diag::ext_decomp_decl_cond
738                  : diag::warn_cxx14_compat_decomp_decl)
739       << Decomp.getSourceRange();
740 
741   // The semantic context is always just the current context.
742   DeclContext *const DC = CurContext;
743 
744   // C++17 [dcl.dcl]/8:
745   //   The decl-specifier-seq shall contain only the type-specifier auto
746   //   and cv-qualifiers.
747   // C++2a [dcl.dcl]/8:
748   //   If decl-specifier-seq contains any decl-specifier other than static,
749   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
750   auto &DS = D.getDeclSpec();
751   {
752     SmallVector<StringRef, 8> BadSpecifiers;
753     SmallVector<SourceLocation, 8> BadSpecifierLocs;
754     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756     if (auto SCS = DS.getStorageClassSpec()) {
757       if (SCS == DeclSpec::SCS_static) {
758         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760       } else {
761         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763       }
764     }
765     if (auto TSCS = DS.getThreadStorageClassSpec()) {
766       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768     }
769     if (DS.hasConstexprSpecifier()) {
770       BadSpecifiers.push_back(
771           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773     }
774     if (DS.isInlineSpecified()) {
775       BadSpecifiers.push_back("inline");
776       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777     }
778     if (!BadSpecifiers.empty()) {
779       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780       Err << (int)BadSpecifiers.size()
781           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782       // Don't add FixItHints to remove the specifiers; we do still respect
783       // them when building the underlying variable.
784       for (auto Loc : BadSpecifierLocs)
785         Err << SourceRange(Loc, Loc);
786     } else if (!CPlusPlus20Specifiers.empty()) {
787       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
788                          getLangOpts().CPlusPlus20
789                              ? diag::warn_cxx17_compat_decomp_decl_spec
790                              : diag::ext_decomp_decl_spec);
791       Warn << (int)CPlusPlus20Specifiers.size()
792            << llvm::join(CPlusPlus20Specifiers.begin(),
793                          CPlusPlus20Specifiers.end(), " ");
794       for (auto Loc : CPlusPlus20SpecifierLocs)
795         Warn << SourceRange(Loc, Loc);
796     }
797     // We can't recover from it being declared as a typedef.
798     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799       return nullptr;
800   }
801 
802   // C++2a [dcl.struct.bind]p1:
803   //   A cv that includes volatile is deprecated
804   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
805       getLangOpts().CPlusPlus20)
806     Diag(DS.getVolatileSpecLoc(),
807          diag::warn_deprecated_volatile_structured_binding);
808 
809   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810   QualType R = TInfo->getType();
811 
812   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
813                                       UPPC_DeclarationType))
814     D.setInvalidType();
815 
816   // The syntax only allows a single ref-qualifier prior to the decomposition
817   // declarator. No other declarator chunks are permitted. Also check the type
818   // specifier here.
819   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
821       (D.getNumTypeObjects() == 1 &&
822        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
823     Diag(Decomp.getLSquareLoc(),
824          (D.hasGroupingParens() ||
825           (D.getNumTypeObjects() &&
826            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
827              ? diag::err_decomp_decl_parens
828              : diag::err_decomp_decl_type)
829         << R;
830 
831     // In most cases, there's no actual problem with an explicitly-specified
832     // type, but a function type won't work here, and ActOnVariableDeclarator
833     // shouldn't be called for such a type.
834     if (R->isFunctionType())
835       D.setInvalidType();
836   }
837 
838   // Build the BindingDecls.
839   SmallVector<BindingDecl*, 8> Bindings;
840 
841   // Build the BindingDecls.
842   for (auto &B : D.getDecompositionDeclarator().bindings()) {
843     // Check for name conflicts.
844     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846                           ForVisibleRedeclaration);
847     LookupName(Previous, S,
848                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849 
850     // It's not permitted to shadow a template parameter name.
851     if (Previous.isSingleResult() &&
852         Previous.getFoundDecl()->isTemplateParameter()) {
853       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
854                                       Previous.getFoundDecl());
855       Previous.clear();
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859 
860     // Find the shadowed declaration before filtering for scope.
861     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
862                                   ? getShadowedDeclaration(BD, Previous)
863                                   : nullptr;
864 
865     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
867     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868                          /*AllowInlineNamespace*/false);
869 
870     if (!Previous.empty()) {
871       auto *Old = Previous.getRepresentativeDecl();
872       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873       Diag(Old->getLocation(), diag::note_previous_definition);
874     } else if (ShadowedDecl && !D.isRedeclaration()) {
875       CheckShadow(BD, ShadowedDecl, Previous);
876     }
877     PushOnScopeChains(BD, S, true);
878     Bindings.push_back(BD);
879     ParsingInitForAutoVars.insert(BD);
880   }
881 
882   // There are no prior lookup results for the variable itself, because it
883   // is unnamed.
884   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885                                Decomp.getLSquareLoc());
886   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
887                         ForVisibleRedeclaration);
888 
889   // Build the variable that holds the non-decomposed object.
890   bool AddToScope = true;
891   NamedDecl *New =
892       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893                               MultiTemplateParamsArg(), AddToScope, Bindings);
894   if (AddToScope) {
895     S->AddDecl(New);
896     CurContext->addHiddenDecl(New);
897   }
898 
899   if (isInOpenMPDeclareTargetContext())
900     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901 
902   return New;
903 }
904 
905 static bool checkSimpleDecomposition(
906     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
907     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909   if ((int64_t)Bindings.size() != NumElems) {
910     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911         << DecompType << (unsigned)Bindings.size()
912         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913         << toString(NumElems, 10) << (NumElems < Bindings.size());
914     return true;
915   }
916 
917   unsigned I = 0;
918   for (auto *B : Bindings) {
919     SourceLocation Loc = B->getLocation();
920     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921     if (E.isInvalid())
922       return true;
923     E = GetInit(Loc, E.get(), I++);
924     if (E.isInvalid())
925       return true;
926     B->setBinding(ElemType, E.get());
927   }
928 
929   return false;
930 }
931 
932 static bool checkArrayLikeDecomposition(Sema &S,
933                                         ArrayRef<BindingDecl *> Bindings,
934                                         ValueDecl *Src, QualType DecompType,
935                                         const llvm::APSInt &NumElems,
936                                         QualType ElemType) {
937   return checkSimpleDecomposition(
938       S, Bindings, Src, DecompType, NumElems, ElemType,
939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940         ExprResult E = S.ActOnIntegerConstant(Loc, I);
941         if (E.isInvalid())
942           return ExprError();
943         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944       });
945 }
946 
947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
948                                     ValueDecl *Src, QualType DecompType,
949                                     const ConstantArrayType *CAT) {
950   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951                                      llvm::APSInt(CAT->getSize()),
952                                      CAT->getElementType());
953 }
954 
955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
956                                      ValueDecl *Src, QualType DecompType,
957                                      const VectorType *VT) {
958   return checkArrayLikeDecomposition(
959       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
960       S.Context.getQualifiedType(VT->getElementType(),
961                                  DecompType.getQualifiers()));
962 }
963 
964 static bool checkComplexDecomposition(Sema &S,
965                                       ArrayRef<BindingDecl *> Bindings,
966                                       ValueDecl *Src, QualType DecompType,
967                                       const ComplexType *CT) {
968   return checkSimpleDecomposition(
969       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
970       S.Context.getQualifiedType(CT->getElementType(),
971                                  DecompType.getQualifiers()),
972       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
974       });
975 }
976 
977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
978                                      TemplateArgumentListInfo &Args,
979                                      const TemplateParameterList *Params) {
980   SmallString<128> SS;
981   llvm::raw_svector_ostream OS(SS);
982   bool First = true;
983   unsigned I = 0;
984   for (auto &Arg : Args.arguments()) {
985     if (!First)
986       OS << ", ";
987     Arg.getArgument().print(PrintingPolicy, OS,
988                             TemplateParameterList::shouldIncludeTypeForArgument(
989                                 PrintingPolicy, Params, I));
990     First = false;
991     I++;
992   }
993   return std::string(OS.str());
994 }
995 
996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997                                      SourceLocation Loc, StringRef Trait,
998                                      TemplateArgumentListInfo &Args,
999                                      unsigned DiagID) {
1000   auto DiagnoseMissing = [&] {
1001     if (DiagID)
1002       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003                                                Args, /*Params*/ nullptr);
1004     return true;
1005   };
1006 
1007   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1008   NamespaceDecl *Std = S.getStdNamespace();
1009   if (!Std)
1010     return DiagnoseMissing();
1011 
1012   // Look up the trait itself, within namespace std. We can diagnose various
1013   // problems with this lookup even if we've been asked to not diagnose a
1014   // missing specialization, because this can only fail if the user has been
1015   // declaring their own names in namespace std or we don't support the
1016   // standard library implementation in use.
1017   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1018                       Loc, Sema::LookupOrdinaryName);
1019   if (!S.LookupQualifiedName(Result, Std))
1020     return DiagnoseMissing();
1021   if (Result.isAmbiguous())
1022     return true;
1023 
1024   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025   if (!TraitTD) {
1026     Result.suppressDiagnostics();
1027     NamedDecl *Found = *Result.begin();
1028     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029     S.Diag(Found->getLocation(), diag::note_declared_at);
1030     return true;
1031   }
1032 
1033   // Build the template-id.
1034   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035   if (TraitTy.isNull())
1036     return true;
1037   if (!S.isCompleteType(Loc, TraitTy)) {
1038     if (DiagID)
1039       S.RequireCompleteType(
1040           Loc, TraitTy, DiagID,
1041           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1042                             TraitTD->getTemplateParameters()));
1043     return true;
1044   }
1045 
1046   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047   assert(RD && "specialization of class template is not a class?");
1048 
1049   // Look up the member of the trait type.
1050   S.LookupQualifiedName(TraitMemberLookup, RD);
1051   return TraitMemberLookup.isAmbiguous();
1052 }
1053 
1054 static TemplateArgumentLoc
1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1056                                    uint64_t I) {
1057   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1058   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1059 }
1060 
1061 static TemplateArgumentLoc
1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1063   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1064 }
1065 
1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067 
1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069                                llvm::APSInt &Size) {
1070   EnterExpressionEvaluationContext ContextRAII(
1071       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1072 
1073   DeclarationName Value = S.PP.getIdentifierInfo("value");
1074   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1075 
1076   // Form template argument list for tuple_size<T>.
1077   TemplateArgumentListInfo Args(Loc, Loc);
1078   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1079 
1080   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081   // it's not tuple-like.
1082   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083       R.empty())
1084     return IsTupleLike::NotTupleLike;
1085 
1086   // If we get this far, we've committed to the tuple interpretation, but
1087   // we can still fail if there actually isn't a usable ::value.
1088 
1089   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090     LookupResult &R;
1091     TemplateArgumentListInfo &Args;
1092     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093         : R(R), Args(Args) {}
1094     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095                                                SourceLocation Loc) override {
1096       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1097              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1098                                   /*Params*/ nullptr);
1099     }
1100   } Diagnoser(R, Args);
1101 
1102   ExprResult E =
1103       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104   if (E.isInvalid())
1105     return IsTupleLike::Error;
1106 
1107   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108   if (E.isInvalid())
1109     return IsTupleLike::Error;
1110 
1111   return IsTupleLike::TupleLike;
1112 }
1113 
1114 /// \return std::tuple_element<I, T>::type.
1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1116                                         unsigned I, QualType T) {
1117   // Form template argument list for tuple_element<I, T>.
1118   TemplateArgumentListInfo Args(Loc, Loc);
1119   Args.addArgument(
1120       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1122 
1123   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1125   if (lookupStdTypeTraitMember(
1126           S, R, Loc, "tuple_element", Args,
1127           diag::err_decomp_decl_std_tuple_element_not_specialized))
1128     return QualType();
1129 
1130   auto *TD = R.getAsSingle<TypeDecl>();
1131   if (!TD) {
1132     R.suppressDiagnostics();
1133     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1134         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1135                              /*Params*/ nullptr);
1136     if (!R.empty())
1137       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138     return QualType();
1139   }
1140 
1141   return S.Context.getTypeDeclType(TD);
1142 }
1143 
1144 namespace {
1145 struct InitializingBinding {
1146   Sema &S;
1147   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1148     Sema::CodeSynthesisContext Ctx;
1149     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1150     Ctx.PointOfInstantiation = BD->getLocation();
1151     Ctx.Entity = BD;
1152     S.pushCodeSynthesisContext(Ctx);
1153   }
1154   ~InitializingBinding() {
1155     S.popCodeSynthesisContext();
1156   }
1157 };
1158 }
1159 
1160 static bool checkTupleLikeDecomposition(Sema &S,
1161                                         ArrayRef<BindingDecl *> Bindings,
1162                                         VarDecl *Src, QualType DecompType,
1163                                         const llvm::APSInt &TupleSize) {
1164   if ((int64_t)Bindings.size() != TupleSize) {
1165     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166         << DecompType << (unsigned)Bindings.size()
1167         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169     return true;
1170   }
1171 
1172   if (Bindings.empty())
1173     return false;
1174 
1175   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176 
1177   // [dcl.decomp]p3:
1178   //   The unqualified-id get is looked up in the scope of E by class member
1179   //   access lookup ...
1180   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181   bool UseMemberGet = false;
1182   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183     if (auto *RD = DecompType->getAsCXXRecordDecl())
1184       S.LookupQualifiedName(MemberGet, RD);
1185     if (MemberGet.isAmbiguous())
1186       return true;
1187     //   ... and if that finds at least one declaration that is a function
1188     //   template whose first template parameter is a non-type parameter ...
1189     for (NamedDecl *D : MemberGet) {
1190       if (FunctionTemplateDecl *FTD =
1191               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192         TemplateParameterList *TPL = FTD->getTemplateParameters();
1193         if (TPL->size() != 0 &&
1194             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195           //   ... the initializer is e.get<i>().
1196           UseMemberGet = true;
1197           break;
1198         }
1199       }
1200     }
1201   }
1202 
1203   unsigned I = 0;
1204   for (auto *B : Bindings) {
1205     InitializingBinding InitContext(S, B);
1206     SourceLocation Loc = B->getLocation();
1207 
1208     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209     if (E.isInvalid())
1210       return true;
1211 
1212     //   e is an lvalue if the type of the entity is an lvalue reference and
1213     //   an xvalue otherwise
1214     if (!Src->getType()->isLValueReferenceType())
1215       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216                                    E.get(), nullptr, VK_XValue,
1217                                    FPOptionsOverride());
1218 
1219     TemplateArgumentListInfo Args(Loc, Loc);
1220     Args.addArgument(
1221         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1222 
1223     if (UseMemberGet) {
1224       //   if [lookup of member get] finds at least one declaration, the
1225       //   initializer is e.get<i-1>().
1226       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227                                      CXXScopeSpec(), SourceLocation(), nullptr,
1228                                      MemberGet, &Args, nullptr);
1229       if (E.isInvalid())
1230         return true;
1231 
1232       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233     } else {
1234       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1235       //   in the associated namespaces.
1236       Expr *Get = UnresolvedLookupExpr::Create(
1237           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1238           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1239           UnresolvedSetIterator(), UnresolvedSetIterator());
1240 
1241       Expr *Arg = E.get();
1242       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243     }
1244     if (E.isInvalid())
1245       return true;
1246     Expr *Init = E.get();
1247 
1248     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1249     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250     if (T.isNull())
1251       return true;
1252 
1253     //   each vi is a variable of type "reference to T" initialized with the
1254     //   initializer, where the reference is an lvalue reference if the
1255     //   initializer is an lvalue and an rvalue reference otherwise
1256     QualType RefType =
1257         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258     if (RefType.isNull())
1259       return true;
1260     auto *RefVD = VarDecl::Create(
1261         S.Context, Src->getDeclContext(), Loc, Loc,
1262         B->getDeclName().getAsIdentifierInfo(), RefType,
1263         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1264     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265     RefVD->setTSCSpec(Src->getTSCSpec());
1266     RefVD->setImplicit();
1267     if (Src->isInlineSpecified())
1268       RefVD->setInlineSpecified();
1269     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270 
1271     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1272     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1273     InitializationSequence Seq(S, Entity, Kind, Init);
1274     E = Seq.Perform(S, Entity, Kind, Init);
1275     if (E.isInvalid())
1276       return true;
1277     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278     if (E.isInvalid())
1279       return true;
1280     RefVD->setInit(E.get());
1281     S.CheckCompleteVariableDeclaration(RefVD);
1282 
1283     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1284                                    DeclarationNameInfo(B->getDeclName(), Loc),
1285                                    RefVD);
1286     if (E.isInvalid())
1287       return true;
1288 
1289     B->setBinding(T, E.get());
1290     I++;
1291   }
1292 
1293   return false;
1294 }
1295 
1296 /// Find the base class to decompose in a built-in decomposition of a class type.
1297 /// This base class search is, unfortunately, not quite like any other that we
1298 /// perform anywhere else in C++.
1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1300                                                 const CXXRecordDecl *RD,
1301                                                 CXXCastPath &BasePath) {
1302   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303                           CXXBasePath &Path) {
1304     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305   };
1306 
1307   const CXXRecordDecl *ClassWithFields = nullptr;
1308   AccessSpecifier AS = AS_public;
1309   if (RD->hasDirectFields())
1310     // [dcl.decomp]p4:
1311     //   Otherwise, all of E's non-static data members shall be public direct
1312     //   members of E ...
1313     ClassWithFields = RD;
1314   else {
1315     //   ... or of ...
1316     CXXBasePaths Paths;
1317     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319       // If no classes have fields, just decompose RD itself. (This will work
1320       // if and only if zero bindings were provided.)
1321       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322     }
1323 
1324     CXXBasePath *BestPath = nullptr;
1325     for (auto &P : Paths) {
1326       if (!BestPath)
1327         BestPath = &P;
1328       else if (!S.Context.hasSameType(P.back().Base->getType(),
1329                                       BestPath->back().Base->getType())) {
1330         //   ... the same ...
1331         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332           << false << RD << BestPath->back().Base->getType()
1333           << P.back().Base->getType();
1334         return DeclAccessPair();
1335       } else if (P.Access < BestPath->Access) {
1336         BestPath = &P;
1337       }
1338     }
1339 
1340     //   ... unambiguous ...
1341     QualType BaseType = BestPath->back().Base->getType();
1342     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345       return DeclAccessPair();
1346     }
1347 
1348     //   ... [accessible, implied by other rules] base class of E.
1349     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1351     AS = BestPath->Access;
1352 
1353     ClassWithFields = BaseType->getAsCXXRecordDecl();
1354     S.BuildBasePathArray(Paths, BasePath);
1355   }
1356 
1357   // The above search did not check whether the selected class itself has base
1358   // classes with fields, so check that now.
1359   CXXBasePaths Paths;
1360   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362       << (ClassWithFields == RD) << RD << ClassWithFields
1363       << Paths.front().back().Base->getType();
1364     return DeclAccessPair();
1365   }
1366 
1367   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368 }
1369 
1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1371                                      ValueDecl *Src, QualType DecompType,
1372                                      const CXXRecordDecl *OrigRD) {
1373   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374                             diag::err_incomplete_type))
1375     return true;
1376 
1377   CXXCastPath BasePath;
1378   DeclAccessPair BasePair =
1379       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381   if (!RD)
1382     return true;
1383   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1384                                                  DecompType.getQualifiers());
1385 
1386   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387     unsigned NumFields = llvm::count_if(
1388         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389     assert(Bindings.size() != NumFields);
1390     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392         << (NumFields < Bindings.size());
1393     return true;
1394   };
1395 
1396   //   all of E's non-static data members shall be [...] well-formed
1397   //   when named as e.name in the context of the structured binding,
1398   //   E shall not have an anonymous union member, ...
1399   unsigned I = 0;
1400   for (auto *FD : RD->fields()) {
1401     if (FD->isUnnamedBitfield())
1402       continue;
1403 
1404     // All the non-static data members are required to be nameable, so they
1405     // must all have names.
1406     if (!FD->getDeclName()) {
1407       if (RD->isLambda()) {
1408         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410         return true;
1411       }
1412 
1413       if (FD->isAnonymousStructOrUnion()) {
1414         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415           << DecompType << FD->getType()->isUnionType();
1416         S.Diag(FD->getLocation(), diag::note_declared_at);
1417         return true;
1418       }
1419 
1420       // FIXME: Are there any other ways we could have an anonymous member?
1421     }
1422 
1423     // We have a real field to bind.
1424     if (I >= Bindings.size())
1425       return DiagnoseBadNumberOfBindings();
1426     auto *B = Bindings[I++];
1427     SourceLocation Loc = B->getLocation();
1428 
1429     // The field must be accessible in the context of the structured binding.
1430     // We already checked that the base class is accessible.
1431     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432     // const_cast here.
1433     S.CheckStructuredBindingMemberAccess(
1434         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436                                      BasePair.getAccess(), FD->getAccess())));
1437 
1438     // Initialize the binding to Src.FD.
1439     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440     if (E.isInvalid())
1441       return true;
1442     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443                             VK_LValue, &BasePath);
1444     if (E.isInvalid())
1445       return true;
1446     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447                                   CXXScopeSpec(), FD,
1448                                   DeclAccessPair::make(FD, FD->getAccess()),
1449                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1450     if (E.isInvalid())
1451       return true;
1452 
1453     // If the type of the member is T, the referenced type is cv T, where cv is
1454     // the cv-qualification of the decomposition expression.
1455     //
1456     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457     // 'const' to the type of the field.
1458     Qualifiers Q = DecompType.getQualifiers();
1459     if (FD->isMutable())
1460       Q.removeConst();
1461     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462   }
1463 
1464   if (I != Bindings.size())
1465     return DiagnoseBadNumberOfBindings();
1466 
1467   return false;
1468 }
1469 
1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471   QualType DecompType = DD->getType();
1472 
1473   // If the type of the decomposition is dependent, then so is the type of
1474   // each binding.
1475   if (DecompType->isDependentType()) {
1476     for (auto *B : DD->bindings())
1477       B->setType(Context.DependentTy);
1478     return;
1479   }
1480 
1481   DecompType = DecompType.getNonReferenceType();
1482   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483 
1484   // C++1z [dcl.decomp]/2:
1485   //   If E is an array type [...]
1486   // As an extension, we also support decomposition of built-in complex and
1487   // vector types.
1488   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490       DD->setInvalidDecl();
1491     return;
1492   }
1493   if (auto *VT = DecompType->getAs<VectorType>()) {
1494     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495       DD->setInvalidDecl();
1496     return;
1497   }
1498   if (auto *CT = DecompType->getAs<ComplexType>()) {
1499     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500       DD->setInvalidDecl();
1501     return;
1502   }
1503 
1504   // C++1z [dcl.decomp]/3:
1505   //   if the expression std::tuple_size<E>::value is a well-formed integral
1506   //   constant expression, [...]
1507   llvm::APSInt TupleSize(32);
1508   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509   case IsTupleLike::Error:
1510     DD->setInvalidDecl();
1511     return;
1512 
1513   case IsTupleLike::TupleLike:
1514     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515       DD->setInvalidDecl();
1516     return;
1517 
1518   case IsTupleLike::NotTupleLike:
1519     break;
1520   }
1521 
1522   // C++1z [dcl.dcl]/8:
1523   //   [E shall be of array or non-union class type]
1524   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525   if (!RD || RD->isUnion()) {
1526     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527         << DD << !RD << DecompType;
1528     DD->setInvalidDecl();
1529     return;
1530   }
1531 
1532   // C++1z [dcl.decomp]/4:
1533   //   all of E's non-static data members shall be [...] direct members of
1534   //   E or of the same unambiguous public base class of E, ...
1535   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536     DD->setInvalidDecl();
1537 }
1538 
1539 /// Merge the exception specifications of two variable declarations.
1540 ///
1541 /// This is called when there's a redeclaration of a VarDecl. The function
1542 /// checks if the redeclaration might have an exception specification and
1543 /// validates compatibility and merges the specs if necessary.
1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545   // Shortcut if exceptions are disabled.
1546   if (!getLangOpts().CXXExceptions)
1547     return;
1548 
1549   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550          "Should only be called if types are otherwise the same.");
1551 
1552   QualType NewType = New->getType();
1553   QualType OldType = Old->getType();
1554 
1555   // We're only interested in pointers and references to functions, as well
1556   // as pointers to member functions.
1557   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558     NewType = R->getPointeeType();
1559     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561     NewType = P->getPointeeType();
1562     OldType = OldType->castAs<PointerType>()->getPointeeType();
1563   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564     NewType = M->getPointeeType();
1565     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566   }
1567 
1568   if (!NewType->isFunctionProtoType())
1569     return;
1570 
1571   // There's lots of special cases for functions. For function pointers, system
1572   // libraries are hopefully not as broken so that we don't need these
1573   // workarounds.
1574   if (CheckEquivalentExceptionSpec(
1575         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577     New->setInvalidDecl();
1578   }
1579 }
1580 
1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1582 /// function declaration are well-formed according to C++
1583 /// [dcl.fct.default].
1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585   unsigned NumParams = FD->getNumParams();
1586   unsigned ParamIdx = 0;
1587 
1588   // This checking doesn't make sense for explicit specializations; their
1589   // default arguments are determined by the declaration we're specializing,
1590   // not by FD.
1591   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592     return;
1593   if (auto *FTD = FD->getDescribedFunctionTemplate())
1594     if (FTD->isMemberSpecialization())
1595       return;
1596 
1597   // Find first parameter with a default argument
1598   for (; ParamIdx < NumParams; ++ParamIdx) {
1599     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600     if (Param->hasDefaultArg())
1601       break;
1602   }
1603 
1604   // C++20 [dcl.fct.default]p4:
1605   //   In a given function declaration, each parameter subsequent to a parameter
1606   //   with a default argument shall have a default argument supplied in this or
1607   //   a previous declaration, unless the parameter was expanded from a
1608   //   parameter pack, or shall be a function parameter pack.
1609   for (; ParamIdx < NumParams; ++ParamIdx) {
1610     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612         !(CurrentInstantiationScope &&
1613           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614       if (Param->isInvalidDecl())
1615         /* We already complained about this parameter. */;
1616       else if (Param->getIdentifier())
1617         Diag(Param->getLocation(),
1618              diag::err_param_default_argument_missing_name)
1619           << Param->getIdentifier();
1620       else
1621         Diag(Param->getLocation(),
1622              diag::err_param_default_argument_missing);
1623     }
1624   }
1625 }
1626 
1627 /// Check that the given type is a literal type. Issue a diagnostic if not,
1628 /// if Kind is Diagnose.
1629 /// \return \c true if a problem has been found (and optionally diagnosed).
1630 template <typename... Ts>
1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632                              SourceLocation Loc, QualType T, unsigned DiagID,
1633                              Ts &&...DiagArgs) {
1634   if (T->isDependentType())
1635     return false;
1636 
1637   switch (Kind) {
1638   case Sema::CheckConstexprKind::Diagnose:
1639     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640                                       std::forward<Ts>(DiagArgs)...);
1641 
1642   case Sema::CheckConstexprKind::CheckValid:
1643     return !T->isLiteralType(SemaRef.Context);
1644   }
1645 
1646   llvm_unreachable("unknown CheckConstexprKind");
1647 }
1648 
1649 /// Determine whether a destructor cannot be constexpr due to
1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651                                                const CXXDestructorDecl *DD,
1652                                                Sema::CheckConstexprKind Kind) {
1653   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654     const CXXRecordDecl *RD =
1655         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656     if (!RD || RD->hasConstexprDestructor())
1657       return true;
1658 
1659     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661           << static_cast<int>(DD->getConstexprKind()) << !FD
1662           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665     }
1666     return false;
1667   };
1668 
1669   const CXXRecordDecl *RD = DD->getParent();
1670   for (const CXXBaseSpecifier &B : RD->bases())
1671     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672       return false;
1673   for (const FieldDecl *FD : RD->fields())
1674     if (!Check(FD->getLocation(), FD->getType(), FD))
1675       return false;
1676   return true;
1677 }
1678 
1679 /// Check whether a function's parameter types are all literal types. If so,
1680 /// return true. If not, produce a suitable diagnostic and return false.
1681 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682                                          const FunctionDecl *FD,
1683                                          Sema::CheckConstexprKind Kind) {
1684   unsigned ArgIndex = 0;
1685   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687                                               e = FT->param_type_end();
1688        i != e; ++i, ++ArgIndex) {
1689     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690     SourceLocation ParamLoc = PD->getLocation();
1691     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694                          FD->isConsteval()))
1695       return false;
1696   }
1697   return true;
1698 }
1699 
1700 /// Check whether a function's return type is a literal type. If so, return
1701 /// true. If not, produce a suitable diagnostic and return false.
1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703                                      Sema::CheckConstexprKind Kind) {
1704   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705                        diag::err_constexpr_non_literal_return,
1706                        FD->isConsteval()))
1707     return false;
1708   return true;
1709 }
1710 
1711 /// Get diagnostic %select index for tag kind for
1712 /// record diagnostic message.
1713 /// WARNING: Indexes apply to particular diagnostics only!
1714 ///
1715 /// \returns diagnostic %select index.
1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717   switch (Tag) {
1718   case TTK_Struct: return 0;
1719   case TTK_Interface: return 1;
1720   case TTK_Class:  return 2;
1721   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722   }
1723 }
1724 
1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726                                        Stmt *Body,
1727                                        Sema::CheckConstexprKind Kind);
1728 
1729 // Check whether a function declaration satisfies the requirements of a
1730 // constexpr function definition or a constexpr constructor definition. If so,
1731 // return true. If not, produce appropriate diagnostics (unless asked not to by
1732 // Kind) and return false.
1733 //
1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736                                             CheckConstexprKind Kind) {
1737   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738   if (MD && MD->isInstance()) {
1739     // C++11 [dcl.constexpr]p4:
1740     //  The definition of a constexpr constructor shall satisfy the following
1741     //  constraints:
1742     //  - the class shall not have any virtual base classes;
1743     //
1744     // FIXME: This only applies to constructors and destructors, not arbitrary
1745     // member functions.
1746     const CXXRecordDecl *RD = MD->getParent();
1747     if (RD->getNumVBases()) {
1748       if (Kind == CheckConstexprKind::CheckValid)
1749         return false;
1750 
1751       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752         << isa<CXXConstructorDecl>(NewFD)
1753         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754       for (const auto &I : RD->vbases())
1755         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756             << I.getSourceRange();
1757       return false;
1758     }
1759   }
1760 
1761   if (!isa<CXXConstructorDecl>(NewFD)) {
1762     // C++11 [dcl.constexpr]p3:
1763     //  The definition of a constexpr function shall satisfy the following
1764     //  constraints:
1765     // - it shall not be virtual; (removed in C++20)
1766     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767     if (Method && Method->isVirtual()) {
1768       if (getLangOpts().CPlusPlus20) {
1769         if (Kind == CheckConstexprKind::Diagnose)
1770           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771       } else {
1772         if (Kind == CheckConstexprKind::CheckValid)
1773           return false;
1774 
1775         Method = Method->getCanonicalDecl();
1776         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777 
1778         // If it's not obvious why this function is virtual, find an overridden
1779         // function which uses the 'virtual' keyword.
1780         const CXXMethodDecl *WrittenVirtual = Method;
1781         while (!WrittenVirtual->isVirtualAsWritten())
1782           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783         if (WrittenVirtual != Method)
1784           Diag(WrittenVirtual->getLocation(),
1785                diag::note_overridden_virtual_function);
1786         return false;
1787       }
1788     }
1789 
1790     // - its return type shall be a literal type;
1791     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792       return false;
1793   }
1794 
1795   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796     // A destructor can be constexpr only if the defaulted destructor could be;
1797     // we don't need to check the members and bases if we already know they all
1798     // have constexpr destructors.
1799     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800       if (Kind == CheckConstexprKind::CheckValid)
1801         return false;
1802       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803         return false;
1804     }
1805   }
1806 
1807   // - each of its parameter types shall be a literal type;
1808   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809     return false;
1810 
1811   Stmt *Body = NewFD->getBody();
1812   assert(Body &&
1813          "CheckConstexprFunctionDefinition called on function with no body");
1814   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815 }
1816 
1817 /// Check the given declaration statement is legal within a constexpr function
1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819 ///
1820 /// \return true if the body is OK (maybe only as an extension), false if we
1821 ///         have diagnosed a problem.
1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824                                    Sema::CheckConstexprKind Kind) {
1825   // C++11 [dcl.constexpr]p3 and p4:
1826   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827   //  contain only
1828   for (const auto *DclIt : DS->decls()) {
1829     switch (DclIt->getKind()) {
1830     case Decl::StaticAssert:
1831     case Decl::Using:
1832     case Decl::UsingShadow:
1833     case Decl::UsingDirective:
1834     case Decl::UnresolvedUsingTypename:
1835     case Decl::UnresolvedUsingValue:
1836     case Decl::UsingEnum:
1837       //   - static_assert-declarations
1838       //   - using-declarations,
1839       //   - using-directives,
1840       //   - using-enum-declaration
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                          SemaRef.getLangOpts().CPlusPlus2b
1896                              ? diag::warn_cxx20_compat_constexpr_var
1897                              : diag::ext_constexpr_static_var)
1898                 << isa<CXXConstructorDecl>(Dcl)
1899                 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1900           } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1901             return false;
1902           }
1903         }
1904         if (SemaRef.LangOpts.CPlusPlus2b) {
1905           CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1906                            diag::warn_cxx20_compat_constexpr_var,
1907                            isa<CXXConstructorDecl>(Dcl),
1908                            /*variable of non-literal type*/ 2);
1909         } else if (CheckLiteralType(
1910                        SemaRef, Kind, VD->getLocation(), VD->getType(),
1911                        diag::err_constexpr_local_var_non_literal_type,
1912                        isa<CXXConstructorDecl>(Dcl))) {
1913           return false;
1914         }
1915         if (!VD->getType()->isDependentType() &&
1916             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1917           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1918             SemaRef.Diag(
1919                 VD->getLocation(),
1920                 SemaRef.getLangOpts().CPlusPlus20
1921                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1922                     : diag::ext_constexpr_local_var_no_init)
1923                 << isa<CXXConstructorDecl>(Dcl);
1924           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1925             return false;
1926           }
1927           continue;
1928         }
1929       }
1930       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1931         SemaRef.Diag(VD->getLocation(),
1932                      SemaRef.getLangOpts().CPlusPlus14
1933                       ? diag::warn_cxx11_compat_constexpr_local_var
1934                       : diag::ext_constexpr_local_var)
1935           << isa<CXXConstructorDecl>(Dcl);
1936       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1937         return false;
1938       }
1939       continue;
1940     }
1941 
1942     case Decl::NamespaceAlias:
1943     case Decl::Function:
1944       // These are disallowed in C++11 and permitted in C++1y. Allow them
1945       // everywhere as an extension.
1946       if (!Cxx1yLoc.isValid())
1947         Cxx1yLoc = DS->getBeginLoc();
1948       continue;
1949 
1950     default:
1951       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1952         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1953             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1954       }
1955       return false;
1956     }
1957   }
1958 
1959   return true;
1960 }
1961 
1962 /// Check that the given field is initialized within a constexpr constructor.
1963 ///
1964 /// \param Dcl The constexpr constructor being checked.
1965 /// \param Field The field being checked. This may be a member of an anonymous
1966 ///        struct or union nested within the class being checked.
1967 /// \param Inits All declarations, including anonymous struct/union members and
1968 ///        indirect members, for which any initialization was provided.
1969 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1970 ///        multiple notes for different members to the same error.
1971 /// \param Kind Whether we're diagnosing a constructor as written or determining
1972 ///        whether the formal requirements are satisfied.
1973 /// \return \c false if we're checking for validity and the constructor does
1974 ///         not satisfy the requirements on a constexpr constructor.
1975 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1976                                           const FunctionDecl *Dcl,
1977                                           FieldDecl *Field,
1978                                           llvm::SmallSet<Decl*, 16> &Inits,
1979                                           bool &Diagnosed,
1980                                           Sema::CheckConstexprKind Kind) {
1981   // In C++20 onwards, there's nothing to check for validity.
1982   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1983       SemaRef.getLangOpts().CPlusPlus20)
1984     return true;
1985 
1986   if (Field->isInvalidDecl())
1987     return true;
1988 
1989   if (Field->isUnnamedBitfield())
1990     return true;
1991 
1992   // Anonymous unions with no variant members and empty anonymous structs do not
1993   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1994   // indirect fields don't need initializing.
1995   if (Field->isAnonymousStructOrUnion() &&
1996       (Field->getType()->isUnionType()
1997            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1998            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1999     return true;
2000 
2001   if (!Inits.count(Field)) {
2002     if (Kind == Sema::CheckConstexprKind::Diagnose) {
2003       if (!Diagnosed) {
2004         SemaRef.Diag(Dcl->getLocation(),
2005                      SemaRef.getLangOpts().CPlusPlus20
2006                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2007                          : diag::ext_constexpr_ctor_missing_init);
2008         Diagnosed = true;
2009       }
2010       SemaRef.Diag(Field->getLocation(),
2011                    diag::note_constexpr_ctor_missing_init);
2012     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2013       return false;
2014     }
2015   } else if (Field->isAnonymousStructOrUnion()) {
2016     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2017     for (auto *I : RD->fields())
2018       // If an anonymous union contains an anonymous struct of which any member
2019       // is initialized, all members must be initialized.
2020       if (!RD->isUnion() || Inits.count(I))
2021         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2022                                            Kind))
2023           return false;
2024   }
2025   return true;
2026 }
2027 
2028 /// Check the provided statement is allowed in a constexpr function
2029 /// definition.
2030 static bool
2031 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2032                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2033                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2034                            SourceLocation &Cxx2bLoc,
2035                            Sema::CheckConstexprKind Kind) {
2036   // - its function-body shall be [...] a compound-statement that contains only
2037   switch (S->getStmtClass()) {
2038   case Stmt::NullStmtClass:
2039     //   - null statements,
2040     return true;
2041 
2042   case Stmt::DeclStmtClass:
2043     //   - static_assert-declarations
2044     //   - using-declarations,
2045     //   - using-directives,
2046     //   - typedef declarations and alias-declarations that do not define
2047     //     classes or enumerations,
2048     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2049       return false;
2050     return true;
2051 
2052   case Stmt::ReturnStmtClass:
2053     //   - and exactly one return statement;
2054     if (isa<CXXConstructorDecl>(Dcl)) {
2055       // C++1y allows return statements in constexpr constructors.
2056       if (!Cxx1yLoc.isValid())
2057         Cxx1yLoc = S->getBeginLoc();
2058       return true;
2059     }
2060 
2061     ReturnStmts.push_back(S->getBeginLoc());
2062     return true;
2063 
2064   case Stmt::AttributedStmtClass:
2065     // Attributes on a statement don't affect its formal kind and hence don't
2066     // affect its validity in a constexpr function.
2067     return CheckConstexprFunctionStmt(
2068         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2069         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2070 
2071   case Stmt::CompoundStmtClass: {
2072     // C++1y allows compound-statements.
2073     if (!Cxx1yLoc.isValid())
2074       Cxx1yLoc = S->getBeginLoc();
2075 
2076     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2077     for (auto *BodyIt : CompStmt->body()) {
2078       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2079                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2080         return false;
2081     }
2082     return true;
2083   }
2084 
2085   case Stmt::IfStmtClass: {
2086     // C++1y allows if-statements.
2087     if (!Cxx1yLoc.isValid())
2088       Cxx1yLoc = S->getBeginLoc();
2089 
2090     IfStmt *If = cast<IfStmt>(S);
2091     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2092                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2093       return false;
2094     if (If->getElse() &&
2095         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2096                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2097       return false;
2098     return true;
2099   }
2100 
2101   case Stmt::WhileStmtClass:
2102   case Stmt::DoStmtClass:
2103   case Stmt::ForStmtClass:
2104   case Stmt::CXXForRangeStmtClass:
2105   case Stmt::ContinueStmtClass:
2106     // C++1y allows all of these. We don't allow them as extensions in C++11,
2107     // because they don't make sense without variable mutation.
2108     if (!SemaRef.getLangOpts().CPlusPlus14)
2109       break;
2110     if (!Cxx1yLoc.isValid())
2111       Cxx1yLoc = S->getBeginLoc();
2112     for (Stmt *SubStmt : S->children()) {
2113       if (SubStmt &&
2114           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2115                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2116         return false;
2117     }
2118     return true;
2119 
2120   case Stmt::SwitchStmtClass:
2121   case Stmt::CaseStmtClass:
2122   case Stmt::DefaultStmtClass:
2123   case Stmt::BreakStmtClass:
2124     // C++1y allows switch-statements, and since they don't need variable
2125     // mutation, we can reasonably allow them in C++11 as an extension.
2126     if (!Cxx1yLoc.isValid())
2127       Cxx1yLoc = S->getBeginLoc();
2128     for (Stmt *SubStmt : S->children()) {
2129       if (SubStmt &&
2130           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2131                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2132         return false;
2133     }
2134     return true;
2135 
2136   case Stmt::LabelStmtClass:
2137   case Stmt::GotoStmtClass:
2138     if (Cxx2bLoc.isInvalid())
2139       Cxx2bLoc = S->getBeginLoc();
2140     for (Stmt *SubStmt : S->children()) {
2141       if (SubStmt &&
2142           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2143                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2144         return false;
2145     }
2146     return true;
2147 
2148   case Stmt::GCCAsmStmtClass:
2149   case Stmt::MSAsmStmtClass:
2150     // C++2a allows inline assembly statements.
2151   case Stmt::CXXTryStmtClass:
2152     if (Cxx2aLoc.isInvalid())
2153       Cxx2aLoc = S->getBeginLoc();
2154     for (Stmt *SubStmt : S->children()) {
2155       if (SubStmt &&
2156           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2157                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2158         return false;
2159     }
2160     return true;
2161 
2162   case Stmt::CXXCatchStmtClass:
2163     // Do not bother checking the language mode (already covered by the
2164     // try block check).
2165     if (!CheckConstexprFunctionStmt(
2166             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2167             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2168       return false;
2169     return true;
2170 
2171   default:
2172     if (!isa<Expr>(S))
2173       break;
2174 
2175     // C++1y allows expression-statements.
2176     if (!Cxx1yLoc.isValid())
2177       Cxx1yLoc = S->getBeginLoc();
2178     return true;
2179   }
2180 
2181   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2182     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2183         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2184   }
2185   return false;
2186 }
2187 
2188 /// Check the body for the given constexpr function declaration only contains
2189 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2190 ///
2191 /// \return true if the body is OK, false if we have found or diagnosed a
2192 /// problem.
2193 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2194                                        Stmt *Body,
2195                                        Sema::CheckConstexprKind Kind) {
2196   SmallVector<SourceLocation, 4> ReturnStmts;
2197 
2198   if (isa<CXXTryStmt>(Body)) {
2199     // C++11 [dcl.constexpr]p3:
2200     //  The definition of a constexpr function shall satisfy the following
2201     //  constraints: [...]
2202     // - its function-body shall be = delete, = default, or a
2203     //   compound-statement
2204     //
2205     // C++11 [dcl.constexpr]p4:
2206     //  In the definition of a constexpr constructor, [...]
2207     // - its function-body shall not be a function-try-block;
2208     //
2209     // This restriction is lifted in C++2a, as long as inner statements also
2210     // apply the general constexpr rules.
2211     switch (Kind) {
2212     case Sema::CheckConstexprKind::CheckValid:
2213       if (!SemaRef.getLangOpts().CPlusPlus20)
2214         return false;
2215       break;
2216 
2217     case Sema::CheckConstexprKind::Diagnose:
2218       SemaRef.Diag(Body->getBeginLoc(),
2219            !SemaRef.getLangOpts().CPlusPlus20
2220                ? diag::ext_constexpr_function_try_block_cxx20
2221                : diag::warn_cxx17_compat_constexpr_function_try_block)
2222           << isa<CXXConstructorDecl>(Dcl);
2223       break;
2224     }
2225   }
2226 
2227   // - its function-body shall be [...] a compound-statement that contains only
2228   //   [... list of cases ...]
2229   //
2230   // Note that walking the children here is enough to properly check for
2231   // CompoundStmt and CXXTryStmt body.
2232   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2233   for (Stmt *SubStmt : Body->children()) {
2234     if (SubStmt &&
2235         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2236                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2237       return false;
2238   }
2239 
2240   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2241     // If this is only valid as an extension, report that we don't satisfy the
2242     // constraints of the current language.
2243     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2244         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2245         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2246       return false;
2247   } else if (Cxx2bLoc.isValid()) {
2248     SemaRef.Diag(Cxx2bLoc,
2249                  SemaRef.getLangOpts().CPlusPlus2b
2250                      ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2251                      : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2252         << isa<CXXConstructorDecl>(Dcl);
2253   } else if (Cxx2aLoc.isValid()) {
2254     SemaRef.Diag(Cxx2aLoc,
2255          SemaRef.getLangOpts().CPlusPlus20
2256            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2257            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2258       << isa<CXXConstructorDecl>(Dcl);
2259   } else if (Cxx1yLoc.isValid()) {
2260     SemaRef.Diag(Cxx1yLoc,
2261          SemaRef.getLangOpts().CPlusPlus14
2262            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2263            : diag::ext_constexpr_body_invalid_stmt)
2264       << isa<CXXConstructorDecl>(Dcl);
2265   }
2266 
2267   if (const CXXConstructorDecl *Constructor
2268         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2269     const CXXRecordDecl *RD = Constructor->getParent();
2270     // DR1359:
2271     // - every non-variant non-static data member and base class sub-object
2272     //   shall be initialized;
2273     // DR1460:
2274     // - if the class is a union having variant members, exactly one of them
2275     //   shall be initialized;
2276     if (RD->isUnion()) {
2277       if (Constructor->getNumCtorInitializers() == 0 &&
2278           RD->hasVariantMembers()) {
2279         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2280           SemaRef.Diag(
2281               Dcl->getLocation(),
2282               SemaRef.getLangOpts().CPlusPlus20
2283                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2284                   : diag::ext_constexpr_union_ctor_no_init);
2285         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2286           return false;
2287         }
2288       }
2289     } else if (!Constructor->isDependentContext() &&
2290                !Constructor->isDelegatingConstructor()) {
2291       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2292 
2293       // Skip detailed checking if we have enough initializers, and we would
2294       // allow at most one initializer per member.
2295       bool AnyAnonStructUnionMembers = false;
2296       unsigned Fields = 0;
2297       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2298            E = RD->field_end(); I != E; ++I, ++Fields) {
2299         if (I->isAnonymousStructOrUnion()) {
2300           AnyAnonStructUnionMembers = true;
2301           break;
2302         }
2303       }
2304       // DR1460:
2305       // - if the class is a union-like class, but is not a union, for each of
2306       //   its anonymous union members having variant members, exactly one of
2307       //   them shall be initialized;
2308       if (AnyAnonStructUnionMembers ||
2309           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2310         // Check initialization of non-static data members. Base classes are
2311         // always initialized so do not need to be checked. Dependent bases
2312         // might not have initializers in the member initializer list.
2313         llvm::SmallSet<Decl*, 16> Inits;
2314         for (const auto *I: Constructor->inits()) {
2315           if (FieldDecl *FD = I->getMember())
2316             Inits.insert(FD);
2317           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2318             Inits.insert(ID->chain_begin(), ID->chain_end());
2319         }
2320 
2321         bool Diagnosed = false;
2322         for (auto *I : RD->fields())
2323           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2324                                              Kind))
2325             return false;
2326       }
2327     }
2328   } else {
2329     if (ReturnStmts.empty()) {
2330       // C++1y doesn't require constexpr functions to contain a 'return'
2331       // statement. We still do, unless the return type might be void, because
2332       // otherwise if there's no return statement, the function cannot
2333       // be used in a core constant expression.
2334       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2335                 (Dcl->getReturnType()->isVoidType() ||
2336                  Dcl->getReturnType()->isDependentType());
2337       switch (Kind) {
2338       case Sema::CheckConstexprKind::Diagnose:
2339         SemaRef.Diag(Dcl->getLocation(),
2340                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2341                         : diag::err_constexpr_body_no_return)
2342             << Dcl->isConsteval();
2343         if (!OK)
2344           return false;
2345         break;
2346 
2347       case Sema::CheckConstexprKind::CheckValid:
2348         // The formal requirements don't include this rule in C++14, even
2349         // though the "must be able to produce a constant expression" rules
2350         // still imply it in some cases.
2351         if (!SemaRef.getLangOpts().CPlusPlus14)
2352           return false;
2353         break;
2354       }
2355     } else if (ReturnStmts.size() > 1) {
2356       switch (Kind) {
2357       case Sema::CheckConstexprKind::Diagnose:
2358         SemaRef.Diag(
2359             ReturnStmts.back(),
2360             SemaRef.getLangOpts().CPlusPlus14
2361                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2362                 : diag::ext_constexpr_body_multiple_return);
2363         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2364           SemaRef.Diag(ReturnStmts[I],
2365                        diag::note_constexpr_body_previous_return);
2366         break;
2367 
2368       case Sema::CheckConstexprKind::CheckValid:
2369         if (!SemaRef.getLangOpts().CPlusPlus14)
2370           return false;
2371         break;
2372       }
2373     }
2374   }
2375 
2376   // C++11 [dcl.constexpr]p5:
2377   //   if no function argument values exist such that the function invocation
2378   //   substitution would produce a constant expression, the program is
2379   //   ill-formed; no diagnostic required.
2380   // C++11 [dcl.constexpr]p3:
2381   //   - every constructor call and implicit conversion used in initializing the
2382   //     return value shall be one of those allowed in a constant expression.
2383   // C++11 [dcl.constexpr]p4:
2384   //   - every constructor involved in initializing non-static data members and
2385   //     base class sub-objects shall be a constexpr constructor.
2386   //
2387   // Note that this rule is distinct from the "requirements for a constexpr
2388   // function", so is not checked in CheckValid mode.
2389   SmallVector<PartialDiagnosticAt, 8> Diags;
2390   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2391       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2392     SemaRef.Diag(Dcl->getLocation(),
2393                  diag::ext_constexpr_function_never_constant_expr)
2394         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2395     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2396       SemaRef.Diag(Diags[I].first, Diags[I].second);
2397     // Don't return false here: we allow this for compatibility in
2398     // system headers.
2399   }
2400 
2401   return true;
2402 }
2403 
2404 /// Get the class that is directly named by the current context. This is the
2405 /// class for which an unqualified-id in this scope could name a constructor
2406 /// or destructor.
2407 ///
2408 /// If the scope specifier denotes a class, this will be that class.
2409 /// If the scope specifier is empty, this will be the class whose
2410 /// member-specification we are currently within. Otherwise, there
2411 /// is no such class.
2412 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2413   assert(getLangOpts().CPlusPlus && "No class names in C!");
2414 
2415   if (SS && SS->isInvalid())
2416     return nullptr;
2417 
2418   if (SS && SS->isNotEmpty()) {
2419     DeclContext *DC = computeDeclContext(*SS, true);
2420     return dyn_cast_or_null<CXXRecordDecl>(DC);
2421   }
2422 
2423   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2424 }
2425 
2426 /// isCurrentClassName - Determine whether the identifier II is the
2427 /// name of the class type currently being defined. In the case of
2428 /// nested classes, this will only return true if II is the name of
2429 /// the innermost class.
2430 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2431                               const CXXScopeSpec *SS) {
2432   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2433   return CurDecl && &II == CurDecl->getIdentifier();
2434 }
2435 
2436 /// Determine whether the identifier II is a typo for the name of
2437 /// the class type currently being defined. If so, update it to the identifier
2438 /// that should have been used.
2439 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2440   assert(getLangOpts().CPlusPlus && "No class names in C!");
2441 
2442   if (!getLangOpts().SpellChecking)
2443     return false;
2444 
2445   CXXRecordDecl *CurDecl;
2446   if (SS && SS->isSet() && !SS->isInvalid()) {
2447     DeclContext *DC = computeDeclContext(*SS, true);
2448     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2449   } else
2450     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2451 
2452   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2453       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2454           < II->getLength()) {
2455     II = CurDecl->getIdentifier();
2456     return true;
2457   }
2458 
2459   return false;
2460 }
2461 
2462 /// Determine whether the given class is a base class of the given
2463 /// class, including looking at dependent bases.
2464 static bool findCircularInheritance(const CXXRecordDecl *Class,
2465                                     const CXXRecordDecl *Current) {
2466   SmallVector<const CXXRecordDecl*, 8> Queue;
2467 
2468   Class = Class->getCanonicalDecl();
2469   while (true) {
2470     for (const auto &I : Current->bases()) {
2471       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2472       if (!Base)
2473         continue;
2474 
2475       Base = Base->getDefinition();
2476       if (!Base)
2477         continue;
2478 
2479       if (Base->getCanonicalDecl() == Class)
2480         return true;
2481 
2482       Queue.push_back(Base);
2483     }
2484 
2485     if (Queue.empty())
2486       return false;
2487 
2488     Current = Queue.pop_back_val();
2489   }
2490 
2491   return false;
2492 }
2493 
2494 /// Check the validity of a C++ base class specifier.
2495 ///
2496 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2497 /// and returns NULL otherwise.
2498 CXXBaseSpecifier *
2499 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2500                          SourceRange SpecifierRange,
2501                          bool Virtual, AccessSpecifier Access,
2502                          TypeSourceInfo *TInfo,
2503                          SourceLocation EllipsisLoc) {
2504   // In HLSL, unspecified class access is public rather than private.
2505   if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2506       Access == AS_none)
2507     Access = AS_public;
2508 
2509   QualType BaseType = TInfo->getType();
2510   if (BaseType->containsErrors()) {
2511     // Already emitted a diagnostic when parsing the error type.
2512     return nullptr;
2513   }
2514   // C++ [class.union]p1:
2515   //   A union shall not have base classes.
2516   if (Class->isUnion()) {
2517     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2518       << SpecifierRange;
2519     return nullptr;
2520   }
2521 
2522   if (EllipsisLoc.isValid() &&
2523       !TInfo->getType()->containsUnexpandedParameterPack()) {
2524     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2525       << TInfo->getTypeLoc().getSourceRange();
2526     EllipsisLoc = SourceLocation();
2527   }
2528 
2529   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2530 
2531   if (BaseType->isDependentType()) {
2532     // Make sure that we don't have circular inheritance among our dependent
2533     // bases. For non-dependent bases, the check for completeness below handles
2534     // this.
2535     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2536       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2537           ((BaseDecl = BaseDecl->getDefinition()) &&
2538            findCircularInheritance(Class, BaseDecl))) {
2539         Diag(BaseLoc, diag::err_circular_inheritance)
2540           << BaseType << Context.getTypeDeclType(Class);
2541 
2542         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2543           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2544             << BaseType;
2545 
2546         return nullptr;
2547       }
2548     }
2549 
2550     // Make sure that we don't make an ill-formed AST where the type of the
2551     // Class is non-dependent and its attached base class specifier is an
2552     // dependent type, which violates invariants in many clang code paths (e.g.
2553     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2554     // explicitly mark the Class decl invalid. The diagnostic was already
2555     // emitted.
2556     if (!Class->getTypeForDecl()->isDependentType())
2557       Class->setInvalidDecl();
2558     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2559                                           Class->getTagKind() == TTK_Class,
2560                                           Access, TInfo, EllipsisLoc);
2561   }
2562 
2563   // Base specifiers must be record types.
2564   if (!BaseType->isRecordType()) {
2565     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2566     return nullptr;
2567   }
2568 
2569   // C++ [class.union]p1:
2570   //   A union shall not be used as a base class.
2571   if (BaseType->isUnionType()) {
2572     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2573     return nullptr;
2574   }
2575 
2576   // For the MS ABI, propagate DLL attributes to base class templates.
2577   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2578     if (Attr *ClassAttr = getDLLAttr(Class)) {
2579       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2580               BaseType->getAsCXXRecordDecl())) {
2581         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2582                                             BaseLoc);
2583       }
2584     }
2585   }
2586 
2587   // C++ [class.derived]p2:
2588   //   The class-name in a base-specifier shall not be an incompletely
2589   //   defined class.
2590   if (RequireCompleteType(BaseLoc, BaseType,
2591                           diag::err_incomplete_base_class, SpecifierRange)) {
2592     Class->setInvalidDecl();
2593     return nullptr;
2594   }
2595 
2596   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2597   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2598   assert(BaseDecl && "Record type has no declaration");
2599   BaseDecl = BaseDecl->getDefinition();
2600   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2601   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2602   assert(CXXBaseDecl && "Base type is not a C++ type");
2603 
2604   // Microsoft docs say:
2605   // "If a base-class has a code_seg attribute, derived classes must have the
2606   // same attribute."
2607   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2608   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2609   if ((DerivedCSA || BaseCSA) &&
2610       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2611     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2612     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2613       << CXXBaseDecl;
2614     return nullptr;
2615   }
2616 
2617   // A class which contains a flexible array member is not suitable for use as a
2618   // base class:
2619   //   - If the layout determines that a base comes before another base,
2620   //     the flexible array member would index into the subsequent base.
2621   //   - If the layout determines that base comes before the derived class,
2622   //     the flexible array member would index into the derived class.
2623   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2624     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2625       << CXXBaseDecl->getDeclName();
2626     return nullptr;
2627   }
2628 
2629   // C++ [class]p3:
2630   //   If a class is marked final and it appears as a base-type-specifier in
2631   //   base-clause, the program is ill-formed.
2632   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2633     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2634       << CXXBaseDecl->getDeclName()
2635       << FA->isSpelledAsSealed();
2636     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2637         << CXXBaseDecl->getDeclName() << FA->getRange();
2638     return nullptr;
2639   }
2640 
2641   if (BaseDecl->isInvalidDecl())
2642     Class->setInvalidDecl();
2643 
2644   // Create the base specifier.
2645   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2646                                         Class->getTagKind() == TTK_Class,
2647                                         Access, TInfo, EllipsisLoc);
2648 }
2649 
2650 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2651 /// one entry in the base class list of a class specifier, for
2652 /// example:
2653 ///    class foo : public bar, virtual private baz {
2654 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2655 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2656                                     const ParsedAttributesView &Attributes,
2657                                     bool Virtual, AccessSpecifier Access,
2658                                     ParsedType basetype, SourceLocation BaseLoc,
2659                                     SourceLocation EllipsisLoc) {
2660   if (!classdecl)
2661     return true;
2662 
2663   AdjustDeclIfTemplate(classdecl);
2664   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2665   if (!Class)
2666     return true;
2667 
2668   // We haven't yet attached the base specifiers.
2669   Class->setIsParsingBaseSpecifiers();
2670 
2671   // We do not support any C++11 attributes on base-specifiers yet.
2672   // Diagnose any attributes we see.
2673   for (const ParsedAttr &AL : Attributes) {
2674     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2675       continue;
2676     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2677                           ? (unsigned)diag::warn_unknown_attribute_ignored
2678                           : (unsigned)diag::err_base_specifier_attribute)
2679         << AL << AL.getRange();
2680   }
2681 
2682   TypeSourceInfo *TInfo = nullptr;
2683   GetTypeFromParser(basetype, &TInfo);
2684 
2685   if (EllipsisLoc.isInvalid() &&
2686       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2687                                       UPPC_BaseType))
2688     return true;
2689 
2690   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2691                                                       Virtual, Access, TInfo,
2692                                                       EllipsisLoc))
2693     return BaseSpec;
2694   else
2695     Class->setInvalidDecl();
2696 
2697   return true;
2698 }
2699 
2700 /// Use small set to collect indirect bases.  As this is only used
2701 /// locally, there's no need to abstract the small size parameter.
2702 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2703 
2704 /// Recursively add the bases of Type.  Don't add Type itself.
2705 static void
2706 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2707                   const QualType &Type)
2708 {
2709   // Even though the incoming type is a base, it might not be
2710   // a class -- it could be a template parm, for instance.
2711   if (auto Rec = Type->getAs<RecordType>()) {
2712     auto Decl = Rec->getAsCXXRecordDecl();
2713 
2714     // Iterate over its bases.
2715     for (const auto &BaseSpec : Decl->bases()) {
2716       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2717         .getUnqualifiedType();
2718       if (Set.insert(Base).second)
2719         // If we've not already seen it, recurse.
2720         NoteIndirectBases(Context, Set, Base);
2721     }
2722   }
2723 }
2724 
2725 /// Performs the actual work of attaching the given base class
2726 /// specifiers to a C++ class.
2727 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2728                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2729  if (Bases.empty())
2730     return false;
2731 
2732   // Used to keep track of which base types we have already seen, so
2733   // that we can properly diagnose redundant direct base types. Note
2734   // that the key is always the unqualified canonical type of the base
2735   // class.
2736   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2737 
2738   // Used to track indirect bases so we can see if a direct base is
2739   // ambiguous.
2740   IndirectBaseSet IndirectBaseTypes;
2741 
2742   // Copy non-redundant base specifiers into permanent storage.
2743   unsigned NumGoodBases = 0;
2744   bool Invalid = false;
2745   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2746     QualType NewBaseType
2747       = Context.getCanonicalType(Bases[idx]->getType());
2748     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2749 
2750     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2751     if (KnownBase) {
2752       // C++ [class.mi]p3:
2753       //   A class shall not be specified as a direct base class of a
2754       //   derived class more than once.
2755       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2756           << KnownBase->getType() << Bases[idx]->getSourceRange();
2757 
2758       // Delete the duplicate base class specifier; we're going to
2759       // overwrite its pointer later.
2760       Context.Deallocate(Bases[idx]);
2761 
2762       Invalid = true;
2763     } else {
2764       // Okay, add this new base class.
2765       KnownBase = Bases[idx];
2766       Bases[NumGoodBases++] = Bases[idx];
2767 
2768       if (NewBaseType->isDependentType())
2769         continue;
2770       // Note this base's direct & indirect bases, if there could be ambiguity.
2771       if (Bases.size() > 1)
2772         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2773 
2774       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2775         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2776         if (Class->isInterface() &&
2777               (!RD->isInterfaceLike() ||
2778                KnownBase->getAccessSpecifier() != AS_public)) {
2779           // The Microsoft extension __interface does not permit bases that
2780           // are not themselves public interfaces.
2781           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2782               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2783               << RD->getSourceRange();
2784           Invalid = true;
2785         }
2786         if (RD->hasAttr<WeakAttr>())
2787           Class->addAttr(WeakAttr::CreateImplicit(Context));
2788       }
2789     }
2790   }
2791 
2792   // Attach the remaining base class specifiers to the derived class.
2793   Class->setBases(Bases.data(), NumGoodBases);
2794 
2795   // Check that the only base classes that are duplicate are virtual.
2796   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2797     // Check whether this direct base is inaccessible due to ambiguity.
2798     QualType BaseType = Bases[idx]->getType();
2799 
2800     // Skip all dependent types in templates being used as base specifiers.
2801     // Checks below assume that the base specifier is a CXXRecord.
2802     if (BaseType->isDependentType())
2803       continue;
2804 
2805     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2806       .getUnqualifiedType();
2807 
2808     if (IndirectBaseTypes.count(CanonicalBase)) {
2809       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2810                          /*DetectVirtual=*/true);
2811       bool found
2812         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2813       assert(found);
2814       (void)found;
2815 
2816       if (Paths.isAmbiguous(CanonicalBase))
2817         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2818             << BaseType << getAmbiguousPathsDisplayString(Paths)
2819             << Bases[idx]->getSourceRange();
2820       else
2821         assert(Bases[idx]->isVirtual());
2822     }
2823 
2824     // Delete the base class specifier, since its data has been copied
2825     // into the CXXRecordDecl.
2826     Context.Deallocate(Bases[idx]);
2827   }
2828 
2829   return Invalid;
2830 }
2831 
2832 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2833 /// class, after checking whether there are any duplicate base
2834 /// classes.
2835 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2836                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2837   if (!ClassDecl || Bases.empty())
2838     return;
2839 
2840   AdjustDeclIfTemplate(ClassDecl);
2841   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2842 }
2843 
2844 /// Determine whether the type \p Derived is a C++ class that is
2845 /// derived from the type \p Base.
2846 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2847   if (!getLangOpts().CPlusPlus)
2848     return false;
2849 
2850   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2851   if (!DerivedRD)
2852     return false;
2853 
2854   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2855   if (!BaseRD)
2856     return false;
2857 
2858   // If either the base or the derived type is invalid, don't try to
2859   // check whether one is derived from the other.
2860   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2861     return false;
2862 
2863   // FIXME: In a modules build, do we need the entire path to be visible for us
2864   // to be able to use the inheritance relationship?
2865   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2866     return false;
2867 
2868   return DerivedRD->isDerivedFrom(BaseRD);
2869 }
2870 
2871 /// Determine whether the type \p Derived is a C++ class that is
2872 /// derived from the type \p Base.
2873 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2874                          CXXBasePaths &Paths) {
2875   if (!getLangOpts().CPlusPlus)
2876     return false;
2877 
2878   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2879   if (!DerivedRD)
2880     return false;
2881 
2882   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2883   if (!BaseRD)
2884     return false;
2885 
2886   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2887     return false;
2888 
2889   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2890 }
2891 
2892 static void BuildBasePathArray(const CXXBasePath &Path,
2893                                CXXCastPath &BasePathArray) {
2894   // We first go backward and check if we have a virtual base.
2895   // FIXME: It would be better if CXXBasePath had the base specifier for
2896   // the nearest virtual base.
2897   unsigned Start = 0;
2898   for (unsigned I = Path.size(); I != 0; --I) {
2899     if (Path[I - 1].Base->isVirtual()) {
2900       Start = I - 1;
2901       break;
2902     }
2903   }
2904 
2905   // Now add all bases.
2906   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2907     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2908 }
2909 
2910 
2911 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2912                               CXXCastPath &BasePathArray) {
2913   assert(BasePathArray.empty() && "Base path array must be empty!");
2914   assert(Paths.isRecordingPaths() && "Must record paths!");
2915   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2916 }
2917 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2918 /// conversion (where Derived and Base are class types) is
2919 /// well-formed, meaning that the conversion is unambiguous (and
2920 /// that all of the base classes are accessible). Returns true
2921 /// and emits a diagnostic if the code is ill-formed, returns false
2922 /// otherwise. Loc is the location where this routine should point to
2923 /// if there is an error, and Range is the source range to highlight
2924 /// if there is an error.
2925 ///
2926 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2927 /// diagnostic for the respective type of error will be suppressed, but the
2928 /// check for ill-formed code will still be performed.
2929 bool
2930 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2931                                    unsigned InaccessibleBaseID,
2932                                    unsigned AmbiguousBaseConvID,
2933                                    SourceLocation Loc, SourceRange Range,
2934                                    DeclarationName Name,
2935                                    CXXCastPath *BasePath,
2936                                    bool IgnoreAccess) {
2937   // First, determine whether the path from Derived to Base is
2938   // ambiguous. This is slightly more expensive than checking whether
2939   // the Derived to Base conversion exists, because here we need to
2940   // explore multiple paths to determine if there is an ambiguity.
2941   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2942                      /*DetectVirtual=*/false);
2943   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2944   if (!DerivationOkay)
2945     return true;
2946 
2947   const CXXBasePath *Path = nullptr;
2948   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2949     Path = &Paths.front();
2950 
2951   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2952   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2953   // user to access such bases.
2954   if (!Path && getLangOpts().MSVCCompat) {
2955     for (const CXXBasePath &PossiblePath : Paths) {
2956       if (PossiblePath.size() == 1) {
2957         Path = &PossiblePath;
2958         if (AmbiguousBaseConvID)
2959           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2960               << Base << Derived << Range;
2961         break;
2962       }
2963     }
2964   }
2965 
2966   if (Path) {
2967     if (!IgnoreAccess) {
2968       // Check that the base class can be accessed.
2969       switch (
2970           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2971       case AR_inaccessible:
2972         return true;
2973       case AR_accessible:
2974       case AR_dependent:
2975       case AR_delayed:
2976         break;
2977       }
2978     }
2979 
2980     // Build a base path if necessary.
2981     if (BasePath)
2982       ::BuildBasePathArray(*Path, *BasePath);
2983     return false;
2984   }
2985 
2986   if (AmbiguousBaseConvID) {
2987     // We know that the derived-to-base conversion is ambiguous, and
2988     // we're going to produce a diagnostic. Perform the derived-to-base
2989     // search just one more time to compute all of the possible paths so
2990     // that we can print them out. This is more expensive than any of
2991     // the previous derived-to-base checks we've done, but at this point
2992     // performance isn't as much of an issue.
2993     Paths.clear();
2994     Paths.setRecordingPaths(true);
2995     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2996     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2997     (void)StillOkay;
2998 
2999     // Build up a textual representation of the ambiguous paths, e.g.,
3000     // D -> B -> A, that will be used to illustrate the ambiguous
3001     // conversions in the diagnostic. We only print one of the paths
3002     // to each base class subobject.
3003     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3004 
3005     Diag(Loc, AmbiguousBaseConvID)
3006     << Derived << Base << PathDisplayStr << Range << Name;
3007   }
3008   return true;
3009 }
3010 
3011 bool
3012 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3013                                    SourceLocation Loc, SourceRange Range,
3014                                    CXXCastPath *BasePath,
3015                                    bool IgnoreAccess) {
3016   return CheckDerivedToBaseConversion(
3017       Derived, Base, diag::err_upcast_to_inaccessible_base,
3018       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3019       BasePath, IgnoreAccess);
3020 }
3021 
3022 
3023 /// Builds a string representing ambiguous paths from a
3024 /// specific derived class to different subobjects of the same base
3025 /// class.
3026 ///
3027 /// This function builds a string that can be used in error messages
3028 /// to show the different paths that one can take through the
3029 /// inheritance hierarchy to go from the derived class to different
3030 /// subobjects of a base class. The result looks something like this:
3031 /// @code
3032 /// struct D -> struct B -> struct A
3033 /// struct D -> struct C -> struct A
3034 /// @endcode
3035 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3036   std::string PathDisplayStr;
3037   std::set<unsigned> DisplayedPaths;
3038   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3039        Path != Paths.end(); ++Path) {
3040     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3041       // We haven't displayed a path to this particular base
3042       // class subobject yet.
3043       PathDisplayStr += "\n    ";
3044       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3045       for (CXXBasePath::const_iterator Element = Path->begin();
3046            Element != Path->end(); ++Element)
3047         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3048     }
3049   }
3050 
3051   return PathDisplayStr;
3052 }
3053 
3054 //===----------------------------------------------------------------------===//
3055 // C++ class member Handling
3056 //===----------------------------------------------------------------------===//
3057 
3058 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3059 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3060                                 SourceLocation ColonLoc,
3061                                 const ParsedAttributesView &Attrs) {
3062   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3063   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3064                                                   ASLoc, ColonLoc);
3065   CurContext->addHiddenDecl(ASDecl);
3066   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3067 }
3068 
3069 /// CheckOverrideControl - Check C++11 override control semantics.
3070 void Sema::CheckOverrideControl(NamedDecl *D) {
3071   if (D->isInvalidDecl())
3072     return;
3073 
3074   // We only care about "override" and "final" declarations.
3075   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3076     return;
3077 
3078   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3079 
3080   // We can't check dependent instance methods.
3081   if (MD && MD->isInstance() &&
3082       (MD->getParent()->hasAnyDependentBases() ||
3083        MD->getType()->isDependentType()))
3084     return;
3085 
3086   if (MD && !MD->isVirtual()) {
3087     // If we have a non-virtual method, check if if hides a virtual method.
3088     // (In that case, it's most likely the method has the wrong type.)
3089     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3090     FindHiddenVirtualMethods(MD, OverloadedMethods);
3091 
3092     if (!OverloadedMethods.empty()) {
3093       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3094         Diag(OA->getLocation(),
3095              diag::override_keyword_hides_virtual_member_function)
3096           << "override" << (OverloadedMethods.size() > 1);
3097       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3098         Diag(FA->getLocation(),
3099              diag::override_keyword_hides_virtual_member_function)
3100           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3101           << (OverloadedMethods.size() > 1);
3102       }
3103       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3104       MD->setInvalidDecl();
3105       return;
3106     }
3107     // Fall through into the general case diagnostic.
3108     // FIXME: We might want to attempt typo correction here.
3109   }
3110 
3111   if (!MD || !MD->isVirtual()) {
3112     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3113       Diag(OA->getLocation(),
3114            diag::override_keyword_only_allowed_on_virtual_member_functions)
3115         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3116       D->dropAttr<OverrideAttr>();
3117     }
3118     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3119       Diag(FA->getLocation(),
3120            diag::override_keyword_only_allowed_on_virtual_member_functions)
3121         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3122         << FixItHint::CreateRemoval(FA->getLocation());
3123       D->dropAttr<FinalAttr>();
3124     }
3125     return;
3126   }
3127 
3128   // C++11 [class.virtual]p5:
3129   //   If a function is marked with the virt-specifier override and
3130   //   does not override a member function of a base class, the program is
3131   //   ill-formed.
3132   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3133   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3134     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3135       << MD->getDeclName();
3136 }
3137 
3138 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3139   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3140     return;
3141   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3142   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3143     return;
3144 
3145   SourceLocation Loc = MD->getLocation();
3146   SourceLocation SpellingLoc = Loc;
3147   if (getSourceManager().isMacroArgExpansion(Loc))
3148     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3149   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3150   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3151       return;
3152 
3153   if (MD->size_overridden_methods() > 0) {
3154     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3155       unsigned DiagID =
3156           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3157               ? DiagInconsistent
3158               : DiagSuggest;
3159       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3160       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3161       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3162     };
3163     if (isa<CXXDestructorDecl>(MD))
3164       EmitDiag(
3165           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3166           diag::warn_suggest_destructor_marked_not_override_overriding);
3167     else
3168       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3169                diag::warn_suggest_function_marked_not_override_overriding);
3170   }
3171 }
3172 
3173 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3174 /// function overrides a virtual member function marked 'final', according to
3175 /// C++11 [class.virtual]p4.
3176 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3177                                                   const CXXMethodDecl *Old) {
3178   FinalAttr *FA = Old->getAttr<FinalAttr>();
3179   if (!FA)
3180     return false;
3181 
3182   Diag(New->getLocation(), diag::err_final_function_overridden)
3183     << New->getDeclName()
3184     << FA->isSpelledAsSealed();
3185   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3186   return true;
3187 }
3188 
3189 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3190   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3191   // FIXME: Destruction of ObjC lifetime types has side-effects.
3192   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3193     return !RD->isCompleteDefinition() ||
3194            !RD->hasTrivialDefaultConstructor() ||
3195            !RD->hasTrivialDestructor();
3196   return false;
3197 }
3198 
3199 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3200   ParsedAttributesView::const_iterator Itr =
3201       llvm::find_if(list, [](const ParsedAttr &AL) {
3202         return AL.isDeclspecPropertyAttribute();
3203       });
3204   if (Itr != list.end())
3205     return &*Itr;
3206   return nullptr;
3207 }
3208 
3209 // Check if there is a field shadowing.
3210 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3211                                       DeclarationName FieldName,
3212                                       const CXXRecordDecl *RD,
3213                                       bool DeclIsField) {
3214   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3215     return;
3216 
3217   // To record a shadowed field in a base
3218   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3219   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3220                            CXXBasePath &Path) {
3221     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3222     // Record an ambiguous path directly
3223     if (Bases.find(Base) != Bases.end())
3224       return true;
3225     for (const auto Field : Base->lookup(FieldName)) {
3226       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3227           Field->getAccess() != AS_private) {
3228         assert(Field->getAccess() != AS_none);
3229         assert(Bases.find(Base) == Bases.end());
3230         Bases[Base] = Field;
3231         return true;
3232       }
3233     }
3234     return false;
3235   };
3236 
3237   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3238                      /*DetectVirtual=*/true);
3239   if (!RD->lookupInBases(FieldShadowed, Paths))
3240     return;
3241 
3242   for (const auto &P : Paths) {
3243     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3244     auto It = Bases.find(Base);
3245     // Skip duplicated bases
3246     if (It == Bases.end())
3247       continue;
3248     auto BaseField = It->second;
3249     assert(BaseField->getAccess() != AS_private);
3250     if (AS_none !=
3251         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3252       Diag(Loc, diag::warn_shadow_field)
3253         << FieldName << RD << Base << DeclIsField;
3254       Diag(BaseField->getLocation(), diag::note_shadow_field);
3255       Bases.erase(It);
3256     }
3257   }
3258 }
3259 
3260 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3261 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3262 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3263 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3264 /// present (but parsing it has been deferred).
3265 NamedDecl *
3266 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3267                                MultiTemplateParamsArg TemplateParameterLists,
3268                                Expr *BW, const VirtSpecifiers &VS,
3269                                InClassInitStyle InitStyle) {
3270   const DeclSpec &DS = D.getDeclSpec();
3271   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3272   DeclarationName Name = NameInfo.getName();
3273   SourceLocation Loc = NameInfo.getLoc();
3274 
3275   // For anonymous bitfields, the location should point to the type.
3276   if (Loc.isInvalid())
3277     Loc = D.getBeginLoc();
3278 
3279   Expr *BitWidth = static_cast<Expr*>(BW);
3280 
3281   assert(isa<CXXRecordDecl>(CurContext));
3282   assert(!DS.isFriendSpecified());
3283 
3284   bool isFunc = D.isDeclarationOfFunction();
3285   const ParsedAttr *MSPropertyAttr =
3286       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3287 
3288   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3289     // The Microsoft extension __interface only permits public member functions
3290     // and prohibits constructors, destructors, operators, non-public member
3291     // functions, static methods and data members.
3292     unsigned InvalidDecl;
3293     bool ShowDeclName = true;
3294     if (!isFunc &&
3295         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3296       InvalidDecl = 0;
3297     else if (!isFunc)
3298       InvalidDecl = 1;
3299     else if (AS != AS_public)
3300       InvalidDecl = 2;
3301     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3302       InvalidDecl = 3;
3303     else switch (Name.getNameKind()) {
3304       case DeclarationName::CXXConstructorName:
3305         InvalidDecl = 4;
3306         ShowDeclName = false;
3307         break;
3308 
3309       case DeclarationName::CXXDestructorName:
3310         InvalidDecl = 5;
3311         ShowDeclName = false;
3312         break;
3313 
3314       case DeclarationName::CXXOperatorName:
3315       case DeclarationName::CXXConversionFunctionName:
3316         InvalidDecl = 6;
3317         break;
3318 
3319       default:
3320         InvalidDecl = 0;
3321         break;
3322     }
3323 
3324     if (InvalidDecl) {
3325       if (ShowDeclName)
3326         Diag(Loc, diag::err_invalid_member_in_interface)
3327           << (InvalidDecl-1) << Name;
3328       else
3329         Diag(Loc, diag::err_invalid_member_in_interface)
3330           << (InvalidDecl-1) << "";
3331       return nullptr;
3332     }
3333   }
3334 
3335   // C++ 9.2p6: A member shall not be declared to have automatic storage
3336   // duration (auto, register) or with the extern storage-class-specifier.
3337   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3338   // data members and cannot be applied to names declared const or static,
3339   // and cannot be applied to reference members.
3340   switch (DS.getStorageClassSpec()) {
3341   case DeclSpec::SCS_unspecified:
3342   case DeclSpec::SCS_typedef:
3343   case DeclSpec::SCS_static:
3344     break;
3345   case DeclSpec::SCS_mutable:
3346     if (isFunc) {
3347       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3348 
3349       // FIXME: It would be nicer if the keyword was ignored only for this
3350       // declarator. Otherwise we could get follow-up errors.
3351       D.getMutableDeclSpec().ClearStorageClassSpecs();
3352     }
3353     break;
3354   default:
3355     Diag(DS.getStorageClassSpecLoc(),
3356          diag::err_storageclass_invalid_for_member);
3357     D.getMutableDeclSpec().ClearStorageClassSpecs();
3358     break;
3359   }
3360 
3361   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3362                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3363                       !isFunc);
3364 
3365   if (DS.hasConstexprSpecifier() && isInstField) {
3366     SemaDiagnosticBuilder B =
3367         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3368     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3369     if (InitStyle == ICIS_NoInit) {
3370       B << 0 << 0;
3371       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3372         B << FixItHint::CreateRemoval(ConstexprLoc);
3373       else {
3374         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3375         D.getMutableDeclSpec().ClearConstexprSpec();
3376         const char *PrevSpec;
3377         unsigned DiagID;
3378         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3379             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3380         (void)Failed;
3381         assert(!Failed && "Making a constexpr member const shouldn't fail");
3382       }
3383     } else {
3384       B << 1;
3385       const char *PrevSpec;
3386       unsigned DiagID;
3387       if (D.getMutableDeclSpec().SetStorageClassSpec(
3388           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3389           Context.getPrintingPolicy())) {
3390         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3391                "This is the only DeclSpec that should fail to be applied");
3392         B << 1;
3393       } else {
3394         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3395         isInstField = false;
3396       }
3397     }
3398   }
3399 
3400   NamedDecl *Member;
3401   if (isInstField) {
3402     CXXScopeSpec &SS = D.getCXXScopeSpec();
3403 
3404     // Data members must have identifiers for names.
3405     if (!Name.isIdentifier()) {
3406       Diag(Loc, diag::err_bad_variable_name)
3407         << Name;
3408       return nullptr;
3409     }
3410 
3411     IdentifierInfo *II = Name.getAsIdentifierInfo();
3412 
3413     // Member field could not be with "template" keyword.
3414     // So TemplateParameterLists should be empty in this case.
3415     if (TemplateParameterLists.size()) {
3416       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3417       if (TemplateParams->size()) {
3418         // There is no such thing as a member field template.
3419         Diag(D.getIdentifierLoc(), diag::err_template_member)
3420             << II
3421             << SourceRange(TemplateParams->getTemplateLoc(),
3422                 TemplateParams->getRAngleLoc());
3423       } else {
3424         // There is an extraneous 'template<>' for this member.
3425         Diag(TemplateParams->getTemplateLoc(),
3426             diag::err_template_member_noparams)
3427             << II
3428             << SourceRange(TemplateParams->getTemplateLoc(),
3429                 TemplateParams->getRAngleLoc());
3430       }
3431       return nullptr;
3432     }
3433 
3434     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3435       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3436           << II
3437           << SourceRange(D.getName().TemplateId->LAngleLoc,
3438                          D.getName().TemplateId->RAngleLoc)
3439           << D.getName().TemplateId->LAngleLoc;
3440       D.SetIdentifier(II, Loc);
3441     }
3442 
3443     if (SS.isSet() && !SS.isInvalid()) {
3444       // The user provided a superfluous scope specifier inside a class
3445       // definition:
3446       //
3447       // class X {
3448       //   int X::member;
3449       // };
3450       if (DeclContext *DC = computeDeclContext(SS, false))
3451         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3452                                      D.getName().getKind() ==
3453                                          UnqualifiedIdKind::IK_TemplateId);
3454       else
3455         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3456           << Name << SS.getRange();
3457 
3458       SS.clear();
3459     }
3460 
3461     if (MSPropertyAttr) {
3462       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3463                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3464       if (!Member)
3465         return nullptr;
3466       isInstField = false;
3467     } else {
3468       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3469                                 BitWidth, InitStyle, AS);
3470       if (!Member)
3471         return nullptr;
3472     }
3473 
3474     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3475   } else {
3476     Member = HandleDeclarator(S, D, TemplateParameterLists);
3477     if (!Member)
3478       return nullptr;
3479 
3480     // Non-instance-fields can't have a bitfield.
3481     if (BitWidth) {
3482       if (Member->isInvalidDecl()) {
3483         // don't emit another diagnostic.
3484       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3485         // C++ 9.6p3: A bit-field shall not be a static member.
3486         // "static member 'A' cannot be a bit-field"
3487         Diag(Loc, diag::err_static_not_bitfield)
3488           << Name << BitWidth->getSourceRange();
3489       } else if (isa<TypedefDecl>(Member)) {
3490         // "typedef member 'x' cannot be a bit-field"
3491         Diag(Loc, diag::err_typedef_not_bitfield)
3492           << Name << BitWidth->getSourceRange();
3493       } else {
3494         // A function typedef ("typedef int f(); f a;").
3495         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3496         Diag(Loc, diag::err_not_integral_type_bitfield)
3497           << Name << cast<ValueDecl>(Member)->getType()
3498           << BitWidth->getSourceRange();
3499       }
3500 
3501       BitWidth = nullptr;
3502       Member->setInvalidDecl();
3503     }
3504 
3505     NamedDecl *NonTemplateMember = Member;
3506     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3507       NonTemplateMember = FunTmpl->getTemplatedDecl();
3508     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3509       NonTemplateMember = VarTmpl->getTemplatedDecl();
3510 
3511     Member->setAccess(AS);
3512 
3513     // If we have declared a member function template or static data member
3514     // template, set the access of the templated declaration as well.
3515     if (NonTemplateMember != Member)
3516       NonTemplateMember->setAccess(AS);
3517 
3518     // C++ [temp.deduct.guide]p3:
3519     //   A deduction guide [...] for a member class template [shall be
3520     //   declared] with the same access [as the template].
3521     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3522       auto *TD = DG->getDeducedTemplate();
3523       // Access specifiers are only meaningful if both the template and the
3524       // deduction guide are from the same scope.
3525       if (AS != TD->getAccess() &&
3526           TD->getDeclContext()->getRedeclContext()->Equals(
3527               DG->getDeclContext()->getRedeclContext())) {
3528         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3529         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3530             << TD->getAccess();
3531         const AccessSpecDecl *LastAccessSpec = nullptr;
3532         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3533           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3534             LastAccessSpec = AccessSpec;
3535         }
3536         assert(LastAccessSpec && "differing access with no access specifier");
3537         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3538             << AS;
3539       }
3540     }
3541   }
3542 
3543   if (VS.isOverrideSpecified())
3544     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3545                                          AttributeCommonInfo::AS_Keyword));
3546   if (VS.isFinalSpecified())
3547     Member->addAttr(FinalAttr::Create(
3548         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3549         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3550 
3551   if (VS.getLastLocation().isValid()) {
3552     // Update the end location of a method that has a virt-specifiers.
3553     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3554       MD->setRangeEnd(VS.getLastLocation());
3555   }
3556 
3557   CheckOverrideControl(Member);
3558 
3559   assert((Name || isInstField) && "No identifier for non-field ?");
3560 
3561   if (isInstField) {
3562     FieldDecl *FD = cast<FieldDecl>(Member);
3563     FieldCollector->Add(FD);
3564 
3565     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3566       // Remember all explicit private FieldDecls that have a name, no side
3567       // effects and are not part of a dependent type declaration.
3568       if (!FD->isImplicit() && FD->getDeclName() &&
3569           FD->getAccess() == AS_private &&
3570           !FD->hasAttr<UnusedAttr>() &&
3571           !FD->getParent()->isDependentContext() &&
3572           !InitializationHasSideEffects(*FD))
3573         UnusedPrivateFields.insert(FD);
3574     }
3575   }
3576 
3577   return Member;
3578 }
3579 
3580 namespace {
3581   class UninitializedFieldVisitor
3582       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3583     Sema &S;
3584     // List of Decls to generate a warning on.  Also remove Decls that become
3585     // initialized.
3586     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3587     // List of base classes of the record.  Classes are removed after their
3588     // initializers.
3589     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3590     // Vector of decls to be removed from the Decl set prior to visiting the
3591     // nodes.  These Decls may have been initialized in the prior initializer.
3592     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3593     // If non-null, add a note to the warning pointing back to the constructor.
3594     const CXXConstructorDecl *Constructor;
3595     // Variables to hold state when processing an initializer list.  When
3596     // InitList is true, special case initialization of FieldDecls matching
3597     // InitListFieldDecl.
3598     bool InitList;
3599     FieldDecl *InitListFieldDecl;
3600     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3601 
3602   public:
3603     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3604     UninitializedFieldVisitor(Sema &S,
3605                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3606                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3607       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3608         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3609 
3610     // Returns true if the use of ME is not an uninitialized use.
3611     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3612                                          bool CheckReferenceOnly) {
3613       llvm::SmallVector<FieldDecl*, 4> Fields;
3614       bool ReferenceField = false;
3615       while (ME) {
3616         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3617         if (!FD)
3618           return false;
3619         Fields.push_back(FD);
3620         if (FD->getType()->isReferenceType())
3621           ReferenceField = true;
3622         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3623       }
3624 
3625       // Binding a reference to an uninitialized field is not an
3626       // uninitialized use.
3627       if (CheckReferenceOnly && !ReferenceField)
3628         return true;
3629 
3630       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3631       // Discard the first field since it is the field decl that is being
3632       // initialized.
3633       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3634         UsedFieldIndex.push_back(FD->getFieldIndex());
3635 
3636       for (auto UsedIter = UsedFieldIndex.begin(),
3637                 UsedEnd = UsedFieldIndex.end(),
3638                 OrigIter = InitFieldIndex.begin(),
3639                 OrigEnd = InitFieldIndex.end();
3640            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3641         if (*UsedIter < *OrigIter)
3642           return true;
3643         if (*UsedIter > *OrigIter)
3644           break;
3645       }
3646 
3647       return false;
3648     }
3649 
3650     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3651                           bool AddressOf) {
3652       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3653         return;
3654 
3655       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3656       // or union.
3657       MemberExpr *FieldME = ME;
3658 
3659       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3660 
3661       Expr *Base = ME;
3662       while (MemberExpr *SubME =
3663                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3664 
3665         if (isa<VarDecl>(SubME->getMemberDecl()))
3666           return;
3667 
3668         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3669           if (!FD->isAnonymousStructOrUnion())
3670             FieldME = SubME;
3671 
3672         if (!FieldME->getType().isPODType(S.Context))
3673           AllPODFields = false;
3674 
3675         Base = SubME->getBase();
3676       }
3677 
3678       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3679         Visit(Base);
3680         return;
3681       }
3682 
3683       if (AddressOf && AllPODFields)
3684         return;
3685 
3686       ValueDecl* FoundVD = FieldME->getMemberDecl();
3687 
3688       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3689         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3690           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3691         }
3692 
3693         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3694           QualType T = BaseCast->getType();
3695           if (T->isPointerType() &&
3696               BaseClasses.count(T->getPointeeType())) {
3697             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3698                 << T->getPointeeType() << FoundVD;
3699           }
3700         }
3701       }
3702 
3703       if (!Decls.count(FoundVD))
3704         return;
3705 
3706       const bool IsReference = FoundVD->getType()->isReferenceType();
3707 
3708       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3709         // Special checking for initializer lists.
3710         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3711           return;
3712         }
3713       } else {
3714         // Prevent double warnings on use of unbounded references.
3715         if (CheckReferenceOnly && !IsReference)
3716           return;
3717       }
3718 
3719       unsigned diag = IsReference
3720           ? diag::warn_reference_field_is_uninit
3721           : diag::warn_field_is_uninit;
3722       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3723       if (Constructor)
3724         S.Diag(Constructor->getLocation(),
3725                diag::note_uninit_in_this_constructor)
3726           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3727 
3728     }
3729 
3730     void HandleValue(Expr *E, bool AddressOf) {
3731       E = E->IgnoreParens();
3732 
3733       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3734         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3735                          AddressOf /*AddressOf*/);
3736         return;
3737       }
3738 
3739       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3740         Visit(CO->getCond());
3741         HandleValue(CO->getTrueExpr(), AddressOf);
3742         HandleValue(CO->getFalseExpr(), AddressOf);
3743         return;
3744       }
3745 
3746       if (BinaryConditionalOperator *BCO =
3747               dyn_cast<BinaryConditionalOperator>(E)) {
3748         Visit(BCO->getCond());
3749         HandleValue(BCO->getFalseExpr(), AddressOf);
3750         return;
3751       }
3752 
3753       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3754         HandleValue(OVE->getSourceExpr(), AddressOf);
3755         return;
3756       }
3757 
3758       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3759         switch (BO->getOpcode()) {
3760         default:
3761           break;
3762         case(BO_PtrMemD):
3763         case(BO_PtrMemI):
3764           HandleValue(BO->getLHS(), AddressOf);
3765           Visit(BO->getRHS());
3766           return;
3767         case(BO_Comma):
3768           Visit(BO->getLHS());
3769           HandleValue(BO->getRHS(), AddressOf);
3770           return;
3771         }
3772       }
3773 
3774       Visit(E);
3775     }
3776 
3777     void CheckInitListExpr(InitListExpr *ILE) {
3778       InitFieldIndex.push_back(0);
3779       for (auto Child : ILE->children()) {
3780         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3781           CheckInitListExpr(SubList);
3782         } else {
3783           Visit(Child);
3784         }
3785         ++InitFieldIndex.back();
3786       }
3787       InitFieldIndex.pop_back();
3788     }
3789 
3790     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3791                           FieldDecl *Field, const Type *BaseClass) {
3792       // Remove Decls that may have been initialized in the previous
3793       // initializer.
3794       for (ValueDecl* VD : DeclsToRemove)
3795         Decls.erase(VD);
3796       DeclsToRemove.clear();
3797 
3798       Constructor = FieldConstructor;
3799       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3800 
3801       if (ILE && Field) {
3802         InitList = true;
3803         InitListFieldDecl = Field;
3804         InitFieldIndex.clear();
3805         CheckInitListExpr(ILE);
3806       } else {
3807         InitList = false;
3808         Visit(E);
3809       }
3810 
3811       if (Field)
3812         Decls.erase(Field);
3813       if (BaseClass)
3814         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3815     }
3816 
3817     void VisitMemberExpr(MemberExpr *ME) {
3818       // All uses of unbounded reference fields will warn.
3819       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3820     }
3821 
3822     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3823       if (E->getCastKind() == CK_LValueToRValue) {
3824         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3825         return;
3826       }
3827 
3828       Inherited::VisitImplicitCastExpr(E);
3829     }
3830 
3831     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3832       if (E->getConstructor()->isCopyConstructor()) {
3833         Expr *ArgExpr = E->getArg(0);
3834         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3835           if (ILE->getNumInits() == 1)
3836             ArgExpr = ILE->getInit(0);
3837         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3838           if (ICE->getCastKind() == CK_NoOp)
3839             ArgExpr = ICE->getSubExpr();
3840         HandleValue(ArgExpr, false /*AddressOf*/);
3841         return;
3842       }
3843       Inherited::VisitCXXConstructExpr(E);
3844     }
3845 
3846     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3847       Expr *Callee = E->getCallee();
3848       if (isa<MemberExpr>(Callee)) {
3849         HandleValue(Callee, false /*AddressOf*/);
3850         for (auto Arg : E->arguments())
3851           Visit(Arg);
3852         return;
3853       }
3854 
3855       Inherited::VisitCXXMemberCallExpr(E);
3856     }
3857 
3858     void VisitCallExpr(CallExpr *E) {
3859       // Treat std::move as a use.
3860       if (E->isCallToStdMove()) {
3861         HandleValue(E->getArg(0), /*AddressOf=*/false);
3862         return;
3863       }
3864 
3865       Inherited::VisitCallExpr(E);
3866     }
3867 
3868     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3869       Expr *Callee = E->getCallee();
3870 
3871       if (isa<UnresolvedLookupExpr>(Callee))
3872         return Inherited::VisitCXXOperatorCallExpr(E);
3873 
3874       Visit(Callee);
3875       for (auto Arg : E->arguments())
3876         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3877     }
3878 
3879     void VisitBinaryOperator(BinaryOperator *E) {
3880       // If a field assignment is detected, remove the field from the
3881       // uninitiailized field set.
3882       if (E->getOpcode() == BO_Assign)
3883         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3884           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3885             if (!FD->getType()->isReferenceType())
3886               DeclsToRemove.push_back(FD);
3887 
3888       if (E->isCompoundAssignmentOp()) {
3889         HandleValue(E->getLHS(), false /*AddressOf*/);
3890         Visit(E->getRHS());
3891         return;
3892       }
3893 
3894       Inherited::VisitBinaryOperator(E);
3895     }
3896 
3897     void VisitUnaryOperator(UnaryOperator *E) {
3898       if (E->isIncrementDecrementOp()) {
3899         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3900         return;
3901       }
3902       if (E->getOpcode() == UO_AddrOf) {
3903         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3904           HandleValue(ME->getBase(), true /*AddressOf*/);
3905           return;
3906         }
3907       }
3908 
3909       Inherited::VisitUnaryOperator(E);
3910     }
3911   };
3912 
3913   // Diagnose value-uses of fields to initialize themselves, e.g.
3914   //   foo(foo)
3915   // where foo is not also a parameter to the constructor.
3916   // Also diagnose across field uninitialized use such as
3917   //   x(y), y(x)
3918   // TODO: implement -Wuninitialized and fold this into that framework.
3919   static void DiagnoseUninitializedFields(
3920       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3921 
3922     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3923                                            Constructor->getLocation())) {
3924       return;
3925     }
3926 
3927     if (Constructor->isInvalidDecl())
3928       return;
3929 
3930     const CXXRecordDecl *RD = Constructor->getParent();
3931 
3932     if (RD->isDependentContext())
3933       return;
3934 
3935     // Holds fields that are uninitialized.
3936     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3937 
3938     // At the beginning, all fields are uninitialized.
3939     for (auto *I : RD->decls()) {
3940       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3941         UninitializedFields.insert(FD);
3942       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3943         UninitializedFields.insert(IFD->getAnonField());
3944       }
3945     }
3946 
3947     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3948     for (auto I : RD->bases())
3949       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3950 
3951     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3952       return;
3953 
3954     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3955                                                    UninitializedFields,
3956                                                    UninitializedBaseClasses);
3957 
3958     for (const auto *FieldInit : Constructor->inits()) {
3959       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3960         break;
3961 
3962       Expr *InitExpr = FieldInit->getInit();
3963       if (!InitExpr)
3964         continue;
3965 
3966       if (CXXDefaultInitExpr *Default =
3967               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3968         InitExpr = Default->getExpr();
3969         if (!InitExpr)
3970           continue;
3971         // In class initializers will point to the constructor.
3972         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3973                                               FieldInit->getAnyMember(),
3974                                               FieldInit->getBaseClass());
3975       } else {
3976         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3977                                               FieldInit->getAnyMember(),
3978                                               FieldInit->getBaseClass());
3979       }
3980     }
3981   }
3982 } // namespace
3983 
3984 /// Enter a new C++ default initializer scope. After calling this, the
3985 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3986 /// parsing or instantiating the initializer failed.
3987 void Sema::ActOnStartCXXInClassMemberInitializer() {
3988   // Create a synthetic function scope to represent the call to the constructor
3989   // that notionally surrounds a use of this initializer.
3990   PushFunctionScope();
3991 }
3992 
3993 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3994   if (!D.isFunctionDeclarator())
3995     return;
3996   auto &FTI = D.getFunctionTypeInfo();
3997   if (!FTI.Params)
3998     return;
3999   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4000                                                           FTI.NumParams)) {
4001     auto *ParamDecl = cast<NamedDecl>(Param.Param);
4002     if (ParamDecl->getDeclName())
4003       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4004   }
4005 }
4006 
4007 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4008   return ActOnRequiresClause(ConstraintExpr);
4009 }
4010 
4011 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4012   if (ConstraintExpr.isInvalid())
4013     return ExprError();
4014 
4015   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4016   if (ConstraintExpr.isInvalid())
4017     return ExprError();
4018 
4019   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4020                                       UPPC_RequiresClause))
4021     return ExprError();
4022 
4023   return ConstraintExpr;
4024 }
4025 
4026 /// This is invoked after parsing an in-class initializer for a
4027 /// non-static C++ class member, and after instantiating an in-class initializer
4028 /// in a class template. Such actions are deferred until the class is complete.
4029 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4030                                                   SourceLocation InitLoc,
4031                                                   Expr *InitExpr) {
4032   // Pop the notional constructor scope we created earlier.
4033   PopFunctionScopeInfo(nullptr, D);
4034 
4035   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4036   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4037          "must set init style when field is created");
4038 
4039   if (!InitExpr) {
4040     D->setInvalidDecl();
4041     if (FD)
4042       FD->removeInClassInitializer();
4043     return;
4044   }
4045 
4046   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4047     FD->setInvalidDecl();
4048     FD->removeInClassInitializer();
4049     return;
4050   }
4051 
4052   ExprResult Init = InitExpr;
4053   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4054     InitializedEntity Entity =
4055         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4056     InitializationKind Kind =
4057         FD->getInClassInitStyle() == ICIS_ListInit
4058             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4059                                                    InitExpr->getBeginLoc(),
4060                                                    InitExpr->getEndLoc())
4061             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4062     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4063     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4064     if (Init.isInvalid()) {
4065       FD->setInvalidDecl();
4066       return;
4067     }
4068   }
4069 
4070   // C++11 [class.base.init]p7:
4071   //   The initialization of each base and member constitutes a
4072   //   full-expression.
4073   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4074   if (Init.isInvalid()) {
4075     FD->setInvalidDecl();
4076     return;
4077   }
4078 
4079   InitExpr = Init.get();
4080 
4081   FD->setInClassInitializer(InitExpr);
4082 }
4083 
4084 /// Find the direct and/or virtual base specifiers that
4085 /// correspond to the given base type, for use in base initialization
4086 /// within a constructor.
4087 static bool FindBaseInitializer(Sema &SemaRef,
4088                                 CXXRecordDecl *ClassDecl,
4089                                 QualType BaseType,
4090                                 const CXXBaseSpecifier *&DirectBaseSpec,
4091                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4092   // First, check for a direct base class.
4093   DirectBaseSpec = nullptr;
4094   for (const auto &Base : ClassDecl->bases()) {
4095     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4096       // We found a direct base of this type. That's what we're
4097       // initializing.
4098       DirectBaseSpec = &Base;
4099       break;
4100     }
4101   }
4102 
4103   // Check for a virtual base class.
4104   // FIXME: We might be able to short-circuit this if we know in advance that
4105   // there are no virtual bases.
4106   VirtualBaseSpec = nullptr;
4107   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4108     // We haven't found a base yet; search the class hierarchy for a
4109     // virtual base class.
4110     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4111                        /*DetectVirtual=*/false);
4112     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4113                               SemaRef.Context.getTypeDeclType(ClassDecl),
4114                               BaseType, Paths)) {
4115       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4116            Path != Paths.end(); ++Path) {
4117         if (Path->back().Base->isVirtual()) {
4118           VirtualBaseSpec = Path->back().Base;
4119           break;
4120         }
4121       }
4122     }
4123   }
4124 
4125   return DirectBaseSpec || VirtualBaseSpec;
4126 }
4127 
4128 /// Handle a C++ member initializer using braced-init-list syntax.
4129 MemInitResult
4130 Sema::ActOnMemInitializer(Decl *ConstructorD,
4131                           Scope *S,
4132                           CXXScopeSpec &SS,
4133                           IdentifierInfo *MemberOrBase,
4134                           ParsedType TemplateTypeTy,
4135                           const DeclSpec &DS,
4136                           SourceLocation IdLoc,
4137                           Expr *InitList,
4138                           SourceLocation EllipsisLoc) {
4139   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4140                              DS, IdLoc, InitList,
4141                              EllipsisLoc);
4142 }
4143 
4144 /// Handle a C++ member initializer using parentheses syntax.
4145 MemInitResult
4146 Sema::ActOnMemInitializer(Decl *ConstructorD,
4147                           Scope *S,
4148                           CXXScopeSpec &SS,
4149                           IdentifierInfo *MemberOrBase,
4150                           ParsedType TemplateTypeTy,
4151                           const DeclSpec &DS,
4152                           SourceLocation IdLoc,
4153                           SourceLocation LParenLoc,
4154                           ArrayRef<Expr *> Args,
4155                           SourceLocation RParenLoc,
4156                           SourceLocation EllipsisLoc) {
4157   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4158   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4159                              DS, IdLoc, List, EllipsisLoc);
4160 }
4161 
4162 namespace {
4163 
4164 // Callback to only accept typo corrections that can be a valid C++ member
4165 // initializer: either a non-static field member or a base class.
4166 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4167 public:
4168   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4169       : ClassDecl(ClassDecl) {}
4170 
4171   bool ValidateCandidate(const TypoCorrection &candidate) override {
4172     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4173       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4174         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4175       return isa<TypeDecl>(ND);
4176     }
4177     return false;
4178   }
4179 
4180   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4181     return std::make_unique<MemInitializerValidatorCCC>(*this);
4182   }
4183 
4184 private:
4185   CXXRecordDecl *ClassDecl;
4186 };
4187 
4188 }
4189 
4190 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4191                                              CXXScopeSpec &SS,
4192                                              ParsedType TemplateTypeTy,
4193                                              IdentifierInfo *MemberOrBase) {
4194   if (SS.getScopeRep() || TemplateTypeTy)
4195     return nullptr;
4196   for (auto *D : ClassDecl->lookup(MemberOrBase))
4197     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4198       return cast<ValueDecl>(D);
4199   return nullptr;
4200 }
4201 
4202 /// Handle a C++ member initializer.
4203 MemInitResult
4204 Sema::BuildMemInitializer(Decl *ConstructorD,
4205                           Scope *S,
4206                           CXXScopeSpec &SS,
4207                           IdentifierInfo *MemberOrBase,
4208                           ParsedType TemplateTypeTy,
4209                           const DeclSpec &DS,
4210                           SourceLocation IdLoc,
4211                           Expr *Init,
4212                           SourceLocation EllipsisLoc) {
4213   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4214                                              /*RecoverUncorrectedTypos=*/true);
4215   if (!Res.isUsable())
4216     return true;
4217   Init = Res.get();
4218 
4219   if (!ConstructorD)
4220     return true;
4221 
4222   AdjustDeclIfTemplate(ConstructorD);
4223 
4224   CXXConstructorDecl *Constructor
4225     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4226   if (!Constructor) {
4227     // The user wrote a constructor initializer on a function that is
4228     // not a C++ constructor. Ignore the error for now, because we may
4229     // have more member initializers coming; we'll diagnose it just
4230     // once in ActOnMemInitializers.
4231     return true;
4232   }
4233 
4234   CXXRecordDecl *ClassDecl = Constructor->getParent();
4235 
4236   // C++ [class.base.init]p2:
4237   //   Names in a mem-initializer-id are looked up in the scope of the
4238   //   constructor's class and, if not found in that scope, are looked
4239   //   up in the scope containing the constructor's definition.
4240   //   [Note: if the constructor's class contains a member with the
4241   //   same name as a direct or virtual base class of the class, a
4242   //   mem-initializer-id naming the member or base class and composed
4243   //   of a single identifier refers to the class member. A
4244   //   mem-initializer-id for the hidden base class may be specified
4245   //   using a qualified name. ]
4246 
4247   // Look for a member, first.
4248   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4249           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4250     if (EllipsisLoc.isValid())
4251       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4252           << MemberOrBase
4253           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4254 
4255     return BuildMemberInitializer(Member, Init, IdLoc);
4256   }
4257   // It didn't name a member, so see if it names a class.
4258   QualType BaseType;
4259   TypeSourceInfo *TInfo = nullptr;
4260 
4261   if (TemplateTypeTy) {
4262     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4263     if (BaseType.isNull())
4264       return true;
4265   } else if (DS.getTypeSpecType() == TST_decltype) {
4266     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4267   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4268     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4269     return true;
4270   } else {
4271     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4272     LookupParsedName(R, S, &SS);
4273 
4274     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4275     if (!TyD) {
4276       if (R.isAmbiguous()) return true;
4277 
4278       // We don't want access-control diagnostics here.
4279       R.suppressDiagnostics();
4280 
4281       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4282         bool NotUnknownSpecialization = false;
4283         DeclContext *DC = computeDeclContext(SS, false);
4284         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4285           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4286 
4287         if (!NotUnknownSpecialization) {
4288           // When the scope specifier can refer to a member of an unknown
4289           // specialization, we take it as a type name.
4290           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4291                                        SS.getWithLocInContext(Context),
4292                                        *MemberOrBase, IdLoc);
4293           if (BaseType.isNull())
4294             return true;
4295 
4296           TInfo = Context.CreateTypeSourceInfo(BaseType);
4297           DependentNameTypeLoc TL =
4298               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4299           if (!TL.isNull()) {
4300             TL.setNameLoc(IdLoc);
4301             TL.setElaboratedKeywordLoc(SourceLocation());
4302             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4303           }
4304 
4305           R.clear();
4306           R.setLookupName(MemberOrBase);
4307         }
4308       }
4309 
4310       // If no results were found, try to correct typos.
4311       TypoCorrection Corr;
4312       MemInitializerValidatorCCC CCC(ClassDecl);
4313       if (R.empty() && BaseType.isNull() &&
4314           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4315                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4316         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4317           // We have found a non-static data member with a similar
4318           // name to what was typed; complain and initialize that
4319           // member.
4320           diagnoseTypo(Corr,
4321                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4322                          << MemberOrBase << true);
4323           return BuildMemberInitializer(Member, Init, IdLoc);
4324         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4325           const CXXBaseSpecifier *DirectBaseSpec;
4326           const CXXBaseSpecifier *VirtualBaseSpec;
4327           if (FindBaseInitializer(*this, ClassDecl,
4328                                   Context.getTypeDeclType(Type),
4329                                   DirectBaseSpec, VirtualBaseSpec)) {
4330             // We have found a direct or virtual base class with a
4331             // similar name to what was typed; complain and initialize
4332             // that base class.
4333             diagnoseTypo(Corr,
4334                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4335                            << MemberOrBase << false,
4336                          PDiag() /*Suppress note, we provide our own.*/);
4337 
4338             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4339                                                               : VirtualBaseSpec;
4340             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4341                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4342 
4343             TyD = Type;
4344           }
4345         }
4346       }
4347 
4348       if (!TyD && BaseType.isNull()) {
4349         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4350           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4351         return true;
4352       }
4353     }
4354 
4355     if (BaseType.isNull()) {
4356       BaseType = Context.getTypeDeclType(TyD);
4357       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4358       if (SS.isSet()) {
4359         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4360                                              BaseType);
4361         TInfo = Context.CreateTypeSourceInfo(BaseType);
4362         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4363         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4364         TL.setElaboratedKeywordLoc(SourceLocation());
4365         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4366       }
4367     }
4368   }
4369 
4370   if (!TInfo)
4371     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4372 
4373   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4374 }
4375 
4376 MemInitResult
4377 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4378                              SourceLocation IdLoc) {
4379   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4380   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4381   assert((DirectMember || IndirectMember) &&
4382          "Member must be a FieldDecl or IndirectFieldDecl");
4383 
4384   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4385     return true;
4386 
4387   if (Member->isInvalidDecl())
4388     return true;
4389 
4390   MultiExprArg Args;
4391   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4392     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4393   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4394     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4395   } else {
4396     // Template instantiation doesn't reconstruct ParenListExprs for us.
4397     Args = Init;
4398   }
4399 
4400   SourceRange InitRange = Init->getSourceRange();
4401 
4402   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4403     // Can't check initialization for a member of dependent type or when
4404     // any of the arguments are type-dependent expressions.
4405     DiscardCleanupsInEvaluationContext();
4406   } else {
4407     bool InitList = false;
4408     if (isa<InitListExpr>(Init)) {
4409       InitList = true;
4410       Args = Init;
4411     }
4412 
4413     // Initialize the member.
4414     InitializedEntity MemberEntity =
4415       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4416                    : InitializedEntity::InitializeMember(IndirectMember,
4417                                                          nullptr);
4418     InitializationKind Kind =
4419         InitList ? InitializationKind::CreateDirectList(
4420                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4421                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4422                                                     InitRange.getEnd());
4423 
4424     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4425     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4426                                             nullptr);
4427     if (!MemberInit.isInvalid()) {
4428       // C++11 [class.base.init]p7:
4429       //   The initialization of each base and member constitutes a
4430       //   full-expression.
4431       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4432                                        /*DiscardedValue*/ false);
4433     }
4434 
4435     if (MemberInit.isInvalid()) {
4436       // Args were sensible expressions but we couldn't initialize the member
4437       // from them. Preserve them in a RecoveryExpr instead.
4438       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4439                                 Member->getType())
4440                  .get();
4441       if (!Init)
4442         return true;
4443     } else {
4444       Init = MemberInit.get();
4445     }
4446   }
4447 
4448   if (DirectMember) {
4449     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4450                                             InitRange.getBegin(), Init,
4451                                             InitRange.getEnd());
4452   } else {
4453     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4454                                             InitRange.getBegin(), Init,
4455                                             InitRange.getEnd());
4456   }
4457 }
4458 
4459 MemInitResult
4460 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4461                                  CXXRecordDecl *ClassDecl) {
4462   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4463   if (!LangOpts.CPlusPlus11)
4464     return Diag(NameLoc, diag::err_delegating_ctor)
4465       << TInfo->getTypeLoc().getLocalSourceRange();
4466   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4467 
4468   bool InitList = true;
4469   MultiExprArg Args = Init;
4470   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4471     InitList = false;
4472     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4473   }
4474 
4475   SourceRange InitRange = Init->getSourceRange();
4476   // Initialize the object.
4477   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4478                                      QualType(ClassDecl->getTypeForDecl(), 0));
4479   InitializationKind Kind =
4480       InitList ? InitializationKind::CreateDirectList(
4481                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4482                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4483                                                   InitRange.getEnd());
4484   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4485   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4486                                               Args, nullptr);
4487   if (!DelegationInit.isInvalid()) {
4488     assert((DelegationInit.get()->containsErrors() ||
4489             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4490            "Delegating constructor with no target?");
4491 
4492     // C++11 [class.base.init]p7:
4493     //   The initialization of each base and member constitutes a
4494     //   full-expression.
4495     DelegationInit = ActOnFinishFullExpr(
4496         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4497   }
4498 
4499   if (DelegationInit.isInvalid()) {
4500     DelegationInit =
4501         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4502                            QualType(ClassDecl->getTypeForDecl(), 0));
4503     if (DelegationInit.isInvalid())
4504       return true;
4505   } else {
4506     // If we are in a dependent context, template instantiation will
4507     // perform this type-checking again. Just save the arguments that we
4508     // received in a ParenListExpr.
4509     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4510     // of the information that we have about the base
4511     // initializer. However, deconstructing the ASTs is a dicey process,
4512     // and this approach is far more likely to get the corner cases right.
4513     if (CurContext->isDependentContext())
4514       DelegationInit = Init;
4515   }
4516 
4517   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4518                                           DelegationInit.getAs<Expr>(),
4519                                           InitRange.getEnd());
4520 }
4521 
4522 MemInitResult
4523 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4524                            Expr *Init, CXXRecordDecl *ClassDecl,
4525                            SourceLocation EllipsisLoc) {
4526   SourceLocation BaseLoc
4527     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4528 
4529   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4530     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4531              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4532 
4533   // C++ [class.base.init]p2:
4534   //   [...] Unless the mem-initializer-id names a nonstatic data
4535   //   member of the constructor's class or a direct or virtual base
4536   //   of that class, the mem-initializer is ill-formed. A
4537   //   mem-initializer-list can initialize a base class using any
4538   //   name that denotes that base class type.
4539 
4540   // We can store the initializers in "as-written" form and delay analysis until
4541   // instantiation if the constructor is dependent. But not for dependent
4542   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4543   bool Dependent = CurContext->isDependentContext() &&
4544                    (BaseType->isDependentType() || Init->isTypeDependent());
4545 
4546   SourceRange InitRange = Init->getSourceRange();
4547   if (EllipsisLoc.isValid()) {
4548     // This is a pack expansion.
4549     if (!BaseType->containsUnexpandedParameterPack())  {
4550       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4551         << SourceRange(BaseLoc, InitRange.getEnd());
4552 
4553       EllipsisLoc = SourceLocation();
4554     }
4555   } else {
4556     // Check for any unexpanded parameter packs.
4557     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4558       return true;
4559 
4560     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4561       return true;
4562   }
4563 
4564   // Check for direct and virtual base classes.
4565   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4566   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4567   if (!Dependent) {
4568     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4569                                        BaseType))
4570       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4571 
4572     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4573                         VirtualBaseSpec);
4574 
4575     // C++ [base.class.init]p2:
4576     // Unless the mem-initializer-id names a nonstatic data member of the
4577     // constructor's class or a direct or virtual base of that class, the
4578     // mem-initializer is ill-formed.
4579     if (!DirectBaseSpec && !VirtualBaseSpec) {
4580       // If the class has any dependent bases, then it's possible that
4581       // one of those types will resolve to the same type as
4582       // BaseType. Therefore, just treat this as a dependent base
4583       // class initialization.  FIXME: Should we try to check the
4584       // initialization anyway? It seems odd.
4585       if (ClassDecl->hasAnyDependentBases())
4586         Dependent = true;
4587       else
4588         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4589           << BaseType << Context.getTypeDeclType(ClassDecl)
4590           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4591     }
4592   }
4593 
4594   if (Dependent) {
4595     DiscardCleanupsInEvaluationContext();
4596 
4597     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4598                                             /*IsVirtual=*/false,
4599                                             InitRange.getBegin(), Init,
4600                                             InitRange.getEnd(), EllipsisLoc);
4601   }
4602 
4603   // C++ [base.class.init]p2:
4604   //   If a mem-initializer-id is ambiguous because it designates both
4605   //   a direct non-virtual base class and an inherited virtual base
4606   //   class, the mem-initializer is ill-formed.
4607   if (DirectBaseSpec && VirtualBaseSpec)
4608     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4609       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4610 
4611   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4612   if (!BaseSpec)
4613     BaseSpec = VirtualBaseSpec;
4614 
4615   // Initialize the base.
4616   bool InitList = true;
4617   MultiExprArg Args = Init;
4618   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4619     InitList = false;
4620     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4621   }
4622 
4623   InitializedEntity BaseEntity =
4624     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4625   InitializationKind Kind =
4626       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4627                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4628                                                   InitRange.getEnd());
4629   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4630   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4631   if (!BaseInit.isInvalid()) {
4632     // C++11 [class.base.init]p7:
4633     //   The initialization of each base and member constitutes a
4634     //   full-expression.
4635     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4636                                    /*DiscardedValue*/ false);
4637   }
4638 
4639   if (BaseInit.isInvalid()) {
4640     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4641                                   Args, BaseType);
4642     if (BaseInit.isInvalid())
4643       return true;
4644   } else {
4645     // If we are in a dependent context, template instantiation will
4646     // perform this type-checking again. Just save the arguments that we
4647     // received in a ParenListExpr.
4648     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4649     // of the information that we have about the base
4650     // initializer. However, deconstructing the ASTs is a dicey process,
4651     // and this approach is far more likely to get the corner cases right.
4652     if (CurContext->isDependentContext())
4653       BaseInit = Init;
4654   }
4655 
4656   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4657                                           BaseSpec->isVirtual(),
4658                                           InitRange.getBegin(),
4659                                           BaseInit.getAs<Expr>(),
4660                                           InitRange.getEnd(), EllipsisLoc);
4661 }
4662 
4663 // Create a static_cast\<T&&>(expr).
4664 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4665   if (T.isNull()) T = E->getType();
4666   QualType TargetType = SemaRef.BuildReferenceType(
4667       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4668   SourceLocation ExprLoc = E->getBeginLoc();
4669   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4670       TargetType, ExprLoc);
4671 
4672   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4673                                    SourceRange(ExprLoc, ExprLoc),
4674                                    E->getSourceRange()).get();
4675 }
4676 
4677 /// ImplicitInitializerKind - How an implicit base or member initializer should
4678 /// initialize its base or member.
4679 enum ImplicitInitializerKind {
4680   IIK_Default,
4681   IIK_Copy,
4682   IIK_Move,
4683   IIK_Inherit
4684 };
4685 
4686 static bool
4687 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4688                              ImplicitInitializerKind ImplicitInitKind,
4689                              CXXBaseSpecifier *BaseSpec,
4690                              bool IsInheritedVirtualBase,
4691                              CXXCtorInitializer *&CXXBaseInit) {
4692   InitializedEntity InitEntity
4693     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4694                                         IsInheritedVirtualBase);
4695 
4696   ExprResult BaseInit;
4697 
4698   switch (ImplicitInitKind) {
4699   case IIK_Inherit:
4700   case IIK_Default: {
4701     InitializationKind InitKind
4702       = InitializationKind::CreateDefault(Constructor->getLocation());
4703     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4704     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4705     break;
4706   }
4707 
4708   case IIK_Move:
4709   case IIK_Copy: {
4710     bool Moving = ImplicitInitKind == IIK_Move;
4711     ParmVarDecl *Param = Constructor->getParamDecl(0);
4712     QualType ParamType = Param->getType().getNonReferenceType();
4713 
4714     Expr *CopyCtorArg =
4715       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4716                           SourceLocation(), Param, false,
4717                           Constructor->getLocation(), ParamType,
4718                           VK_LValue, nullptr);
4719 
4720     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4721 
4722     // Cast to the base class to avoid ambiguities.
4723     QualType ArgTy =
4724       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4725                                        ParamType.getQualifiers());
4726 
4727     if (Moving) {
4728       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4729     }
4730 
4731     CXXCastPath BasePath;
4732     BasePath.push_back(BaseSpec);
4733     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4734                                             CK_UncheckedDerivedToBase,
4735                                             Moving ? VK_XValue : VK_LValue,
4736                                             &BasePath).get();
4737 
4738     InitializationKind InitKind
4739       = InitializationKind::CreateDirect(Constructor->getLocation(),
4740                                          SourceLocation(), SourceLocation());
4741     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4742     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4743     break;
4744   }
4745   }
4746 
4747   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4748   if (BaseInit.isInvalid())
4749     return true;
4750 
4751   CXXBaseInit =
4752     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4753                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4754                                                         SourceLocation()),
4755                                              BaseSpec->isVirtual(),
4756                                              SourceLocation(),
4757                                              BaseInit.getAs<Expr>(),
4758                                              SourceLocation(),
4759                                              SourceLocation());
4760 
4761   return false;
4762 }
4763 
4764 static bool RefersToRValueRef(Expr *MemRef) {
4765   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4766   return Referenced->getType()->isRValueReferenceType();
4767 }
4768 
4769 static bool
4770 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4771                                ImplicitInitializerKind ImplicitInitKind,
4772                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4773                                CXXCtorInitializer *&CXXMemberInit) {
4774   if (Field->isInvalidDecl())
4775     return true;
4776 
4777   SourceLocation Loc = Constructor->getLocation();
4778 
4779   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4780     bool Moving = ImplicitInitKind == IIK_Move;
4781     ParmVarDecl *Param = Constructor->getParamDecl(0);
4782     QualType ParamType = Param->getType().getNonReferenceType();
4783 
4784     // Suppress copying zero-width bitfields.
4785     if (Field->isZeroLengthBitField(SemaRef.Context))
4786       return false;
4787 
4788     Expr *MemberExprBase =
4789       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4790                           SourceLocation(), Param, false,
4791                           Loc, ParamType, VK_LValue, nullptr);
4792 
4793     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4794 
4795     if (Moving) {
4796       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4797     }
4798 
4799     // Build a reference to this field within the parameter.
4800     CXXScopeSpec SS;
4801     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4802                               Sema::LookupMemberName);
4803     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4804                                   : cast<ValueDecl>(Field), AS_public);
4805     MemberLookup.resolveKind();
4806     ExprResult CtorArg
4807       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4808                                          ParamType, Loc,
4809                                          /*IsArrow=*/false,
4810                                          SS,
4811                                          /*TemplateKWLoc=*/SourceLocation(),
4812                                          /*FirstQualifierInScope=*/nullptr,
4813                                          MemberLookup,
4814                                          /*TemplateArgs=*/nullptr,
4815                                          /*S*/nullptr);
4816     if (CtorArg.isInvalid())
4817       return true;
4818 
4819     // C++11 [class.copy]p15:
4820     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4821     //     with static_cast<T&&>(x.m);
4822     if (RefersToRValueRef(CtorArg.get())) {
4823       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4824     }
4825 
4826     InitializedEntity Entity =
4827         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4828                                                        /*Implicit*/ true)
4829                  : InitializedEntity::InitializeMember(Field, nullptr,
4830                                                        /*Implicit*/ true);
4831 
4832     // Direct-initialize to use the copy constructor.
4833     InitializationKind InitKind =
4834       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4835 
4836     Expr *CtorArgE = CtorArg.getAs<Expr>();
4837     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4838     ExprResult MemberInit =
4839         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4840     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4841     if (MemberInit.isInvalid())
4842       return true;
4843 
4844     if (Indirect)
4845       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4846           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4847     else
4848       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4849           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4850     return false;
4851   }
4852 
4853   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4854          "Unhandled implicit init kind!");
4855 
4856   QualType FieldBaseElementType =
4857     SemaRef.Context.getBaseElementType(Field->getType());
4858 
4859   if (FieldBaseElementType->isRecordType()) {
4860     InitializedEntity InitEntity =
4861         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4862                                                        /*Implicit*/ true)
4863                  : InitializedEntity::InitializeMember(Field, nullptr,
4864                                                        /*Implicit*/ true);
4865     InitializationKind InitKind =
4866       InitializationKind::CreateDefault(Loc);
4867 
4868     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4869     ExprResult MemberInit =
4870       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4871 
4872     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4873     if (MemberInit.isInvalid())
4874       return true;
4875 
4876     if (Indirect)
4877       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4878                                                                Indirect, Loc,
4879                                                                Loc,
4880                                                                MemberInit.get(),
4881                                                                Loc);
4882     else
4883       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4884                                                                Field, Loc, Loc,
4885                                                                MemberInit.get(),
4886                                                                Loc);
4887     return false;
4888   }
4889 
4890   if (!Field->getParent()->isUnion()) {
4891     if (FieldBaseElementType->isReferenceType()) {
4892       SemaRef.Diag(Constructor->getLocation(),
4893                    diag::err_uninitialized_member_in_ctor)
4894       << (int)Constructor->isImplicit()
4895       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4896       << 0 << Field->getDeclName();
4897       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4898       return true;
4899     }
4900 
4901     if (FieldBaseElementType.isConstQualified()) {
4902       SemaRef.Diag(Constructor->getLocation(),
4903                    diag::err_uninitialized_member_in_ctor)
4904       << (int)Constructor->isImplicit()
4905       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4906       << 1 << Field->getDeclName();
4907       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4908       return true;
4909     }
4910   }
4911 
4912   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4913     // ARC and Weak:
4914     //   Default-initialize Objective-C pointers to NULL.
4915     CXXMemberInit
4916       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4917                                                  Loc, Loc,
4918                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4919                                                  Loc);
4920     return false;
4921   }
4922 
4923   // Nothing to initialize.
4924   CXXMemberInit = nullptr;
4925   return false;
4926 }
4927 
4928 namespace {
4929 struct BaseAndFieldInfo {
4930   Sema &S;
4931   CXXConstructorDecl *Ctor;
4932   bool AnyErrorsInInits;
4933   ImplicitInitializerKind IIK;
4934   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4935   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4936   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4937 
4938   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4939     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4940     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4941     if (Ctor->getInheritedConstructor())
4942       IIK = IIK_Inherit;
4943     else if (Generated && Ctor->isCopyConstructor())
4944       IIK = IIK_Copy;
4945     else if (Generated && Ctor->isMoveConstructor())
4946       IIK = IIK_Move;
4947     else
4948       IIK = IIK_Default;
4949   }
4950 
4951   bool isImplicitCopyOrMove() const {
4952     switch (IIK) {
4953     case IIK_Copy:
4954     case IIK_Move:
4955       return true;
4956 
4957     case IIK_Default:
4958     case IIK_Inherit:
4959       return false;
4960     }
4961 
4962     llvm_unreachable("Invalid ImplicitInitializerKind!");
4963   }
4964 
4965   bool addFieldInitializer(CXXCtorInitializer *Init) {
4966     AllToInit.push_back(Init);
4967 
4968     // Check whether this initializer makes the field "used".
4969     if (Init->getInit()->HasSideEffects(S.Context))
4970       S.UnusedPrivateFields.remove(Init->getAnyMember());
4971 
4972     return false;
4973   }
4974 
4975   bool isInactiveUnionMember(FieldDecl *Field) {
4976     RecordDecl *Record = Field->getParent();
4977     if (!Record->isUnion())
4978       return false;
4979 
4980     if (FieldDecl *Active =
4981             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4982       return Active != Field->getCanonicalDecl();
4983 
4984     // In an implicit copy or move constructor, ignore any in-class initializer.
4985     if (isImplicitCopyOrMove())
4986       return true;
4987 
4988     // If there's no explicit initialization, the field is active only if it
4989     // has an in-class initializer...
4990     if (Field->hasInClassInitializer())
4991       return false;
4992     // ... or it's an anonymous struct or union whose class has an in-class
4993     // initializer.
4994     if (!Field->isAnonymousStructOrUnion())
4995       return true;
4996     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4997     return !FieldRD->hasInClassInitializer();
4998   }
4999 
5000   /// Determine whether the given field is, or is within, a union member
5001   /// that is inactive (because there was an initializer given for a different
5002   /// member of the union, or because the union was not initialized at all).
5003   bool isWithinInactiveUnionMember(FieldDecl *Field,
5004                                    IndirectFieldDecl *Indirect) {
5005     if (!Indirect)
5006       return isInactiveUnionMember(Field);
5007 
5008     for (auto *C : Indirect->chain()) {
5009       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5010       if (Field && isInactiveUnionMember(Field))
5011         return true;
5012     }
5013     return false;
5014   }
5015 };
5016 }
5017 
5018 /// Determine whether the given type is an incomplete or zero-lenfgth
5019 /// array type.
5020 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5021   if (T->isIncompleteArrayType())
5022     return true;
5023 
5024   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5025     if (!ArrayT->getSize())
5026       return true;
5027 
5028     T = ArrayT->getElementType();
5029   }
5030 
5031   return false;
5032 }
5033 
5034 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5035                                     FieldDecl *Field,
5036                                     IndirectFieldDecl *Indirect = nullptr) {
5037   if (Field->isInvalidDecl())
5038     return false;
5039 
5040   // Overwhelmingly common case: we have a direct initializer for this field.
5041   if (CXXCtorInitializer *Init =
5042           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5043     return Info.addFieldInitializer(Init);
5044 
5045   // C++11 [class.base.init]p8:
5046   //   if the entity is a non-static data member that has a
5047   //   brace-or-equal-initializer and either
5048   //   -- the constructor's class is a union and no other variant member of that
5049   //      union is designated by a mem-initializer-id or
5050   //   -- the constructor's class is not a union, and, if the entity is a member
5051   //      of an anonymous union, no other member of that union is designated by
5052   //      a mem-initializer-id,
5053   //   the entity is initialized as specified in [dcl.init].
5054   //
5055   // We also apply the same rules to handle anonymous structs within anonymous
5056   // unions.
5057   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5058     return false;
5059 
5060   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5061     ExprResult DIE =
5062         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5063     if (DIE.isInvalid())
5064       return true;
5065 
5066     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5067     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5068 
5069     CXXCtorInitializer *Init;
5070     if (Indirect)
5071       Init = new (SemaRef.Context)
5072           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5073                              SourceLocation(), DIE.get(), SourceLocation());
5074     else
5075       Init = new (SemaRef.Context)
5076           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5077                              SourceLocation(), DIE.get(), SourceLocation());
5078     return Info.addFieldInitializer(Init);
5079   }
5080 
5081   // Don't initialize incomplete or zero-length arrays.
5082   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5083     return false;
5084 
5085   // Don't try to build an implicit initializer if there were semantic
5086   // errors in any of the initializers (and therefore we might be
5087   // missing some that the user actually wrote).
5088   if (Info.AnyErrorsInInits)
5089     return false;
5090 
5091   CXXCtorInitializer *Init = nullptr;
5092   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5093                                      Indirect, Init))
5094     return true;
5095 
5096   if (!Init)
5097     return false;
5098 
5099   return Info.addFieldInitializer(Init);
5100 }
5101 
5102 bool
5103 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5104                                CXXCtorInitializer *Initializer) {
5105   assert(Initializer->isDelegatingInitializer());
5106   Constructor->setNumCtorInitializers(1);
5107   CXXCtorInitializer **initializer =
5108     new (Context) CXXCtorInitializer*[1];
5109   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5110   Constructor->setCtorInitializers(initializer);
5111 
5112   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5113     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5114     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5115   }
5116 
5117   DelegatingCtorDecls.push_back(Constructor);
5118 
5119   DiagnoseUninitializedFields(*this, Constructor);
5120 
5121   return false;
5122 }
5123 
5124 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5125                                ArrayRef<CXXCtorInitializer *> Initializers) {
5126   if (Constructor->isDependentContext()) {
5127     // Just store the initializers as written, they will be checked during
5128     // instantiation.
5129     if (!Initializers.empty()) {
5130       Constructor->setNumCtorInitializers(Initializers.size());
5131       CXXCtorInitializer **baseOrMemberInitializers =
5132         new (Context) CXXCtorInitializer*[Initializers.size()];
5133       memcpy(baseOrMemberInitializers, Initializers.data(),
5134              Initializers.size() * sizeof(CXXCtorInitializer*));
5135       Constructor->setCtorInitializers(baseOrMemberInitializers);
5136     }
5137 
5138     // Let template instantiation know whether we had errors.
5139     if (AnyErrors)
5140       Constructor->setInvalidDecl();
5141 
5142     return false;
5143   }
5144 
5145   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5146 
5147   // We need to build the initializer AST according to order of construction
5148   // and not what user specified in the Initializers list.
5149   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5150   if (!ClassDecl)
5151     return true;
5152 
5153   bool HadError = false;
5154 
5155   for (unsigned i = 0; i < Initializers.size(); i++) {
5156     CXXCtorInitializer *Member = Initializers[i];
5157 
5158     if (Member->isBaseInitializer())
5159       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5160     else {
5161       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5162 
5163       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5164         for (auto *C : F->chain()) {
5165           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5166           if (FD && FD->getParent()->isUnion())
5167             Info.ActiveUnionMember.insert(std::make_pair(
5168                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5169         }
5170       } else if (FieldDecl *FD = Member->getMember()) {
5171         if (FD->getParent()->isUnion())
5172           Info.ActiveUnionMember.insert(std::make_pair(
5173               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5174       }
5175     }
5176   }
5177 
5178   // Keep track of the direct virtual bases.
5179   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5180   for (auto &I : ClassDecl->bases()) {
5181     if (I.isVirtual())
5182       DirectVBases.insert(&I);
5183   }
5184 
5185   // Push virtual bases before others.
5186   for (auto &VBase : ClassDecl->vbases()) {
5187     if (CXXCtorInitializer *Value
5188         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5189       // [class.base.init]p7, per DR257:
5190       //   A mem-initializer where the mem-initializer-id names a virtual base
5191       //   class is ignored during execution of a constructor of any class that
5192       //   is not the most derived class.
5193       if (ClassDecl->isAbstract()) {
5194         // FIXME: Provide a fixit to remove the base specifier. This requires
5195         // tracking the location of the associated comma for a base specifier.
5196         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5197           << VBase.getType() << ClassDecl;
5198         DiagnoseAbstractType(ClassDecl);
5199       }
5200 
5201       Info.AllToInit.push_back(Value);
5202     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5203       // [class.base.init]p8, per DR257:
5204       //   If a given [...] base class is not named by a mem-initializer-id
5205       //   [...] and the entity is not a virtual base class of an abstract
5206       //   class, then [...] the entity is default-initialized.
5207       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5208       CXXCtorInitializer *CXXBaseInit;
5209       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5210                                        &VBase, IsInheritedVirtualBase,
5211                                        CXXBaseInit)) {
5212         HadError = true;
5213         continue;
5214       }
5215 
5216       Info.AllToInit.push_back(CXXBaseInit);
5217     }
5218   }
5219 
5220   // Non-virtual bases.
5221   for (auto &Base : ClassDecl->bases()) {
5222     // Virtuals are in the virtual base list and already constructed.
5223     if (Base.isVirtual())
5224       continue;
5225 
5226     if (CXXCtorInitializer *Value
5227           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5228       Info.AllToInit.push_back(Value);
5229     } else if (!AnyErrors) {
5230       CXXCtorInitializer *CXXBaseInit;
5231       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5232                                        &Base, /*IsInheritedVirtualBase=*/false,
5233                                        CXXBaseInit)) {
5234         HadError = true;
5235         continue;
5236       }
5237 
5238       Info.AllToInit.push_back(CXXBaseInit);
5239     }
5240   }
5241 
5242   // Fields.
5243   for (auto *Mem : ClassDecl->decls()) {
5244     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5245       // C++ [class.bit]p2:
5246       //   A declaration for a bit-field that omits the identifier declares an
5247       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5248       //   initialized.
5249       if (F->isUnnamedBitfield())
5250         continue;
5251 
5252       // If we're not generating the implicit copy/move constructor, then we'll
5253       // handle anonymous struct/union fields based on their individual
5254       // indirect fields.
5255       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5256         continue;
5257 
5258       if (CollectFieldInitializer(*this, Info, F))
5259         HadError = true;
5260       continue;
5261     }
5262 
5263     // Beyond this point, we only consider default initialization.
5264     if (Info.isImplicitCopyOrMove())
5265       continue;
5266 
5267     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5268       if (F->getType()->isIncompleteArrayType()) {
5269         assert(ClassDecl->hasFlexibleArrayMember() &&
5270                "Incomplete array type is not valid");
5271         continue;
5272       }
5273 
5274       // Initialize each field of an anonymous struct individually.
5275       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5276         HadError = true;
5277 
5278       continue;
5279     }
5280   }
5281 
5282   unsigned NumInitializers = Info.AllToInit.size();
5283   if (NumInitializers > 0) {
5284     Constructor->setNumCtorInitializers(NumInitializers);
5285     CXXCtorInitializer **baseOrMemberInitializers =
5286       new (Context) CXXCtorInitializer*[NumInitializers];
5287     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5288            NumInitializers * sizeof(CXXCtorInitializer*));
5289     Constructor->setCtorInitializers(baseOrMemberInitializers);
5290 
5291     // Constructors implicitly reference the base and member
5292     // destructors.
5293     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5294                                            Constructor->getParent());
5295   }
5296 
5297   return HadError;
5298 }
5299 
5300 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5301   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5302     const RecordDecl *RD = RT->getDecl();
5303     if (RD->isAnonymousStructOrUnion()) {
5304       for (auto *Field : RD->fields())
5305         PopulateKeysForFields(Field, IdealInits);
5306       return;
5307     }
5308   }
5309   IdealInits.push_back(Field->getCanonicalDecl());
5310 }
5311 
5312 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5313   return Context.getCanonicalType(BaseType).getTypePtr();
5314 }
5315 
5316 static const void *GetKeyForMember(ASTContext &Context,
5317                                    CXXCtorInitializer *Member) {
5318   if (!Member->isAnyMemberInitializer())
5319     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5320 
5321   return Member->getAnyMember()->getCanonicalDecl();
5322 }
5323 
5324 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5325                                  const CXXCtorInitializer *Previous,
5326                                  const CXXCtorInitializer *Current) {
5327   if (Previous->isAnyMemberInitializer())
5328     Diag << 0 << Previous->getAnyMember();
5329   else
5330     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5331 
5332   if (Current->isAnyMemberInitializer())
5333     Diag << 0 << Current->getAnyMember();
5334   else
5335     Diag << 1 << Current->getTypeSourceInfo()->getType();
5336 }
5337 
5338 static void DiagnoseBaseOrMemInitializerOrder(
5339     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5340     ArrayRef<CXXCtorInitializer *> Inits) {
5341   if (Constructor->getDeclContext()->isDependentContext())
5342     return;
5343 
5344   // Don't check initializers order unless the warning is enabled at the
5345   // location of at least one initializer.
5346   bool ShouldCheckOrder = false;
5347   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5348     CXXCtorInitializer *Init = Inits[InitIndex];
5349     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5350                                  Init->getSourceLocation())) {
5351       ShouldCheckOrder = true;
5352       break;
5353     }
5354   }
5355   if (!ShouldCheckOrder)
5356     return;
5357 
5358   // Build the list of bases and members in the order that they'll
5359   // actually be initialized.  The explicit initializers should be in
5360   // this same order but may be missing things.
5361   SmallVector<const void*, 32> IdealInitKeys;
5362 
5363   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5364 
5365   // 1. Virtual bases.
5366   for (const auto &VBase : ClassDecl->vbases())
5367     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5368 
5369   // 2. Non-virtual bases.
5370   for (const auto &Base : ClassDecl->bases()) {
5371     if (Base.isVirtual())
5372       continue;
5373     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5374   }
5375 
5376   // 3. Direct fields.
5377   for (auto *Field : ClassDecl->fields()) {
5378     if (Field->isUnnamedBitfield())
5379       continue;
5380 
5381     PopulateKeysForFields(Field, IdealInitKeys);
5382   }
5383 
5384   unsigned NumIdealInits = IdealInitKeys.size();
5385   unsigned IdealIndex = 0;
5386 
5387   // Track initializers that are in an incorrect order for either a warning or
5388   // note if multiple ones occur.
5389   SmallVector<unsigned> WarnIndexes;
5390   // Correlates the index of an initializer in the init-list to the index of
5391   // the field/base in the class.
5392   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5393 
5394   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5395     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5396 
5397     // Scan forward to try to find this initializer in the idealized
5398     // initializers list.
5399     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5400       if (InitKey == IdealInitKeys[IdealIndex])
5401         break;
5402 
5403     // If we didn't find this initializer, it must be because we
5404     // scanned past it on a previous iteration.  That can only
5405     // happen if we're out of order;  emit a warning.
5406     if (IdealIndex == NumIdealInits && InitIndex) {
5407       WarnIndexes.push_back(InitIndex);
5408 
5409       // Move back to the initializer's location in the ideal list.
5410       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5411         if (InitKey == IdealInitKeys[IdealIndex])
5412           break;
5413 
5414       assert(IdealIndex < NumIdealInits &&
5415              "initializer not found in initializer list");
5416     }
5417     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5418   }
5419 
5420   if (WarnIndexes.empty())
5421     return;
5422 
5423   // Sort based on the ideal order, first in the pair.
5424   llvm::sort(CorrelatedInitOrder,
5425              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5426 
5427   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5428   // emit the diagnostic before we can try adding notes.
5429   {
5430     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5431         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5432         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5433                                 : diag::warn_some_initializers_out_of_order);
5434 
5435     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5436       if (CorrelatedInitOrder[I].second == I)
5437         continue;
5438       // Ideally we would be using InsertFromRange here, but clang doesn't
5439       // appear to handle InsertFromRange correctly when the source range is
5440       // modified by another fix-it.
5441       D << FixItHint::CreateReplacement(
5442           Inits[I]->getSourceRange(),
5443           Lexer::getSourceText(
5444               CharSourceRange::getTokenRange(
5445                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5446               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5447     }
5448 
5449     // If there is only 1 item out of order, the warning expects the name and
5450     // type of each being added to it.
5451     if (WarnIndexes.size() == 1) {
5452       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5453                            Inits[WarnIndexes.front()]);
5454       return;
5455     }
5456   }
5457   // More than 1 item to warn, create notes letting the user know which ones
5458   // are bad.
5459   for (unsigned WarnIndex : WarnIndexes) {
5460     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5461     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5462                           diag::note_initializer_out_of_order);
5463     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5464     D << PrevInit->getSourceRange();
5465   }
5466 }
5467 
5468 namespace {
5469 bool CheckRedundantInit(Sema &S,
5470                         CXXCtorInitializer *Init,
5471                         CXXCtorInitializer *&PrevInit) {
5472   if (!PrevInit) {
5473     PrevInit = Init;
5474     return false;
5475   }
5476 
5477   if (FieldDecl *Field = Init->getAnyMember())
5478     S.Diag(Init->getSourceLocation(),
5479            diag::err_multiple_mem_initialization)
5480       << Field->getDeclName()
5481       << Init->getSourceRange();
5482   else {
5483     const Type *BaseClass = Init->getBaseClass();
5484     assert(BaseClass && "neither field nor base");
5485     S.Diag(Init->getSourceLocation(),
5486            diag::err_multiple_base_initialization)
5487       << QualType(BaseClass, 0)
5488       << Init->getSourceRange();
5489   }
5490   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5491     << 0 << PrevInit->getSourceRange();
5492 
5493   return true;
5494 }
5495 
5496 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5497 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5498 
5499 bool CheckRedundantUnionInit(Sema &S,
5500                              CXXCtorInitializer *Init,
5501                              RedundantUnionMap &Unions) {
5502   FieldDecl *Field = Init->getAnyMember();
5503   RecordDecl *Parent = Field->getParent();
5504   NamedDecl *Child = Field;
5505 
5506   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5507     if (Parent->isUnion()) {
5508       UnionEntry &En = Unions[Parent];
5509       if (En.first && En.first != Child) {
5510         S.Diag(Init->getSourceLocation(),
5511                diag::err_multiple_mem_union_initialization)
5512           << Field->getDeclName()
5513           << Init->getSourceRange();
5514         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5515           << 0 << En.second->getSourceRange();
5516         return true;
5517       }
5518       if (!En.first) {
5519         En.first = Child;
5520         En.second = Init;
5521       }
5522       if (!Parent->isAnonymousStructOrUnion())
5523         return false;
5524     }
5525 
5526     Child = Parent;
5527     Parent = cast<RecordDecl>(Parent->getDeclContext());
5528   }
5529 
5530   return false;
5531 }
5532 } // namespace
5533 
5534 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5535 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5536                                 SourceLocation ColonLoc,
5537                                 ArrayRef<CXXCtorInitializer*> MemInits,
5538                                 bool AnyErrors) {
5539   if (!ConstructorDecl)
5540     return;
5541 
5542   AdjustDeclIfTemplate(ConstructorDecl);
5543 
5544   CXXConstructorDecl *Constructor
5545     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5546 
5547   if (!Constructor) {
5548     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5549     return;
5550   }
5551 
5552   // Mapping for the duplicate initializers check.
5553   // For member initializers, this is keyed with a FieldDecl*.
5554   // For base initializers, this is keyed with a Type*.
5555   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5556 
5557   // Mapping for the inconsistent anonymous-union initializers check.
5558   RedundantUnionMap MemberUnions;
5559 
5560   bool HadError = false;
5561   for (unsigned i = 0; i < MemInits.size(); i++) {
5562     CXXCtorInitializer *Init = MemInits[i];
5563 
5564     // Set the source order index.
5565     Init->setSourceOrder(i);
5566 
5567     if (Init->isAnyMemberInitializer()) {
5568       const void *Key = GetKeyForMember(Context, Init);
5569       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5570           CheckRedundantUnionInit(*this, Init, MemberUnions))
5571         HadError = true;
5572     } else if (Init->isBaseInitializer()) {
5573       const void *Key = GetKeyForMember(Context, Init);
5574       if (CheckRedundantInit(*this, Init, Members[Key]))
5575         HadError = true;
5576     } else {
5577       assert(Init->isDelegatingInitializer());
5578       // This must be the only initializer
5579       if (MemInits.size() != 1) {
5580         Diag(Init->getSourceLocation(),
5581              diag::err_delegating_initializer_alone)
5582           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5583         // We will treat this as being the only initializer.
5584       }
5585       SetDelegatingInitializer(Constructor, MemInits[i]);
5586       // Return immediately as the initializer is set.
5587       return;
5588     }
5589   }
5590 
5591   if (HadError)
5592     return;
5593 
5594   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5595 
5596   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5597 
5598   DiagnoseUninitializedFields(*this, Constructor);
5599 }
5600 
5601 void
5602 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5603                                              CXXRecordDecl *ClassDecl) {
5604   // Ignore dependent contexts. Also ignore unions, since their members never
5605   // have destructors implicitly called.
5606   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5607     return;
5608 
5609   // FIXME: all the access-control diagnostics are positioned on the
5610   // field/base declaration.  That's probably good; that said, the
5611   // user might reasonably want to know why the destructor is being
5612   // emitted, and we currently don't say.
5613 
5614   // Non-static data members.
5615   for (auto *Field : ClassDecl->fields()) {
5616     if (Field->isInvalidDecl())
5617       continue;
5618 
5619     // Don't destroy incomplete or zero-length arrays.
5620     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5621       continue;
5622 
5623     QualType FieldType = Context.getBaseElementType(Field->getType());
5624 
5625     const RecordType* RT = FieldType->getAs<RecordType>();
5626     if (!RT)
5627       continue;
5628 
5629     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5630     if (FieldClassDecl->isInvalidDecl())
5631       continue;
5632     if (FieldClassDecl->hasIrrelevantDestructor())
5633       continue;
5634     // The destructor for an implicit anonymous union member is never invoked.
5635     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5636       continue;
5637 
5638     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5639     assert(Dtor && "No dtor found for FieldClassDecl!");
5640     CheckDestructorAccess(Field->getLocation(), Dtor,
5641                           PDiag(diag::err_access_dtor_field)
5642                             << Field->getDeclName()
5643                             << FieldType);
5644 
5645     MarkFunctionReferenced(Location, Dtor);
5646     DiagnoseUseOfDecl(Dtor, Location);
5647   }
5648 
5649   // We only potentially invoke the destructors of potentially constructed
5650   // subobjects.
5651   bool VisitVirtualBases = !ClassDecl->isAbstract();
5652 
5653   // If the destructor exists and has already been marked used in the MS ABI,
5654   // then virtual base destructors have already been checked and marked used.
5655   // Skip checking them again to avoid duplicate diagnostics.
5656   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5657     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5658     if (Dtor && Dtor->isUsed())
5659       VisitVirtualBases = false;
5660   }
5661 
5662   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5663 
5664   // Bases.
5665   for (const auto &Base : ClassDecl->bases()) {
5666     const RecordType *RT = Base.getType()->getAs<RecordType>();
5667     if (!RT)
5668       continue;
5669 
5670     // Remember direct virtual bases.
5671     if (Base.isVirtual()) {
5672       if (!VisitVirtualBases)
5673         continue;
5674       DirectVirtualBases.insert(RT);
5675     }
5676 
5677     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5678     // If our base class is invalid, we probably can't get its dtor anyway.
5679     if (BaseClassDecl->isInvalidDecl())
5680       continue;
5681     if (BaseClassDecl->hasIrrelevantDestructor())
5682       continue;
5683 
5684     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5685     assert(Dtor && "No dtor found for BaseClassDecl!");
5686 
5687     // FIXME: caret should be on the start of the class name
5688     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5689                           PDiag(diag::err_access_dtor_base)
5690                               << Base.getType() << Base.getSourceRange(),
5691                           Context.getTypeDeclType(ClassDecl));
5692 
5693     MarkFunctionReferenced(Location, Dtor);
5694     DiagnoseUseOfDecl(Dtor, Location);
5695   }
5696 
5697   if (VisitVirtualBases)
5698     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5699                                          &DirectVirtualBases);
5700 }
5701 
5702 void Sema::MarkVirtualBaseDestructorsReferenced(
5703     SourceLocation Location, CXXRecordDecl *ClassDecl,
5704     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5705   // Virtual bases.
5706   for (const auto &VBase : ClassDecl->vbases()) {
5707     // Bases are always records in a well-formed non-dependent class.
5708     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5709 
5710     // Ignore already visited direct virtual bases.
5711     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5712       continue;
5713 
5714     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5715     // If our base class is invalid, we probably can't get its dtor anyway.
5716     if (BaseClassDecl->isInvalidDecl())
5717       continue;
5718     if (BaseClassDecl->hasIrrelevantDestructor())
5719       continue;
5720 
5721     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5722     assert(Dtor && "No dtor found for BaseClassDecl!");
5723     if (CheckDestructorAccess(
5724             ClassDecl->getLocation(), Dtor,
5725             PDiag(diag::err_access_dtor_vbase)
5726                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5727             Context.getTypeDeclType(ClassDecl)) ==
5728         AR_accessible) {
5729       CheckDerivedToBaseConversion(
5730           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5731           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5732           SourceRange(), DeclarationName(), nullptr);
5733     }
5734 
5735     MarkFunctionReferenced(Location, Dtor);
5736     DiagnoseUseOfDecl(Dtor, Location);
5737   }
5738 }
5739 
5740 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5741   if (!CDtorDecl)
5742     return;
5743 
5744   if (CXXConstructorDecl *Constructor
5745       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5746     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5747     DiagnoseUninitializedFields(*this, Constructor);
5748   }
5749 }
5750 
5751 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5752   if (!getLangOpts().CPlusPlus)
5753     return false;
5754 
5755   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5756   if (!RD)
5757     return false;
5758 
5759   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5760   // class template specialization here, but doing so breaks a lot of code.
5761 
5762   // We can't answer whether something is abstract until it has a
5763   // definition. If it's currently being defined, we'll walk back
5764   // over all the declarations when we have a full definition.
5765   const CXXRecordDecl *Def = RD->getDefinition();
5766   if (!Def || Def->isBeingDefined())
5767     return false;
5768 
5769   return RD->isAbstract();
5770 }
5771 
5772 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5773                                   TypeDiagnoser &Diagnoser) {
5774   if (!isAbstractType(Loc, T))
5775     return false;
5776 
5777   T = Context.getBaseElementType(T);
5778   Diagnoser.diagnose(*this, Loc, T);
5779   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5780   return true;
5781 }
5782 
5783 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5784   // Check if we've already emitted the list of pure virtual functions
5785   // for this class.
5786   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5787     return;
5788 
5789   // If the diagnostic is suppressed, don't emit the notes. We're only
5790   // going to emit them once, so try to attach them to a diagnostic we're
5791   // actually going to show.
5792   if (Diags.isLastDiagnosticIgnored())
5793     return;
5794 
5795   CXXFinalOverriderMap FinalOverriders;
5796   RD->getFinalOverriders(FinalOverriders);
5797 
5798   // Keep a set of seen pure methods so we won't diagnose the same method
5799   // more than once.
5800   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5801 
5802   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5803                                    MEnd = FinalOverriders.end();
5804        M != MEnd;
5805        ++M) {
5806     for (OverridingMethods::iterator SO = M->second.begin(),
5807                                   SOEnd = M->second.end();
5808          SO != SOEnd; ++SO) {
5809       // C++ [class.abstract]p4:
5810       //   A class is abstract if it contains or inherits at least one
5811       //   pure virtual function for which the final overrider is pure
5812       //   virtual.
5813 
5814       //
5815       if (SO->second.size() != 1)
5816         continue;
5817 
5818       if (!SO->second.front().Method->isPure())
5819         continue;
5820 
5821       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5822         continue;
5823 
5824       Diag(SO->second.front().Method->getLocation(),
5825            diag::note_pure_virtual_function)
5826         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5827     }
5828   }
5829 
5830   if (!PureVirtualClassDiagSet)
5831     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5832   PureVirtualClassDiagSet->insert(RD);
5833 }
5834 
5835 namespace {
5836 struct AbstractUsageInfo {
5837   Sema &S;
5838   CXXRecordDecl *Record;
5839   CanQualType AbstractType;
5840   bool Invalid;
5841 
5842   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5843     : S(S), Record(Record),
5844       AbstractType(S.Context.getCanonicalType(
5845                    S.Context.getTypeDeclType(Record))),
5846       Invalid(false) {}
5847 
5848   void DiagnoseAbstractType() {
5849     if (Invalid) return;
5850     S.DiagnoseAbstractType(Record);
5851     Invalid = true;
5852   }
5853 
5854   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5855 };
5856 
5857 struct CheckAbstractUsage {
5858   AbstractUsageInfo &Info;
5859   const NamedDecl *Ctx;
5860 
5861   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5862     : Info(Info), Ctx(Ctx) {}
5863 
5864   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5865     switch (TL.getTypeLocClass()) {
5866 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5867 #define TYPELOC(CLASS, PARENT) \
5868     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5869 #include "clang/AST/TypeLocNodes.def"
5870     }
5871   }
5872 
5873   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5874     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5875     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5876       if (!TL.getParam(I))
5877         continue;
5878 
5879       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5880       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5881     }
5882   }
5883 
5884   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5885     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5886   }
5887 
5888   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5889     // Visit the type parameters from a permissive context.
5890     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5891       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5892       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5893         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5894           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5895       // TODO: other template argument types?
5896     }
5897   }
5898 
5899   // Visit pointee types from a permissive context.
5900 #define CheckPolymorphic(Type) \
5901   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5902     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5903   }
5904   CheckPolymorphic(PointerTypeLoc)
5905   CheckPolymorphic(ReferenceTypeLoc)
5906   CheckPolymorphic(MemberPointerTypeLoc)
5907   CheckPolymorphic(BlockPointerTypeLoc)
5908   CheckPolymorphic(AtomicTypeLoc)
5909 
5910   /// Handle all the types we haven't given a more specific
5911   /// implementation for above.
5912   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5913     // Every other kind of type that we haven't called out already
5914     // that has an inner type is either (1) sugar or (2) contains that
5915     // inner type in some way as a subobject.
5916     if (TypeLoc Next = TL.getNextTypeLoc())
5917       return Visit(Next, Sel);
5918 
5919     // If there's no inner type and we're in a permissive context,
5920     // don't diagnose.
5921     if (Sel == Sema::AbstractNone) return;
5922 
5923     // Check whether the type matches the abstract type.
5924     QualType T = TL.getType();
5925     if (T->isArrayType()) {
5926       Sel = Sema::AbstractArrayType;
5927       T = Info.S.Context.getBaseElementType(T);
5928     }
5929     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5930     if (CT != Info.AbstractType) return;
5931 
5932     // It matched; do some magic.
5933     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5934     if (Sel == Sema::AbstractArrayType) {
5935       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5936         << T << TL.getSourceRange();
5937     } else {
5938       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5939         << Sel << T << TL.getSourceRange();
5940     }
5941     Info.DiagnoseAbstractType();
5942   }
5943 };
5944 
5945 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5946                                   Sema::AbstractDiagSelID Sel) {
5947   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5948 }
5949 
5950 }
5951 
5952 /// Check for invalid uses of an abstract type in a function declaration.
5953 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5954                                     FunctionDecl *FD) {
5955   // No need to do the check on definitions, which require that
5956   // the return/param types be complete.
5957   if (FD->doesThisDeclarationHaveABody())
5958     return;
5959 
5960   // For safety's sake, just ignore it if we don't have type source
5961   // information.  This should never happen for non-implicit methods,
5962   // but...
5963   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5964     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5965 }
5966 
5967 /// Check for invalid uses of an abstract type in a variable0 declaration.
5968 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5969                                     VarDecl *VD) {
5970   // No need to do the check on definitions, which require that
5971   // the type is complete.
5972   if (VD->isThisDeclarationADefinition())
5973     return;
5974 
5975   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5976                  Sema::AbstractVariableType);
5977 }
5978 
5979 /// Check for invalid uses of an abstract type within a class definition.
5980 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5981                                     CXXRecordDecl *RD) {
5982   for (auto *D : RD->decls()) {
5983     if (D->isImplicit()) continue;
5984 
5985     // Step through friends to the befriended declaration.
5986     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5987       D = FD->getFriendDecl();
5988       if (!D) continue;
5989     }
5990 
5991     // Functions and function templates.
5992     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5993       CheckAbstractClassUsage(Info, FD);
5994     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
5995       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
5996 
5997     // Fields and static variables.
5998     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
5999       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6000         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6001     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6002       CheckAbstractClassUsage(Info, VD);
6003     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6004       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6005 
6006     // Nested classes and class templates.
6007     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6008       CheckAbstractClassUsage(Info, RD);
6009     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6010       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6011     }
6012   }
6013 }
6014 
6015 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6016   Attr *ClassAttr = getDLLAttr(Class);
6017   if (!ClassAttr)
6018     return;
6019 
6020   assert(ClassAttr->getKind() == attr::DLLExport);
6021 
6022   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6023 
6024   if (TSK == TSK_ExplicitInstantiationDeclaration)
6025     // Don't go any further if this is just an explicit instantiation
6026     // declaration.
6027     return;
6028 
6029   // Add a context note to explain how we got to any diagnostics produced below.
6030   struct MarkingClassDllexported {
6031     Sema &S;
6032     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6033                             SourceLocation AttrLoc)
6034         : S(S) {
6035       Sema::CodeSynthesisContext Ctx;
6036       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6037       Ctx.PointOfInstantiation = AttrLoc;
6038       Ctx.Entity = Class;
6039       S.pushCodeSynthesisContext(Ctx);
6040     }
6041     ~MarkingClassDllexported() {
6042       S.popCodeSynthesisContext();
6043     }
6044   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6045 
6046   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6047     S.MarkVTableUsed(Class->getLocation(), Class, true);
6048 
6049   for (Decl *Member : Class->decls()) {
6050     // Skip members that were not marked exported.
6051     if (!Member->hasAttr<DLLExportAttr>())
6052       continue;
6053 
6054     // Defined static variables that are members of an exported base
6055     // class must be marked export too.
6056     auto *VD = dyn_cast<VarDecl>(Member);
6057     if (VD && VD->getStorageClass() == SC_Static &&
6058         TSK == TSK_ImplicitInstantiation)
6059       S.MarkVariableReferenced(VD->getLocation(), VD);
6060 
6061     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6062     if (!MD)
6063       continue;
6064 
6065     if (MD->isUserProvided()) {
6066       // Instantiate non-default class member functions ...
6067 
6068       // .. except for certain kinds of template specializations.
6069       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6070         continue;
6071 
6072       // If this is an MS ABI dllexport default constructor, instantiate any
6073       // default arguments.
6074       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6075         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6076         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6077           S.InstantiateDefaultCtorDefaultArgs(CD);
6078         }
6079       }
6080 
6081       S.MarkFunctionReferenced(Class->getLocation(), MD);
6082 
6083       // The function will be passed to the consumer when its definition is
6084       // encountered.
6085     } else if (MD->isExplicitlyDefaulted()) {
6086       // Synthesize and instantiate explicitly defaulted methods.
6087       S.MarkFunctionReferenced(Class->getLocation(), MD);
6088 
6089       if (TSK != TSK_ExplicitInstantiationDefinition) {
6090         // Except for explicit instantiation defs, we will not see the
6091         // definition again later, so pass it to the consumer now.
6092         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6093       }
6094     } else if (!MD->isTrivial() ||
6095                MD->isCopyAssignmentOperator() ||
6096                MD->isMoveAssignmentOperator()) {
6097       // Synthesize and instantiate non-trivial implicit methods, and the copy
6098       // and move assignment operators. The latter are exported even if they
6099       // are trivial, because the address of an operator can be taken and
6100       // should compare equal across libraries.
6101       S.MarkFunctionReferenced(Class->getLocation(), MD);
6102 
6103       // There is no later point when we will see the definition of this
6104       // function, so pass it to the consumer now.
6105       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6106     }
6107   }
6108 }
6109 
6110 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6111                                                         CXXRecordDecl *Class) {
6112   // Only the MS ABI has default constructor closures, so we don't need to do
6113   // this semantic checking anywhere else.
6114   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6115     return;
6116 
6117   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6118   for (Decl *Member : Class->decls()) {
6119     // Look for exported default constructors.
6120     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6121     if (!CD || !CD->isDefaultConstructor())
6122       continue;
6123     auto *Attr = CD->getAttr<DLLExportAttr>();
6124     if (!Attr)
6125       continue;
6126 
6127     // If the class is non-dependent, mark the default arguments as ODR-used so
6128     // that we can properly codegen the constructor closure.
6129     if (!Class->isDependentContext()) {
6130       for (ParmVarDecl *PD : CD->parameters()) {
6131         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6132         S.DiscardCleanupsInEvaluationContext();
6133       }
6134     }
6135 
6136     if (LastExportedDefaultCtor) {
6137       S.Diag(LastExportedDefaultCtor->getLocation(),
6138              diag::err_attribute_dll_ambiguous_default_ctor)
6139           << Class;
6140       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6141           << CD->getDeclName();
6142       return;
6143     }
6144     LastExportedDefaultCtor = CD;
6145   }
6146 }
6147 
6148 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6149                                                        CXXRecordDecl *Class) {
6150   bool ErrorReported = false;
6151   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6152                                                      ClassTemplateDecl *TD) {
6153     if (ErrorReported)
6154       return;
6155     S.Diag(TD->getLocation(),
6156            diag::err_cuda_device_builtin_surftex_cls_template)
6157         << /*surface*/ 0 << TD;
6158     ErrorReported = true;
6159   };
6160 
6161   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6162   if (!TD) {
6163     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6164     if (!SD) {
6165       S.Diag(Class->getLocation(),
6166              diag::err_cuda_device_builtin_surftex_ref_decl)
6167           << /*surface*/ 0 << Class;
6168       S.Diag(Class->getLocation(),
6169              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6170           << Class;
6171       return;
6172     }
6173     TD = SD->getSpecializedTemplate();
6174   }
6175 
6176   TemplateParameterList *Params = TD->getTemplateParameters();
6177   unsigned N = Params->size();
6178 
6179   if (N != 2) {
6180     reportIllegalClassTemplate(S, TD);
6181     S.Diag(TD->getLocation(),
6182            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6183         << TD << 2;
6184   }
6185   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6186     reportIllegalClassTemplate(S, TD);
6187     S.Diag(TD->getLocation(),
6188            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6189         << TD << /*1st*/ 0 << /*type*/ 0;
6190   }
6191   if (N > 1) {
6192     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6193     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6194       reportIllegalClassTemplate(S, TD);
6195       S.Diag(TD->getLocation(),
6196              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6197           << TD << /*2nd*/ 1 << /*integer*/ 1;
6198     }
6199   }
6200 }
6201 
6202 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6203                                                        CXXRecordDecl *Class) {
6204   bool ErrorReported = false;
6205   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6206                                                      ClassTemplateDecl *TD) {
6207     if (ErrorReported)
6208       return;
6209     S.Diag(TD->getLocation(),
6210            diag::err_cuda_device_builtin_surftex_cls_template)
6211         << /*texture*/ 1 << TD;
6212     ErrorReported = true;
6213   };
6214 
6215   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6216   if (!TD) {
6217     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6218     if (!SD) {
6219       S.Diag(Class->getLocation(),
6220              diag::err_cuda_device_builtin_surftex_ref_decl)
6221           << /*texture*/ 1 << Class;
6222       S.Diag(Class->getLocation(),
6223              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6224           << Class;
6225       return;
6226     }
6227     TD = SD->getSpecializedTemplate();
6228   }
6229 
6230   TemplateParameterList *Params = TD->getTemplateParameters();
6231   unsigned N = Params->size();
6232 
6233   if (N != 3) {
6234     reportIllegalClassTemplate(S, TD);
6235     S.Diag(TD->getLocation(),
6236            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6237         << TD << 3;
6238   }
6239   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6240     reportIllegalClassTemplate(S, TD);
6241     S.Diag(TD->getLocation(),
6242            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6243         << TD << /*1st*/ 0 << /*type*/ 0;
6244   }
6245   if (N > 1) {
6246     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6247     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6248       reportIllegalClassTemplate(S, TD);
6249       S.Diag(TD->getLocation(),
6250              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6251           << TD << /*2nd*/ 1 << /*integer*/ 1;
6252     }
6253   }
6254   if (N > 2) {
6255     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6256     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6257       reportIllegalClassTemplate(S, TD);
6258       S.Diag(TD->getLocation(),
6259              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6260           << TD << /*3rd*/ 2 << /*integer*/ 1;
6261     }
6262   }
6263 }
6264 
6265 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6266   // Mark any compiler-generated routines with the implicit code_seg attribute.
6267   for (auto *Method : Class->methods()) {
6268     if (Method->isUserProvided())
6269       continue;
6270     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6271       Method->addAttr(A);
6272   }
6273 }
6274 
6275 /// Check class-level dllimport/dllexport attribute.
6276 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6277   Attr *ClassAttr = getDLLAttr(Class);
6278 
6279   // MSVC inherits DLL attributes to partial class template specializations.
6280   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6281     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6282       if (Attr *TemplateAttr =
6283               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6284         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6285         A->setInherited(true);
6286         ClassAttr = A;
6287       }
6288     }
6289   }
6290 
6291   if (!ClassAttr)
6292     return;
6293 
6294   if (!Class->isExternallyVisible()) {
6295     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6296         << Class << ClassAttr;
6297     return;
6298   }
6299 
6300   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6301       !ClassAttr->isInherited()) {
6302     // Diagnose dll attributes on members of class with dll attribute.
6303     for (Decl *Member : Class->decls()) {
6304       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6305         continue;
6306       InheritableAttr *MemberAttr = getDLLAttr(Member);
6307       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6308         continue;
6309 
6310       Diag(MemberAttr->getLocation(),
6311              diag::err_attribute_dll_member_of_dll_class)
6312           << MemberAttr << ClassAttr;
6313       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6314       Member->setInvalidDecl();
6315     }
6316   }
6317 
6318   if (Class->getDescribedClassTemplate())
6319     // Don't inherit dll attribute until the template is instantiated.
6320     return;
6321 
6322   // The class is either imported or exported.
6323   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6324 
6325   // Check if this was a dllimport attribute propagated from a derived class to
6326   // a base class template specialization. We don't apply these attributes to
6327   // static data members.
6328   const bool PropagatedImport =
6329       !ClassExported &&
6330       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6331 
6332   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6333 
6334   // Ignore explicit dllexport on explicit class template instantiation
6335   // declarations, except in MinGW mode.
6336   if (ClassExported && !ClassAttr->isInherited() &&
6337       TSK == TSK_ExplicitInstantiationDeclaration &&
6338       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6339     Class->dropAttr<DLLExportAttr>();
6340     return;
6341   }
6342 
6343   // Force declaration of implicit members so they can inherit the attribute.
6344   ForceDeclarationOfImplicitMembers(Class);
6345 
6346   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6347   // seem to be true in practice?
6348 
6349   for (Decl *Member : Class->decls()) {
6350     VarDecl *VD = dyn_cast<VarDecl>(Member);
6351     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6352 
6353     // Only methods and static fields inherit the attributes.
6354     if (!VD && !MD)
6355       continue;
6356 
6357     if (MD) {
6358       // Don't process deleted methods.
6359       if (MD->isDeleted())
6360         continue;
6361 
6362       if (MD->isInlined()) {
6363         // MinGW does not import or export inline methods. But do it for
6364         // template instantiations.
6365         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6366             TSK != TSK_ExplicitInstantiationDeclaration &&
6367             TSK != TSK_ExplicitInstantiationDefinition)
6368           continue;
6369 
6370         // MSVC versions before 2015 don't export the move assignment operators
6371         // and move constructor, so don't attempt to import/export them if
6372         // we have a definition.
6373         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6374         if ((MD->isMoveAssignmentOperator() ||
6375              (Ctor && Ctor->isMoveConstructor())) &&
6376             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6377           continue;
6378 
6379         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6380         // operator is exported anyway.
6381         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6382             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6383           continue;
6384       }
6385     }
6386 
6387     // Don't apply dllimport attributes to static data members of class template
6388     // instantiations when the attribute is propagated from a derived class.
6389     if (VD && PropagatedImport)
6390       continue;
6391 
6392     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6393       continue;
6394 
6395     if (!getDLLAttr(Member)) {
6396       InheritableAttr *NewAttr = nullptr;
6397 
6398       // Do not export/import inline function when -fno-dllexport-inlines is
6399       // passed. But add attribute for later local static var check.
6400       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6401           TSK != TSK_ExplicitInstantiationDeclaration &&
6402           TSK != TSK_ExplicitInstantiationDefinition) {
6403         if (ClassExported) {
6404           NewAttr = ::new (getASTContext())
6405               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6406         } else {
6407           NewAttr = ::new (getASTContext())
6408               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6409         }
6410       } else {
6411         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6412       }
6413 
6414       NewAttr->setInherited(true);
6415       Member->addAttr(NewAttr);
6416 
6417       if (MD) {
6418         // Propagate DLLAttr to friend re-declarations of MD that have already
6419         // been constructed.
6420         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6421              FD = FD->getPreviousDecl()) {
6422           if (FD->getFriendObjectKind() == Decl::FOK_None)
6423             continue;
6424           assert(!getDLLAttr(FD) &&
6425                  "friend re-decl should not already have a DLLAttr");
6426           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6427           NewAttr->setInherited(true);
6428           FD->addAttr(NewAttr);
6429         }
6430       }
6431     }
6432   }
6433 
6434   if (ClassExported)
6435     DelayedDllExportClasses.push_back(Class);
6436 }
6437 
6438 /// Perform propagation of DLL attributes from a derived class to a
6439 /// templated base class for MS compatibility.
6440 void Sema::propagateDLLAttrToBaseClassTemplate(
6441     CXXRecordDecl *Class, Attr *ClassAttr,
6442     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6443   if (getDLLAttr(
6444           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6445     // If the base class template has a DLL attribute, don't try to change it.
6446     return;
6447   }
6448 
6449   auto TSK = BaseTemplateSpec->getSpecializationKind();
6450   if (!getDLLAttr(BaseTemplateSpec) &&
6451       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6452        TSK == TSK_ImplicitInstantiation)) {
6453     // The template hasn't been instantiated yet (or it has, but only as an
6454     // explicit instantiation declaration or implicit instantiation, which means
6455     // we haven't codegenned any members yet), so propagate the attribute.
6456     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6457     NewAttr->setInherited(true);
6458     BaseTemplateSpec->addAttr(NewAttr);
6459 
6460     // If this was an import, mark that we propagated it from a derived class to
6461     // a base class template specialization.
6462     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6463       ImportAttr->setPropagatedToBaseTemplate();
6464 
6465     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6466     // needs to be run again to work see the new attribute. Otherwise this will
6467     // get run whenever the template is instantiated.
6468     if (TSK != TSK_Undeclared)
6469       checkClassLevelDLLAttribute(BaseTemplateSpec);
6470 
6471     return;
6472   }
6473 
6474   if (getDLLAttr(BaseTemplateSpec)) {
6475     // The template has already been specialized or instantiated with an
6476     // attribute, explicitly or through propagation. We should not try to change
6477     // it.
6478     return;
6479   }
6480 
6481   // The template was previously instantiated or explicitly specialized without
6482   // a dll attribute, It's too late for us to add an attribute, so warn that
6483   // this is unsupported.
6484   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6485       << BaseTemplateSpec->isExplicitSpecialization();
6486   Diag(ClassAttr->getLocation(), diag::note_attribute);
6487   if (BaseTemplateSpec->isExplicitSpecialization()) {
6488     Diag(BaseTemplateSpec->getLocation(),
6489            diag::note_template_class_explicit_specialization_was_here)
6490         << BaseTemplateSpec;
6491   } else {
6492     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6493            diag::note_template_class_instantiation_was_here)
6494         << BaseTemplateSpec;
6495   }
6496 }
6497 
6498 /// Determine the kind of defaulting that would be done for a given function.
6499 ///
6500 /// If the function is both a default constructor and a copy / move constructor
6501 /// (due to having a default argument for the first parameter), this picks
6502 /// CXXDefaultConstructor.
6503 ///
6504 /// FIXME: Check that case is properly handled by all callers.
6505 Sema::DefaultedFunctionKind
6506 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6507   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6508     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6509       if (Ctor->isDefaultConstructor())
6510         return Sema::CXXDefaultConstructor;
6511 
6512       if (Ctor->isCopyConstructor())
6513         return Sema::CXXCopyConstructor;
6514 
6515       if (Ctor->isMoveConstructor())
6516         return Sema::CXXMoveConstructor;
6517     }
6518 
6519     if (MD->isCopyAssignmentOperator())
6520       return Sema::CXXCopyAssignment;
6521 
6522     if (MD->isMoveAssignmentOperator())
6523       return Sema::CXXMoveAssignment;
6524 
6525     if (isa<CXXDestructorDecl>(FD))
6526       return Sema::CXXDestructor;
6527   }
6528 
6529   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6530   case OO_EqualEqual:
6531     return DefaultedComparisonKind::Equal;
6532 
6533   case OO_ExclaimEqual:
6534     return DefaultedComparisonKind::NotEqual;
6535 
6536   case OO_Spaceship:
6537     // No point allowing this if <=> doesn't exist in the current language mode.
6538     if (!getLangOpts().CPlusPlus20)
6539       break;
6540     return DefaultedComparisonKind::ThreeWay;
6541 
6542   case OO_Less:
6543   case OO_LessEqual:
6544   case OO_Greater:
6545   case OO_GreaterEqual:
6546     // No point allowing this if <=> doesn't exist in the current language mode.
6547     if (!getLangOpts().CPlusPlus20)
6548       break;
6549     return DefaultedComparisonKind::Relational;
6550 
6551   default:
6552     break;
6553   }
6554 
6555   // Not defaultable.
6556   return DefaultedFunctionKind();
6557 }
6558 
6559 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6560                                     SourceLocation DefaultLoc) {
6561   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6562   if (DFK.isComparison())
6563     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6564 
6565   switch (DFK.asSpecialMember()) {
6566   case Sema::CXXDefaultConstructor:
6567     S.DefineImplicitDefaultConstructor(DefaultLoc,
6568                                        cast<CXXConstructorDecl>(FD));
6569     break;
6570   case Sema::CXXCopyConstructor:
6571     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6572     break;
6573   case Sema::CXXCopyAssignment:
6574     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6575     break;
6576   case Sema::CXXDestructor:
6577     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6578     break;
6579   case Sema::CXXMoveConstructor:
6580     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6581     break;
6582   case Sema::CXXMoveAssignment:
6583     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6584     break;
6585   case Sema::CXXInvalid:
6586     llvm_unreachable("Invalid special member.");
6587   }
6588 }
6589 
6590 /// Determine whether a type is permitted to be passed or returned in
6591 /// registers, per C++ [class.temporary]p3.
6592 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6593                                TargetInfo::CallingConvKind CCK) {
6594   if (D->isDependentType() || D->isInvalidDecl())
6595     return false;
6596 
6597   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6598   // The PS4 platform ABI follows the behavior of Clang 3.2.
6599   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6600     return !D->hasNonTrivialDestructorForCall() &&
6601            !D->hasNonTrivialCopyConstructorForCall();
6602 
6603   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6604     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6605     bool DtorIsTrivialForCall = false;
6606 
6607     // If a class has at least one non-deleted, trivial copy constructor, it
6608     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6609     //
6610     // Note: This permits classes with non-trivial copy or move ctors to be
6611     // passed in registers, so long as they *also* have a trivial copy ctor,
6612     // which is non-conforming.
6613     if (D->needsImplicitCopyConstructor()) {
6614       if (!D->defaultedCopyConstructorIsDeleted()) {
6615         if (D->hasTrivialCopyConstructor())
6616           CopyCtorIsTrivial = true;
6617         if (D->hasTrivialCopyConstructorForCall())
6618           CopyCtorIsTrivialForCall = true;
6619       }
6620     } else {
6621       for (const CXXConstructorDecl *CD : D->ctors()) {
6622         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6623           if (CD->isTrivial())
6624             CopyCtorIsTrivial = true;
6625           if (CD->isTrivialForCall())
6626             CopyCtorIsTrivialForCall = true;
6627         }
6628       }
6629     }
6630 
6631     if (D->needsImplicitDestructor()) {
6632       if (!D->defaultedDestructorIsDeleted() &&
6633           D->hasTrivialDestructorForCall())
6634         DtorIsTrivialForCall = true;
6635     } else if (const auto *DD = D->getDestructor()) {
6636       if (!DD->isDeleted() && DD->isTrivialForCall())
6637         DtorIsTrivialForCall = true;
6638     }
6639 
6640     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6641     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6642       return true;
6643 
6644     // If a class has a destructor, we'd really like to pass it indirectly
6645     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6646     // impossible for small types, which it will pass in a single register or
6647     // stack slot. Most objects with dtors are large-ish, so handle that early.
6648     // We can't call out all large objects as being indirect because there are
6649     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6650     // how we pass large POD types.
6651 
6652     // Note: This permits small classes with nontrivial destructors to be
6653     // passed in registers, which is non-conforming.
6654     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6655     uint64_t TypeSize = isAArch64 ? 128 : 64;
6656 
6657     if (CopyCtorIsTrivial &&
6658         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6659       return true;
6660     return false;
6661   }
6662 
6663   // Per C++ [class.temporary]p3, the relevant condition is:
6664   //   each copy constructor, move constructor, and destructor of X is
6665   //   either trivial or deleted, and X has at least one non-deleted copy
6666   //   or move constructor
6667   bool HasNonDeletedCopyOrMove = false;
6668 
6669   if (D->needsImplicitCopyConstructor() &&
6670       !D->defaultedCopyConstructorIsDeleted()) {
6671     if (!D->hasTrivialCopyConstructorForCall())
6672       return false;
6673     HasNonDeletedCopyOrMove = true;
6674   }
6675 
6676   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6677       !D->defaultedMoveConstructorIsDeleted()) {
6678     if (!D->hasTrivialMoveConstructorForCall())
6679       return false;
6680     HasNonDeletedCopyOrMove = true;
6681   }
6682 
6683   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6684       !D->hasTrivialDestructorForCall())
6685     return false;
6686 
6687   for (const CXXMethodDecl *MD : D->methods()) {
6688     if (MD->isDeleted())
6689       continue;
6690 
6691     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6692     if (CD && CD->isCopyOrMoveConstructor())
6693       HasNonDeletedCopyOrMove = true;
6694     else if (!isa<CXXDestructorDecl>(MD))
6695       continue;
6696 
6697     if (!MD->isTrivialForCall())
6698       return false;
6699   }
6700 
6701   return HasNonDeletedCopyOrMove;
6702 }
6703 
6704 /// Report an error regarding overriding, along with any relevant
6705 /// overridden methods.
6706 ///
6707 /// \param DiagID the primary error to report.
6708 /// \param MD the overriding method.
6709 static bool
6710 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6711                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6712   bool IssuedDiagnostic = false;
6713   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6714     if (Report(O)) {
6715       if (!IssuedDiagnostic) {
6716         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6717         IssuedDiagnostic = true;
6718       }
6719       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6720     }
6721   }
6722   return IssuedDiagnostic;
6723 }
6724 
6725 /// Perform semantic checks on a class definition that has been
6726 /// completing, introducing implicitly-declared members, checking for
6727 /// abstract types, etc.
6728 ///
6729 /// \param S The scope in which the class was parsed. Null if we didn't just
6730 ///        parse a class definition.
6731 /// \param Record The completed class.
6732 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6733   if (!Record)
6734     return;
6735 
6736   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6737     AbstractUsageInfo Info(*this, Record);
6738     CheckAbstractClassUsage(Info, Record);
6739   }
6740 
6741   // If this is not an aggregate type and has no user-declared constructor,
6742   // complain about any non-static data members of reference or const scalar
6743   // type, since they will never get initializers.
6744   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6745       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6746       !Record->isLambda()) {
6747     bool Complained = false;
6748     for (const auto *F : Record->fields()) {
6749       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6750         continue;
6751 
6752       if (F->getType()->isReferenceType() ||
6753           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6754         if (!Complained) {
6755           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6756             << Record->getTagKind() << Record;
6757           Complained = true;
6758         }
6759 
6760         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6761           << F->getType()->isReferenceType()
6762           << F->getDeclName();
6763       }
6764     }
6765   }
6766 
6767   if (Record->getIdentifier()) {
6768     // C++ [class.mem]p13:
6769     //   If T is the name of a class, then each of the following shall have a
6770     //   name different from T:
6771     //     - every member of every anonymous union that is a member of class T.
6772     //
6773     // C++ [class.mem]p14:
6774     //   In addition, if class T has a user-declared constructor (12.1), every
6775     //   non-static data member of class T shall have a name different from T.
6776     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6777     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6778          ++I) {
6779       NamedDecl *D = (*I)->getUnderlyingDecl();
6780       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6781            Record->hasUserDeclaredConstructor()) ||
6782           isa<IndirectFieldDecl>(D)) {
6783         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6784           << D->getDeclName();
6785         break;
6786       }
6787     }
6788   }
6789 
6790   // Warn if the class has virtual methods but non-virtual public destructor.
6791   if (Record->isPolymorphic() && !Record->isDependentType()) {
6792     CXXDestructorDecl *dtor = Record->getDestructor();
6793     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6794         !Record->hasAttr<FinalAttr>())
6795       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6796            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6797   }
6798 
6799   if (Record->isAbstract()) {
6800     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6801       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6802         << FA->isSpelledAsSealed();
6803       DiagnoseAbstractType(Record);
6804     }
6805   }
6806 
6807   // Warn if the class has a final destructor but is not itself marked final.
6808   if (!Record->hasAttr<FinalAttr>()) {
6809     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6810       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6811         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6812             << FA->isSpelledAsSealed()
6813             << FixItHint::CreateInsertion(
6814                    getLocForEndOfToken(Record->getLocation()),
6815                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6816         Diag(Record->getLocation(),
6817              diag::note_final_dtor_non_final_class_silence)
6818             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6819       }
6820     }
6821   }
6822 
6823   // See if trivial_abi has to be dropped.
6824   if (Record->hasAttr<TrivialABIAttr>())
6825     checkIllFormedTrivialABIStruct(*Record);
6826 
6827   // Set HasTrivialSpecialMemberForCall if the record has attribute
6828   // "trivial_abi".
6829   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6830 
6831   if (HasTrivialABI)
6832     Record->setHasTrivialSpecialMemberForCall();
6833 
6834   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6835   // We check these last because they can depend on the properties of the
6836   // primary comparison functions (==, <=>).
6837   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6838 
6839   // Perform checks that can't be done until we know all the properties of a
6840   // member function (whether it's defaulted, deleted, virtual, overriding,
6841   // ...).
6842   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6843     // A static function cannot override anything.
6844     if (MD->getStorageClass() == SC_Static) {
6845       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6846                           [](const CXXMethodDecl *) { return true; }))
6847         return;
6848     }
6849 
6850     // A deleted function cannot override a non-deleted function and vice
6851     // versa.
6852     if (ReportOverrides(*this,
6853                         MD->isDeleted() ? diag::err_deleted_override
6854                                         : diag::err_non_deleted_override,
6855                         MD, [&](const CXXMethodDecl *V) {
6856                           return MD->isDeleted() != V->isDeleted();
6857                         })) {
6858       if (MD->isDefaulted() && MD->isDeleted())
6859         // Explain why this defaulted function was deleted.
6860         DiagnoseDeletedDefaultedFunction(MD);
6861       return;
6862     }
6863 
6864     // A consteval function cannot override a non-consteval function and vice
6865     // versa.
6866     if (ReportOverrides(*this,
6867                         MD->isConsteval() ? diag::err_consteval_override
6868                                           : diag::err_non_consteval_override,
6869                         MD, [&](const CXXMethodDecl *V) {
6870                           return MD->isConsteval() != V->isConsteval();
6871                         })) {
6872       if (MD->isDefaulted() && MD->isDeleted())
6873         // Explain why this defaulted function was deleted.
6874         DiagnoseDeletedDefaultedFunction(MD);
6875       return;
6876     }
6877   };
6878 
6879   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6880     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6881       return false;
6882 
6883     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6884     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6885         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6886       DefaultedSecondaryComparisons.push_back(FD);
6887       return true;
6888     }
6889 
6890     CheckExplicitlyDefaultedFunction(S, FD);
6891     return false;
6892   };
6893 
6894   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6895     // Check whether the explicitly-defaulted members are valid.
6896     bool Incomplete = CheckForDefaultedFunction(M);
6897 
6898     // Skip the rest of the checks for a member of a dependent class.
6899     if (Record->isDependentType())
6900       return;
6901 
6902     // For an explicitly defaulted or deleted special member, we defer
6903     // determining triviality until the class is complete. That time is now!
6904     CXXSpecialMember CSM = getSpecialMember(M);
6905     if (!M->isImplicit() && !M->isUserProvided()) {
6906       if (CSM != CXXInvalid) {
6907         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6908         // Inform the class that we've finished declaring this member.
6909         Record->finishedDefaultedOrDeletedMember(M);
6910         M->setTrivialForCall(
6911             HasTrivialABI ||
6912             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6913         Record->setTrivialForCallFlags(M);
6914       }
6915     }
6916 
6917     // Set triviality for the purpose of calls if this is a user-provided
6918     // copy/move constructor or destructor.
6919     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6920          CSM == CXXDestructor) && M->isUserProvided()) {
6921       M->setTrivialForCall(HasTrivialABI);
6922       Record->setTrivialForCallFlags(M);
6923     }
6924 
6925     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6926         M->hasAttr<DLLExportAttr>()) {
6927       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6928           M->isTrivial() &&
6929           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6930            CSM == CXXDestructor))
6931         M->dropAttr<DLLExportAttr>();
6932 
6933       if (M->hasAttr<DLLExportAttr>()) {
6934         // Define after any fields with in-class initializers have been parsed.
6935         DelayedDllExportMemberFunctions.push_back(M);
6936       }
6937     }
6938 
6939     // Define defaulted constexpr virtual functions that override a base class
6940     // function right away.
6941     // FIXME: We can defer doing this until the vtable is marked as used.
6942     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6943       DefineDefaultedFunction(*this, M, M->getLocation());
6944 
6945     if (!Incomplete)
6946       CheckCompletedMemberFunction(M);
6947   };
6948 
6949   // Check the destructor before any other member function. We need to
6950   // determine whether it's trivial in order to determine whether the claas
6951   // type is a literal type, which is a prerequisite for determining whether
6952   // other special member functions are valid and whether they're implicitly
6953   // 'constexpr'.
6954   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6955     CompleteMemberFunction(Dtor);
6956 
6957   bool HasMethodWithOverrideControl = false,
6958        HasOverridingMethodWithoutOverrideControl = false;
6959   for (auto *D : Record->decls()) {
6960     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6961       // FIXME: We could do this check for dependent types with non-dependent
6962       // bases.
6963       if (!Record->isDependentType()) {
6964         // See if a method overloads virtual methods in a base
6965         // class without overriding any.
6966         if (!M->isStatic())
6967           DiagnoseHiddenVirtualMethods(M);
6968         if (M->hasAttr<OverrideAttr>())
6969           HasMethodWithOverrideControl = true;
6970         else if (M->size_overridden_methods() > 0)
6971           HasOverridingMethodWithoutOverrideControl = true;
6972       }
6973 
6974       if (!isa<CXXDestructorDecl>(M))
6975         CompleteMemberFunction(M);
6976     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6977       CheckForDefaultedFunction(
6978           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6979     }
6980   }
6981 
6982   if (HasOverridingMethodWithoutOverrideControl) {
6983     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6984     for (auto *M : Record->methods())
6985       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6986   }
6987 
6988   // Check the defaulted secondary comparisons after any other member functions.
6989   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6990     CheckExplicitlyDefaultedFunction(S, FD);
6991 
6992     // If this is a member function, we deferred checking it until now.
6993     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6994       CheckCompletedMemberFunction(MD);
6995   }
6996 
6997   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6998   // whether this class uses any C++ features that are implemented
6999   // completely differently in MSVC, and if so, emit a diagnostic.
7000   // That diagnostic defaults to an error, but we allow projects to
7001   // map it down to a warning (or ignore it).  It's a fairly common
7002   // practice among users of the ms_struct pragma to mass-annotate
7003   // headers, sweeping up a bunch of types that the project doesn't
7004   // really rely on MSVC-compatible layout for.  We must therefore
7005   // support "ms_struct except for C++ stuff" as a secondary ABI.
7006   // Don't emit this diagnostic if the feature was enabled as a
7007   // language option (as opposed to via a pragma or attribute), as
7008   // the option -mms-bitfields otherwise essentially makes it impossible
7009   // to build C++ code, unless this diagnostic is turned off.
7010   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7011       (Record->isPolymorphic() || Record->getNumBases())) {
7012     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7013   }
7014 
7015   checkClassLevelDLLAttribute(Record);
7016   checkClassLevelCodeSegAttribute(Record);
7017 
7018   bool ClangABICompat4 =
7019       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7020   TargetInfo::CallingConvKind CCK =
7021       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7022   bool CanPass = canPassInRegisters(*this, Record, CCK);
7023 
7024   // Do not change ArgPassingRestrictions if it has already been set to
7025   // APK_CanNeverPassInRegs.
7026   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7027     Record->setArgPassingRestrictions(CanPass
7028                                           ? RecordDecl::APK_CanPassInRegs
7029                                           : RecordDecl::APK_CannotPassInRegs);
7030 
7031   // If canPassInRegisters returns true despite the record having a non-trivial
7032   // destructor, the record is destructed in the callee. This happens only when
7033   // the record or one of its subobjects has a field annotated with trivial_abi
7034   // or a field qualified with ObjC __strong/__weak.
7035   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7036     Record->setParamDestroyedInCallee(true);
7037   else if (Record->hasNonTrivialDestructor())
7038     Record->setParamDestroyedInCallee(CanPass);
7039 
7040   if (getLangOpts().ForceEmitVTables) {
7041     // If we want to emit all the vtables, we need to mark it as used.  This
7042     // is especially required for cases like vtable assumption loads.
7043     MarkVTableUsed(Record->getInnerLocStart(), Record);
7044   }
7045 
7046   if (getLangOpts().CUDA) {
7047     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7048       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7049     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7050       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7051   }
7052 }
7053 
7054 /// Look up the special member function that would be called by a special
7055 /// member function for a subobject of class type.
7056 ///
7057 /// \param Class The class type of the subobject.
7058 /// \param CSM The kind of special member function.
7059 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7060 /// \param ConstRHS True if this is a copy operation with a const object
7061 ///        on its RHS, that is, if the argument to the outer special member
7062 ///        function is 'const' and this is not a field marked 'mutable'.
7063 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7064     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7065     unsigned FieldQuals, bool ConstRHS) {
7066   unsigned LHSQuals = 0;
7067   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7068     LHSQuals = FieldQuals;
7069 
7070   unsigned RHSQuals = FieldQuals;
7071   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7072     RHSQuals = 0;
7073   else if (ConstRHS)
7074     RHSQuals |= Qualifiers::Const;
7075 
7076   return S.LookupSpecialMember(Class, CSM,
7077                                RHSQuals & Qualifiers::Const,
7078                                RHSQuals & Qualifiers::Volatile,
7079                                false,
7080                                LHSQuals & Qualifiers::Const,
7081                                LHSQuals & Qualifiers::Volatile);
7082 }
7083 
7084 class Sema::InheritedConstructorInfo {
7085   Sema &S;
7086   SourceLocation UseLoc;
7087 
7088   /// A mapping from the base classes through which the constructor was
7089   /// inherited to the using shadow declaration in that base class (or a null
7090   /// pointer if the constructor was declared in that base class).
7091   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7092       InheritedFromBases;
7093 
7094 public:
7095   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7096                            ConstructorUsingShadowDecl *Shadow)
7097       : S(S), UseLoc(UseLoc) {
7098     bool DiagnosedMultipleConstructedBases = false;
7099     CXXRecordDecl *ConstructedBase = nullptr;
7100     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7101 
7102     // Find the set of such base class subobjects and check that there's a
7103     // unique constructed subobject.
7104     for (auto *D : Shadow->redecls()) {
7105       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7106       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7107       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7108 
7109       InheritedFromBases.insert(
7110           std::make_pair(DNominatedBase->getCanonicalDecl(),
7111                          DShadow->getNominatedBaseClassShadowDecl()));
7112       if (DShadow->constructsVirtualBase())
7113         InheritedFromBases.insert(
7114             std::make_pair(DConstructedBase->getCanonicalDecl(),
7115                            DShadow->getConstructedBaseClassShadowDecl()));
7116       else
7117         assert(DNominatedBase == DConstructedBase);
7118 
7119       // [class.inhctor.init]p2:
7120       //   If the constructor was inherited from multiple base class subobjects
7121       //   of type B, the program is ill-formed.
7122       if (!ConstructedBase) {
7123         ConstructedBase = DConstructedBase;
7124         ConstructedBaseIntroducer = D->getIntroducer();
7125       } else if (ConstructedBase != DConstructedBase &&
7126                  !Shadow->isInvalidDecl()) {
7127         if (!DiagnosedMultipleConstructedBases) {
7128           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7129               << Shadow->getTargetDecl();
7130           S.Diag(ConstructedBaseIntroducer->getLocation(),
7131                  diag::note_ambiguous_inherited_constructor_using)
7132               << ConstructedBase;
7133           DiagnosedMultipleConstructedBases = true;
7134         }
7135         S.Diag(D->getIntroducer()->getLocation(),
7136                diag::note_ambiguous_inherited_constructor_using)
7137             << DConstructedBase;
7138       }
7139     }
7140 
7141     if (DiagnosedMultipleConstructedBases)
7142       Shadow->setInvalidDecl();
7143   }
7144 
7145   /// Find the constructor to use for inherited construction of a base class,
7146   /// and whether that base class constructor inherits the constructor from a
7147   /// virtual base class (in which case it won't actually invoke it).
7148   std::pair<CXXConstructorDecl *, bool>
7149   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7150     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7151     if (It == InheritedFromBases.end())
7152       return std::make_pair(nullptr, false);
7153 
7154     // This is an intermediary class.
7155     if (It->second)
7156       return std::make_pair(
7157           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7158           It->second->constructsVirtualBase());
7159 
7160     // This is the base class from which the constructor was inherited.
7161     return std::make_pair(Ctor, false);
7162   }
7163 };
7164 
7165 /// Is the special member function which would be selected to perform the
7166 /// specified operation on the specified class type a constexpr constructor?
7167 static bool
7168 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7169                          Sema::CXXSpecialMember CSM, unsigned Quals,
7170                          bool ConstRHS,
7171                          CXXConstructorDecl *InheritedCtor = nullptr,
7172                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7173   // If we're inheriting a constructor, see if we need to call it for this base
7174   // class.
7175   if (InheritedCtor) {
7176     assert(CSM == Sema::CXXDefaultConstructor);
7177     auto BaseCtor =
7178         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7179     if (BaseCtor)
7180       return BaseCtor->isConstexpr();
7181   }
7182 
7183   if (CSM == Sema::CXXDefaultConstructor)
7184     return ClassDecl->hasConstexprDefaultConstructor();
7185   if (CSM == Sema::CXXDestructor)
7186     return ClassDecl->hasConstexprDestructor();
7187 
7188   Sema::SpecialMemberOverloadResult SMOR =
7189       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7190   if (!SMOR.getMethod())
7191     // A constructor we wouldn't select can't be "involved in initializing"
7192     // anything.
7193     return true;
7194   return SMOR.getMethod()->isConstexpr();
7195 }
7196 
7197 /// Determine whether the specified special member function would be constexpr
7198 /// if it were implicitly defined.
7199 static bool defaultedSpecialMemberIsConstexpr(
7200     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7201     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7202     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7203   if (!S.getLangOpts().CPlusPlus11)
7204     return false;
7205 
7206   // C++11 [dcl.constexpr]p4:
7207   // In the definition of a constexpr constructor [...]
7208   bool Ctor = true;
7209   switch (CSM) {
7210   case Sema::CXXDefaultConstructor:
7211     if (Inherited)
7212       break;
7213     // Since default constructor lookup is essentially trivial (and cannot
7214     // involve, for instance, template instantiation), we compute whether a
7215     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7216     //
7217     // This is important for performance; we need to know whether the default
7218     // constructor is constexpr to determine whether the type is a literal type.
7219     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7220 
7221   case Sema::CXXCopyConstructor:
7222   case Sema::CXXMoveConstructor:
7223     // For copy or move constructors, we need to perform overload resolution.
7224     break;
7225 
7226   case Sema::CXXCopyAssignment:
7227   case Sema::CXXMoveAssignment:
7228     if (!S.getLangOpts().CPlusPlus14)
7229       return false;
7230     // In C++1y, we need to perform overload resolution.
7231     Ctor = false;
7232     break;
7233 
7234   case Sema::CXXDestructor:
7235     return ClassDecl->defaultedDestructorIsConstexpr();
7236 
7237   case Sema::CXXInvalid:
7238     return false;
7239   }
7240 
7241   //   -- if the class is a non-empty union, or for each non-empty anonymous
7242   //      union member of a non-union class, exactly one non-static data member
7243   //      shall be initialized; [DR1359]
7244   //
7245   // If we squint, this is guaranteed, since exactly one non-static data member
7246   // will be initialized (if the constructor isn't deleted), we just don't know
7247   // which one.
7248   if (Ctor && ClassDecl->isUnion())
7249     return CSM == Sema::CXXDefaultConstructor
7250                ? ClassDecl->hasInClassInitializer() ||
7251                      !ClassDecl->hasVariantMembers()
7252                : true;
7253 
7254   //   -- the class shall not have any virtual base classes;
7255   if (Ctor && ClassDecl->getNumVBases())
7256     return false;
7257 
7258   // C++1y [class.copy]p26:
7259   //   -- [the class] is a literal type, and
7260   if (!Ctor && !ClassDecl->isLiteral())
7261     return false;
7262 
7263   //   -- every constructor involved in initializing [...] base class
7264   //      sub-objects shall be a constexpr constructor;
7265   //   -- the assignment operator selected to copy/move each direct base
7266   //      class is a constexpr function, and
7267   for (const auto &B : ClassDecl->bases()) {
7268     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7269     if (!BaseType) continue;
7270 
7271     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7272     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7273                                   InheritedCtor, Inherited))
7274       return false;
7275   }
7276 
7277   //   -- every constructor involved in initializing non-static data members
7278   //      [...] shall be a constexpr constructor;
7279   //   -- every non-static data member and base class sub-object shall be
7280   //      initialized
7281   //   -- for each non-static data member of X that is of class type (or array
7282   //      thereof), the assignment operator selected to copy/move that member is
7283   //      a constexpr function
7284   for (const auto *F : ClassDecl->fields()) {
7285     if (F->isInvalidDecl())
7286       continue;
7287     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7288       continue;
7289     QualType BaseType = S.Context.getBaseElementType(F->getType());
7290     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7291       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7292       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7293                                     BaseType.getCVRQualifiers(),
7294                                     ConstArg && !F->isMutable()))
7295         return false;
7296     } else if (CSM == Sema::CXXDefaultConstructor) {
7297       return false;
7298     }
7299   }
7300 
7301   // All OK, it's constexpr!
7302   return true;
7303 }
7304 
7305 namespace {
7306 /// RAII object to register a defaulted function as having its exception
7307 /// specification computed.
7308 struct ComputingExceptionSpec {
7309   Sema &S;
7310 
7311   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7312       : S(S) {
7313     Sema::CodeSynthesisContext Ctx;
7314     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7315     Ctx.PointOfInstantiation = Loc;
7316     Ctx.Entity = FD;
7317     S.pushCodeSynthesisContext(Ctx);
7318   }
7319   ~ComputingExceptionSpec() {
7320     S.popCodeSynthesisContext();
7321   }
7322 };
7323 }
7324 
7325 static Sema::ImplicitExceptionSpecification
7326 ComputeDefaultedSpecialMemberExceptionSpec(
7327     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7328     Sema::InheritedConstructorInfo *ICI);
7329 
7330 static Sema::ImplicitExceptionSpecification
7331 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7332                                         FunctionDecl *FD,
7333                                         Sema::DefaultedComparisonKind DCK);
7334 
7335 static Sema::ImplicitExceptionSpecification
7336 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7337   auto DFK = S.getDefaultedFunctionKind(FD);
7338   if (DFK.isSpecialMember())
7339     return ComputeDefaultedSpecialMemberExceptionSpec(
7340         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7341   if (DFK.isComparison())
7342     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7343                                                    DFK.asComparison());
7344 
7345   auto *CD = cast<CXXConstructorDecl>(FD);
7346   assert(CD->getInheritedConstructor() &&
7347          "only defaulted functions and inherited constructors have implicit "
7348          "exception specs");
7349   Sema::InheritedConstructorInfo ICI(
7350       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7351   return ComputeDefaultedSpecialMemberExceptionSpec(
7352       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7353 }
7354 
7355 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7356                                                             CXXMethodDecl *MD) {
7357   FunctionProtoType::ExtProtoInfo EPI;
7358 
7359   // Build an exception specification pointing back at this member.
7360   EPI.ExceptionSpec.Type = EST_Unevaluated;
7361   EPI.ExceptionSpec.SourceDecl = MD;
7362 
7363   // Set the calling convention to the default for C++ instance methods.
7364   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7365       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7366                                             /*IsCXXMethod=*/true));
7367   return EPI;
7368 }
7369 
7370 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7371   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7372   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7373     return;
7374 
7375   // Evaluate the exception specification.
7376   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7377   auto ESI = IES.getExceptionSpec();
7378 
7379   // Update the type of the special member to use it.
7380   UpdateExceptionSpec(FD, ESI);
7381 }
7382 
7383 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7384   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7385 
7386   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7387   if (!DefKind) {
7388     assert(FD->getDeclContext()->isDependentContext());
7389     return;
7390   }
7391 
7392   if (DefKind.isComparison())
7393     UnusedPrivateFields.clear();
7394 
7395   if (DefKind.isSpecialMember()
7396           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7397                                                   DefKind.asSpecialMember())
7398           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7399     FD->setInvalidDecl();
7400 }
7401 
7402 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7403                                                  CXXSpecialMember CSM) {
7404   CXXRecordDecl *RD = MD->getParent();
7405 
7406   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7407          "not an explicitly-defaulted special member");
7408 
7409   // Defer all checking for special members of a dependent type.
7410   if (RD->isDependentType())
7411     return false;
7412 
7413   // Whether this was the first-declared instance of the constructor.
7414   // This affects whether we implicitly add an exception spec and constexpr.
7415   bool First = MD == MD->getCanonicalDecl();
7416 
7417   bool HadError = false;
7418 
7419   // C++11 [dcl.fct.def.default]p1:
7420   //   A function that is explicitly defaulted shall
7421   //     -- be a special member function [...] (checked elsewhere),
7422   //     -- have the same type (except for ref-qualifiers, and except that a
7423   //        copy operation can take a non-const reference) as an implicit
7424   //        declaration, and
7425   //     -- not have default arguments.
7426   // C++2a changes the second bullet to instead delete the function if it's
7427   // defaulted on its first declaration, unless it's "an assignment operator,
7428   // and its return type differs or its parameter type is not a reference".
7429   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7430   bool ShouldDeleteForTypeMismatch = false;
7431   unsigned ExpectedParams = 1;
7432   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7433     ExpectedParams = 0;
7434   if (MD->getNumParams() != ExpectedParams) {
7435     // This checks for default arguments: a copy or move constructor with a
7436     // default argument is classified as a default constructor, and assignment
7437     // operations and destructors can't have default arguments.
7438     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7439       << CSM << MD->getSourceRange();
7440     HadError = true;
7441   } else if (MD->isVariadic()) {
7442     if (DeleteOnTypeMismatch)
7443       ShouldDeleteForTypeMismatch = true;
7444     else {
7445       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7446         << CSM << MD->getSourceRange();
7447       HadError = true;
7448     }
7449   }
7450 
7451   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7452 
7453   bool CanHaveConstParam = false;
7454   if (CSM == CXXCopyConstructor)
7455     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7456   else if (CSM == CXXCopyAssignment)
7457     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7458 
7459   QualType ReturnType = Context.VoidTy;
7460   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7461     // Check for return type matching.
7462     ReturnType = Type->getReturnType();
7463 
7464     QualType DeclType = Context.getTypeDeclType(RD);
7465     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7466     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7467 
7468     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7469       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7470         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7471       HadError = true;
7472     }
7473 
7474     // A defaulted special member cannot have cv-qualifiers.
7475     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7476       if (DeleteOnTypeMismatch)
7477         ShouldDeleteForTypeMismatch = true;
7478       else {
7479         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7480           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7481         HadError = true;
7482       }
7483     }
7484   }
7485 
7486   // Check for parameter type matching.
7487   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7488   bool HasConstParam = false;
7489   if (ExpectedParams && ArgType->isReferenceType()) {
7490     // Argument must be reference to possibly-const T.
7491     QualType ReferentType = ArgType->getPointeeType();
7492     HasConstParam = ReferentType.isConstQualified();
7493 
7494     if (ReferentType.isVolatileQualified()) {
7495       if (DeleteOnTypeMismatch)
7496         ShouldDeleteForTypeMismatch = true;
7497       else {
7498         Diag(MD->getLocation(),
7499              diag::err_defaulted_special_member_volatile_param) << CSM;
7500         HadError = true;
7501       }
7502     }
7503 
7504     if (HasConstParam && !CanHaveConstParam) {
7505       if (DeleteOnTypeMismatch)
7506         ShouldDeleteForTypeMismatch = true;
7507       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7508         Diag(MD->getLocation(),
7509              diag::err_defaulted_special_member_copy_const_param)
7510           << (CSM == CXXCopyAssignment);
7511         // FIXME: Explain why this special member can't be const.
7512         HadError = true;
7513       } else {
7514         Diag(MD->getLocation(),
7515              diag::err_defaulted_special_member_move_const_param)
7516           << (CSM == CXXMoveAssignment);
7517         HadError = true;
7518       }
7519     }
7520   } else if (ExpectedParams) {
7521     // A copy assignment operator can take its argument by value, but a
7522     // defaulted one cannot.
7523     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7524     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7525     HadError = true;
7526   }
7527 
7528   // C++11 [dcl.fct.def.default]p2:
7529   //   An explicitly-defaulted function may be declared constexpr only if it
7530   //   would have been implicitly declared as constexpr,
7531   // Do not apply this rule to members of class templates, since core issue 1358
7532   // makes such functions always instantiate to constexpr functions. For
7533   // functions which cannot be constexpr (for non-constructors in C++11 and for
7534   // destructors in C++14 and C++17), this is checked elsewhere.
7535   //
7536   // FIXME: This should not apply if the member is deleted.
7537   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7538                                                      HasConstParam);
7539   if ((getLangOpts().CPlusPlus20 ||
7540        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7541                                   : isa<CXXConstructorDecl>(MD))) &&
7542       MD->isConstexpr() && !Constexpr &&
7543       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7544     Diag(MD->getBeginLoc(), MD->isConsteval()
7545                                 ? diag::err_incorrect_defaulted_consteval
7546                                 : diag::err_incorrect_defaulted_constexpr)
7547         << CSM;
7548     // FIXME: Explain why the special member can't be constexpr.
7549     HadError = true;
7550   }
7551 
7552   if (First) {
7553     // C++2a [dcl.fct.def.default]p3:
7554     //   If a function is explicitly defaulted on its first declaration, it is
7555     //   implicitly considered to be constexpr if the implicit declaration
7556     //   would be.
7557     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7558                                           ? ConstexprSpecKind::Consteval
7559                                           : ConstexprSpecKind::Constexpr)
7560                                    : ConstexprSpecKind::Unspecified);
7561 
7562     if (!Type->hasExceptionSpec()) {
7563       // C++2a [except.spec]p3:
7564       //   If a declaration of a function does not have a noexcept-specifier
7565       //   [and] is defaulted on its first declaration, [...] the exception
7566       //   specification is as specified below
7567       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7568       EPI.ExceptionSpec.Type = EST_Unevaluated;
7569       EPI.ExceptionSpec.SourceDecl = MD;
7570       MD->setType(Context.getFunctionType(ReturnType,
7571                                           llvm::makeArrayRef(&ArgType,
7572                                                              ExpectedParams),
7573                                           EPI));
7574     }
7575   }
7576 
7577   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7578     if (First) {
7579       SetDeclDeleted(MD, MD->getLocation());
7580       if (!inTemplateInstantiation() && !HadError) {
7581         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7582         if (ShouldDeleteForTypeMismatch) {
7583           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7584         } else {
7585           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7586         }
7587       }
7588       if (ShouldDeleteForTypeMismatch && !HadError) {
7589         Diag(MD->getLocation(),
7590              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7591       }
7592     } else {
7593       // C++11 [dcl.fct.def.default]p4:
7594       //   [For a] user-provided explicitly-defaulted function [...] if such a
7595       //   function is implicitly defined as deleted, the program is ill-formed.
7596       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7597       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7598       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7599       HadError = true;
7600     }
7601   }
7602 
7603   return HadError;
7604 }
7605 
7606 namespace {
7607 /// Helper class for building and checking a defaulted comparison.
7608 ///
7609 /// Defaulted functions are built in two phases:
7610 ///
7611 ///  * First, the set of operations that the function will perform are
7612 ///    identified, and some of them are checked. If any of the checked
7613 ///    operations is invalid in certain ways, the comparison function is
7614 ///    defined as deleted and no body is built.
7615 ///  * Then, if the function is not defined as deleted, the body is built.
7616 ///
7617 /// This is accomplished by performing two visitation steps over the eventual
7618 /// body of the function.
7619 template<typename Derived, typename ResultList, typename Result,
7620          typename Subobject>
7621 class DefaultedComparisonVisitor {
7622 public:
7623   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7624 
7625   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7626                              DefaultedComparisonKind DCK)
7627       : S(S), RD(RD), FD(FD), DCK(DCK) {
7628     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7629       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7630       // UnresolvedSet to avoid this copy.
7631       Fns.assign(Info->getUnqualifiedLookups().begin(),
7632                  Info->getUnqualifiedLookups().end());
7633     }
7634   }
7635 
7636   ResultList visit() {
7637     // The type of an lvalue naming a parameter of this function.
7638     QualType ParamLvalType =
7639         FD->getParamDecl(0)->getType().getNonReferenceType();
7640 
7641     ResultList Results;
7642 
7643     switch (DCK) {
7644     case DefaultedComparisonKind::None:
7645       llvm_unreachable("not a defaulted comparison");
7646 
7647     case DefaultedComparisonKind::Equal:
7648     case DefaultedComparisonKind::ThreeWay:
7649       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7650       return Results;
7651 
7652     case DefaultedComparisonKind::NotEqual:
7653     case DefaultedComparisonKind::Relational:
7654       Results.add(getDerived().visitExpandedSubobject(
7655           ParamLvalType, getDerived().getCompleteObject()));
7656       return Results;
7657     }
7658     llvm_unreachable("");
7659   }
7660 
7661 protected:
7662   Derived &getDerived() { return static_cast<Derived&>(*this); }
7663 
7664   /// Visit the expanded list of subobjects of the given type, as specified in
7665   /// C++2a [class.compare.default].
7666   ///
7667   /// \return \c true if the ResultList object said we're done, \c false if not.
7668   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7669                        Qualifiers Quals) {
7670     // C++2a [class.compare.default]p4:
7671     //   The direct base class subobjects of C
7672     for (CXXBaseSpecifier &Base : Record->bases())
7673       if (Results.add(getDerived().visitSubobject(
7674               S.Context.getQualifiedType(Base.getType(), Quals),
7675               getDerived().getBase(&Base))))
7676         return true;
7677 
7678     //   followed by the non-static data members of C
7679     for (FieldDecl *Field : Record->fields()) {
7680       // Recursively expand anonymous structs.
7681       if (Field->isAnonymousStructOrUnion()) {
7682         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7683                             Quals))
7684           return true;
7685         continue;
7686       }
7687 
7688       // Figure out the type of an lvalue denoting this field.
7689       Qualifiers FieldQuals = Quals;
7690       if (Field->isMutable())
7691         FieldQuals.removeConst();
7692       QualType FieldType =
7693           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7694 
7695       if (Results.add(getDerived().visitSubobject(
7696               FieldType, getDerived().getField(Field))))
7697         return true;
7698     }
7699 
7700     //   form a list of subobjects.
7701     return false;
7702   }
7703 
7704   Result visitSubobject(QualType Type, Subobject Subobj) {
7705     //   In that list, any subobject of array type is recursively expanded
7706     const ArrayType *AT = S.Context.getAsArrayType(Type);
7707     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7708       return getDerived().visitSubobjectArray(CAT->getElementType(),
7709                                               CAT->getSize(), Subobj);
7710     return getDerived().visitExpandedSubobject(Type, Subobj);
7711   }
7712 
7713   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7714                              Subobject Subobj) {
7715     return getDerived().visitSubobject(Type, Subobj);
7716   }
7717 
7718 protected:
7719   Sema &S;
7720   CXXRecordDecl *RD;
7721   FunctionDecl *FD;
7722   DefaultedComparisonKind DCK;
7723   UnresolvedSet<16> Fns;
7724 };
7725 
7726 /// Information about a defaulted comparison, as determined by
7727 /// DefaultedComparisonAnalyzer.
7728 struct DefaultedComparisonInfo {
7729   bool Deleted = false;
7730   bool Constexpr = true;
7731   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7732 
7733   static DefaultedComparisonInfo deleted() {
7734     DefaultedComparisonInfo Deleted;
7735     Deleted.Deleted = true;
7736     return Deleted;
7737   }
7738 
7739   bool add(const DefaultedComparisonInfo &R) {
7740     Deleted |= R.Deleted;
7741     Constexpr &= R.Constexpr;
7742     Category = commonComparisonType(Category, R.Category);
7743     return Deleted;
7744   }
7745 };
7746 
7747 /// An element in the expanded list of subobjects of a defaulted comparison, as
7748 /// specified in C++2a [class.compare.default]p4.
7749 struct DefaultedComparisonSubobject {
7750   enum { CompleteObject, Member, Base } Kind;
7751   NamedDecl *Decl;
7752   SourceLocation Loc;
7753 };
7754 
7755 /// A visitor over the notional body of a defaulted comparison that determines
7756 /// whether that body would be deleted or constexpr.
7757 class DefaultedComparisonAnalyzer
7758     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7759                                         DefaultedComparisonInfo,
7760                                         DefaultedComparisonInfo,
7761                                         DefaultedComparisonSubobject> {
7762 public:
7763   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7764 
7765 private:
7766   DiagnosticKind Diagnose;
7767 
7768 public:
7769   using Base = DefaultedComparisonVisitor;
7770   using Result = DefaultedComparisonInfo;
7771   using Subobject = DefaultedComparisonSubobject;
7772 
7773   friend Base;
7774 
7775   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7776                               DefaultedComparisonKind DCK,
7777                               DiagnosticKind Diagnose = NoDiagnostics)
7778       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7779 
7780   Result visit() {
7781     if ((DCK == DefaultedComparisonKind::Equal ||
7782          DCK == DefaultedComparisonKind::ThreeWay) &&
7783         RD->hasVariantMembers()) {
7784       // C++2a [class.compare.default]p2 [P2002R0]:
7785       //   A defaulted comparison operator function for class C is defined as
7786       //   deleted if [...] C has variant members.
7787       if (Diagnose == ExplainDeleted) {
7788         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7789           << FD << RD->isUnion() << RD;
7790       }
7791       return Result::deleted();
7792     }
7793 
7794     return Base::visit();
7795   }
7796 
7797 private:
7798   Subobject getCompleteObject() {
7799     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7800   }
7801 
7802   Subobject getBase(CXXBaseSpecifier *Base) {
7803     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7804                      Base->getBaseTypeLoc()};
7805   }
7806 
7807   Subobject getField(FieldDecl *Field) {
7808     return Subobject{Subobject::Member, Field, Field->getLocation()};
7809   }
7810 
7811   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7812     // C++2a [class.compare.default]p2 [P2002R0]:
7813     //   A defaulted <=> or == operator function for class C is defined as
7814     //   deleted if any non-static data member of C is of reference type
7815     if (Type->isReferenceType()) {
7816       if (Diagnose == ExplainDeleted) {
7817         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7818             << FD << RD;
7819       }
7820       return Result::deleted();
7821     }
7822 
7823     // [...] Let xi be an lvalue denoting the ith element [...]
7824     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7825     Expr *Args[] = {&Xi, &Xi};
7826 
7827     // All operators start by trying to apply that same operator recursively.
7828     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7829     assert(OO != OO_None && "not an overloaded operator!");
7830     return visitBinaryOperator(OO, Args, Subobj);
7831   }
7832 
7833   Result
7834   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7835                       Subobject Subobj,
7836                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7837     // Note that there is no need to consider rewritten candidates here if
7838     // we've already found there is no viable 'operator<=>' candidate (and are
7839     // considering synthesizing a '<=>' from '==' and '<').
7840     OverloadCandidateSet CandidateSet(
7841         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7842         OverloadCandidateSet::OperatorRewriteInfo(
7843             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7844 
7845     /// C++2a [class.compare.default]p1 [P2002R0]:
7846     ///   [...] the defaulted function itself is never a candidate for overload
7847     ///   resolution [...]
7848     CandidateSet.exclude(FD);
7849 
7850     if (Args[0]->getType()->isOverloadableType())
7851       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7852     else
7853       // FIXME: We determine whether this is a valid expression by checking to
7854       // see if there's a viable builtin operator candidate for it. That isn't
7855       // really what the rules ask us to do, but should give the right results.
7856       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7857 
7858     Result R;
7859 
7860     OverloadCandidateSet::iterator Best;
7861     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7862     case OR_Success: {
7863       // C++2a [class.compare.secondary]p2 [P2002R0]:
7864       //   The operator function [...] is defined as deleted if [...] the
7865       //   candidate selected by overload resolution is not a rewritten
7866       //   candidate.
7867       if ((DCK == DefaultedComparisonKind::NotEqual ||
7868            DCK == DefaultedComparisonKind::Relational) &&
7869           !Best->RewriteKind) {
7870         if (Diagnose == ExplainDeleted) {
7871           if (Best->Function) {
7872             S.Diag(Best->Function->getLocation(),
7873                    diag::note_defaulted_comparison_not_rewritten_callee)
7874                 << FD;
7875           } else {
7876             assert(Best->Conversions.size() == 2 &&
7877                    Best->Conversions[0].isUserDefined() &&
7878                    "non-user-defined conversion from class to built-in "
7879                    "comparison");
7880             S.Diag(Best->Conversions[0]
7881                        .UserDefined.FoundConversionFunction.getDecl()
7882                        ->getLocation(),
7883                    diag::note_defaulted_comparison_not_rewritten_conversion)
7884                 << FD;
7885           }
7886         }
7887         return Result::deleted();
7888       }
7889 
7890       // Throughout C++2a [class.compare]: if overload resolution does not
7891       // result in a usable function, the candidate function is defined as
7892       // deleted. This requires that we selected an accessible function.
7893       //
7894       // Note that this only considers the access of the function when named
7895       // within the type of the subobject, and not the access path for any
7896       // derived-to-base conversion.
7897       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7898       if (ArgClass && Best->FoundDecl.getDecl() &&
7899           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7900         QualType ObjectType = Subobj.Kind == Subobject::Member
7901                                   ? Args[0]->getType()
7902                                   : S.Context.getRecordType(RD);
7903         if (!S.isMemberAccessibleForDeletion(
7904                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7905                 Diagnose == ExplainDeleted
7906                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7907                           << FD << Subobj.Kind << Subobj.Decl
7908                     : S.PDiag()))
7909           return Result::deleted();
7910       }
7911 
7912       bool NeedsDeducing =
7913           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7914 
7915       if (FunctionDecl *BestFD = Best->Function) {
7916         // C++2a [class.compare.default]p3 [P2002R0]:
7917         //   A defaulted comparison function is constexpr-compatible if
7918         //   [...] no overlod resolution performed [...] results in a
7919         //   non-constexpr function.
7920         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7921         // If it's not constexpr, explain why not.
7922         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7923           if (Subobj.Kind != Subobject::CompleteObject)
7924             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7925               << Subobj.Kind << Subobj.Decl;
7926           S.Diag(BestFD->getLocation(),
7927                  diag::note_defaulted_comparison_not_constexpr_here);
7928           // Bail out after explaining; we don't want any more notes.
7929           return Result::deleted();
7930         }
7931         R.Constexpr &= BestFD->isConstexpr();
7932 
7933         if (NeedsDeducing) {
7934           // If any callee has an undeduced return type, deduce it now.
7935           // FIXME: It's not clear how a failure here should be handled. For
7936           // now, we produce an eager diagnostic, because that is forward
7937           // compatible with most (all?) other reasonable options.
7938           if (BestFD->getReturnType()->isUndeducedType() &&
7939               S.DeduceReturnType(BestFD, FD->getLocation(),
7940                                  /*Diagnose=*/false)) {
7941             // Don't produce a duplicate error when asked to explain why the
7942             // comparison is deleted: we diagnosed that when initially checking
7943             // the defaulted operator.
7944             if (Diagnose == NoDiagnostics) {
7945               S.Diag(
7946                   FD->getLocation(),
7947                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7948                   << Subobj.Kind << Subobj.Decl;
7949               S.Diag(
7950                   Subobj.Loc,
7951                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7952                   << Subobj.Kind << Subobj.Decl;
7953               S.Diag(BestFD->getLocation(),
7954                      diag::note_defaulted_comparison_cannot_deduce_callee)
7955                   << Subobj.Kind << Subobj.Decl;
7956             }
7957             return Result::deleted();
7958           }
7959           auto *Info = S.Context.CompCategories.lookupInfoForType(
7960               BestFD->getCallResultType());
7961           if (!Info) {
7962             if (Diagnose == ExplainDeleted) {
7963               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7964                   << Subobj.Kind << Subobj.Decl
7965                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7966               S.Diag(BestFD->getLocation(),
7967                      diag::note_defaulted_comparison_cannot_deduce_callee)
7968                   << Subobj.Kind << Subobj.Decl;
7969             }
7970             return Result::deleted();
7971           }
7972           R.Category = Info->Kind;
7973         }
7974       } else {
7975         QualType T = Best->BuiltinParamTypes[0];
7976         assert(T == Best->BuiltinParamTypes[1] &&
7977                "builtin comparison for different types?");
7978         assert(Best->BuiltinParamTypes[2].isNull() &&
7979                "invalid builtin comparison");
7980 
7981         if (NeedsDeducing) {
7982           Optional<ComparisonCategoryType> Cat =
7983               getComparisonCategoryForBuiltinCmp(T);
7984           assert(Cat && "no category for builtin comparison?");
7985           R.Category = *Cat;
7986         }
7987       }
7988 
7989       // Note that we might be rewriting to a different operator. That call is
7990       // not considered until we come to actually build the comparison function.
7991       break;
7992     }
7993 
7994     case OR_Ambiguous:
7995       if (Diagnose == ExplainDeleted) {
7996         unsigned Kind = 0;
7997         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7998           Kind = OO == OO_EqualEqual ? 1 : 2;
7999         CandidateSet.NoteCandidates(
8000             PartialDiagnosticAt(
8001                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8002                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8003             S, OCD_AmbiguousCandidates, Args);
8004       }
8005       R = Result::deleted();
8006       break;
8007 
8008     case OR_Deleted:
8009       if (Diagnose == ExplainDeleted) {
8010         if ((DCK == DefaultedComparisonKind::NotEqual ||
8011              DCK == DefaultedComparisonKind::Relational) &&
8012             !Best->RewriteKind) {
8013           S.Diag(Best->Function->getLocation(),
8014                  diag::note_defaulted_comparison_not_rewritten_callee)
8015               << FD;
8016         } else {
8017           S.Diag(Subobj.Loc,
8018                  diag::note_defaulted_comparison_calls_deleted)
8019               << FD << Subobj.Kind << Subobj.Decl;
8020           S.NoteDeletedFunction(Best->Function);
8021         }
8022       }
8023       R = Result::deleted();
8024       break;
8025 
8026     case OR_No_Viable_Function:
8027       // If there's no usable candidate, we're done unless we can rewrite a
8028       // '<=>' in terms of '==' and '<'.
8029       if (OO == OO_Spaceship &&
8030           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8031         // For any kind of comparison category return type, we need a usable
8032         // '==' and a usable '<'.
8033         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8034                                        &CandidateSet)))
8035           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8036         break;
8037       }
8038 
8039       if (Diagnose == ExplainDeleted) {
8040         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8041             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8042 
8043         // For a three-way comparison, list both the candidates for the
8044         // original operator and the candidates for the synthesized operator.
8045         if (SpaceshipCandidates) {
8046           SpaceshipCandidates->NoteCandidates(
8047               S, Args,
8048               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8049                                                       Args, FD->getLocation()));
8050           S.Diag(Subobj.Loc,
8051                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8052               << (OO == OO_EqualEqual ? 0 : 1);
8053         }
8054 
8055         CandidateSet.NoteCandidates(
8056             S, Args,
8057             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8058                                             FD->getLocation()));
8059       }
8060       R = Result::deleted();
8061       break;
8062     }
8063 
8064     return R;
8065   }
8066 };
8067 
8068 /// A list of statements.
8069 struct StmtListResult {
8070   bool IsInvalid = false;
8071   llvm::SmallVector<Stmt*, 16> Stmts;
8072 
8073   bool add(const StmtResult &S) {
8074     IsInvalid |= S.isInvalid();
8075     if (IsInvalid)
8076       return true;
8077     Stmts.push_back(S.get());
8078     return false;
8079   }
8080 };
8081 
8082 /// A visitor over the notional body of a defaulted comparison that synthesizes
8083 /// the actual body.
8084 class DefaultedComparisonSynthesizer
8085     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8086                                         StmtListResult, StmtResult,
8087                                         std::pair<ExprResult, ExprResult>> {
8088   SourceLocation Loc;
8089   unsigned ArrayDepth = 0;
8090 
8091 public:
8092   using Base = DefaultedComparisonVisitor;
8093   using ExprPair = std::pair<ExprResult, ExprResult>;
8094 
8095   friend Base;
8096 
8097   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8098                                  DefaultedComparisonKind DCK,
8099                                  SourceLocation BodyLoc)
8100       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8101 
8102   /// Build a suitable function body for this defaulted comparison operator.
8103   StmtResult build() {
8104     Sema::CompoundScopeRAII CompoundScope(S);
8105 
8106     StmtListResult Stmts = visit();
8107     if (Stmts.IsInvalid)
8108       return StmtError();
8109 
8110     ExprResult RetVal;
8111     switch (DCK) {
8112     case DefaultedComparisonKind::None:
8113       llvm_unreachable("not a defaulted comparison");
8114 
8115     case DefaultedComparisonKind::Equal: {
8116       // C++2a [class.eq]p3:
8117       //   [...] compar[e] the corresponding elements [...] until the first
8118       //   index i where xi == yi yields [...] false. If no such index exists,
8119       //   V is true. Otherwise, V is false.
8120       //
8121       // Join the comparisons with '&&'s and return the result. Use a right
8122       // fold (traversing the conditions right-to-left), because that
8123       // short-circuits more naturally.
8124       auto OldStmts = std::move(Stmts.Stmts);
8125       Stmts.Stmts.clear();
8126       ExprResult CmpSoFar;
8127       // Finish a particular comparison chain.
8128       auto FinishCmp = [&] {
8129         if (Expr *Prior = CmpSoFar.get()) {
8130           // Convert the last expression to 'return ...;'
8131           if (RetVal.isUnset() && Stmts.Stmts.empty())
8132             RetVal = CmpSoFar;
8133           // Convert any prior comparison to 'if (!(...)) return false;'
8134           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8135             return true;
8136           CmpSoFar = ExprResult();
8137         }
8138         return false;
8139       };
8140       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8141         Expr *E = dyn_cast<Expr>(EAsStmt);
8142         if (!E) {
8143           // Found an array comparison.
8144           if (FinishCmp() || Stmts.add(EAsStmt))
8145             return StmtError();
8146           continue;
8147         }
8148 
8149         if (CmpSoFar.isUnset()) {
8150           CmpSoFar = E;
8151           continue;
8152         }
8153         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8154         if (CmpSoFar.isInvalid())
8155           return StmtError();
8156       }
8157       if (FinishCmp())
8158         return StmtError();
8159       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8160       //   If no such index exists, V is true.
8161       if (RetVal.isUnset())
8162         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8163       break;
8164     }
8165 
8166     case DefaultedComparisonKind::ThreeWay: {
8167       // Per C++2a [class.spaceship]p3, as a fallback add:
8168       // return static_cast<R>(std::strong_ordering::equal);
8169       QualType StrongOrdering = S.CheckComparisonCategoryType(
8170           ComparisonCategoryType::StrongOrdering, Loc,
8171           Sema::ComparisonCategoryUsage::DefaultedOperator);
8172       if (StrongOrdering.isNull())
8173         return StmtError();
8174       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8175                              .getValueInfo(ComparisonCategoryResult::Equal)
8176                              ->VD;
8177       RetVal = getDecl(EqualVD);
8178       if (RetVal.isInvalid())
8179         return StmtError();
8180       RetVal = buildStaticCastToR(RetVal.get());
8181       break;
8182     }
8183 
8184     case DefaultedComparisonKind::NotEqual:
8185     case DefaultedComparisonKind::Relational:
8186       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8187       break;
8188     }
8189 
8190     // Build the final return statement.
8191     if (RetVal.isInvalid())
8192       return StmtError();
8193     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8194     if (ReturnStmt.isInvalid())
8195       return StmtError();
8196     Stmts.Stmts.push_back(ReturnStmt.get());
8197 
8198     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8199   }
8200 
8201 private:
8202   ExprResult getDecl(ValueDecl *VD) {
8203     return S.BuildDeclarationNameExpr(
8204         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8205   }
8206 
8207   ExprResult getParam(unsigned I) {
8208     ParmVarDecl *PD = FD->getParamDecl(I);
8209     return getDecl(PD);
8210   }
8211 
8212   ExprPair getCompleteObject() {
8213     unsigned Param = 0;
8214     ExprResult LHS;
8215     if (isa<CXXMethodDecl>(FD)) {
8216       // LHS is '*this'.
8217       LHS = S.ActOnCXXThis(Loc);
8218       if (!LHS.isInvalid())
8219         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8220     } else {
8221       LHS = getParam(Param++);
8222     }
8223     ExprResult RHS = getParam(Param++);
8224     assert(Param == FD->getNumParams());
8225     return {LHS, RHS};
8226   }
8227 
8228   ExprPair getBase(CXXBaseSpecifier *Base) {
8229     ExprPair Obj = getCompleteObject();
8230     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8231       return {ExprError(), ExprError()};
8232     CXXCastPath Path = {Base};
8233     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8234                                 CK_DerivedToBase, VK_LValue, &Path),
8235             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8236                                 CK_DerivedToBase, VK_LValue, &Path)};
8237   }
8238 
8239   ExprPair getField(FieldDecl *Field) {
8240     ExprPair Obj = getCompleteObject();
8241     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8242       return {ExprError(), ExprError()};
8243 
8244     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8245     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8246     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8247                                       CXXScopeSpec(), Field, Found, NameInfo),
8248             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8249                                       CXXScopeSpec(), Field, Found, NameInfo)};
8250   }
8251 
8252   // FIXME: When expanding a subobject, register a note in the code synthesis
8253   // stack to say which subobject we're comparing.
8254 
8255   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8256     if (Cond.isInvalid())
8257       return StmtError();
8258 
8259     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8260     if (NotCond.isInvalid())
8261       return StmtError();
8262 
8263     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8264     assert(!False.isInvalid() && "should never fail");
8265     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8266     if (ReturnFalse.isInvalid())
8267       return StmtError();
8268 
8269     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8270                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8271                                           Sema::ConditionKind::Boolean),
8272                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8273   }
8274 
8275   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8276                                  ExprPair Subobj) {
8277     QualType SizeType = S.Context.getSizeType();
8278     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8279 
8280     // Build 'size_t i$n = 0'.
8281     IdentifierInfo *IterationVarName = nullptr;
8282     {
8283       SmallString<8> Str;
8284       llvm::raw_svector_ostream OS(Str);
8285       OS << "i" << ArrayDepth;
8286       IterationVarName = &S.Context.Idents.get(OS.str());
8287     }
8288     VarDecl *IterationVar = VarDecl::Create(
8289         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8290         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8291     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8292     IterationVar->setInit(
8293         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8294     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8295 
8296     auto IterRef = [&] {
8297       ExprResult Ref = S.BuildDeclarationNameExpr(
8298           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8299           IterationVar);
8300       assert(!Ref.isInvalid() && "can't reference our own variable?");
8301       return Ref.get();
8302     };
8303 
8304     // Build 'i$n != Size'.
8305     ExprResult Cond = S.CreateBuiltinBinOp(
8306         Loc, BO_NE, IterRef(),
8307         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8308     assert(!Cond.isInvalid() && "should never fail");
8309 
8310     // Build '++i$n'.
8311     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8312     assert(!Inc.isInvalid() && "should never fail");
8313 
8314     // Build 'a[i$n]' and 'b[i$n]'.
8315     auto Index = [&](ExprResult E) {
8316       if (E.isInvalid())
8317         return ExprError();
8318       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8319     };
8320     Subobj.first = Index(Subobj.first);
8321     Subobj.second = Index(Subobj.second);
8322 
8323     // Compare the array elements.
8324     ++ArrayDepth;
8325     StmtResult Substmt = visitSubobject(Type, Subobj);
8326     --ArrayDepth;
8327 
8328     if (Substmt.isInvalid())
8329       return StmtError();
8330 
8331     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8332     // For outer levels or for an 'operator<=>' we already have a suitable
8333     // statement that returns as necessary.
8334     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8335       assert(DCK == DefaultedComparisonKind::Equal &&
8336              "should have non-expression statement");
8337       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8338       if (Substmt.isInvalid())
8339         return StmtError();
8340     }
8341 
8342     // Build 'for (...) ...'
8343     return S.ActOnForStmt(Loc, Loc, Init,
8344                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8345                                            Sema::ConditionKind::Boolean),
8346                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8347                           Substmt.get());
8348   }
8349 
8350   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8351     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8352       return StmtError();
8353 
8354     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8355     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8356     ExprResult Op;
8357     if (Type->isOverloadableType())
8358       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8359                                    Obj.second.get(), /*PerformADL=*/true,
8360                                    /*AllowRewrittenCandidates=*/true, FD);
8361     else
8362       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8363     if (Op.isInvalid())
8364       return StmtError();
8365 
8366     switch (DCK) {
8367     case DefaultedComparisonKind::None:
8368       llvm_unreachable("not a defaulted comparison");
8369 
8370     case DefaultedComparisonKind::Equal:
8371       // Per C++2a [class.eq]p2, each comparison is individually contextually
8372       // converted to bool.
8373       Op = S.PerformContextuallyConvertToBool(Op.get());
8374       if (Op.isInvalid())
8375         return StmtError();
8376       return Op.get();
8377 
8378     case DefaultedComparisonKind::ThreeWay: {
8379       // Per C++2a [class.spaceship]p3, form:
8380       //   if (R cmp = static_cast<R>(op); cmp != 0)
8381       //     return cmp;
8382       QualType R = FD->getReturnType();
8383       Op = buildStaticCastToR(Op.get());
8384       if (Op.isInvalid())
8385         return StmtError();
8386 
8387       // R cmp = ...;
8388       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8389       VarDecl *VD =
8390           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8391                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8392       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8393       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8394 
8395       // cmp != 0
8396       ExprResult VDRef = getDecl(VD);
8397       if (VDRef.isInvalid())
8398         return StmtError();
8399       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8400       Expr *Zero =
8401           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8402       ExprResult Comp;
8403       if (VDRef.get()->getType()->isOverloadableType())
8404         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8405                                        true, FD);
8406       else
8407         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8408       if (Comp.isInvalid())
8409         return StmtError();
8410       Sema::ConditionResult Cond = S.ActOnCondition(
8411           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8412       if (Cond.isInvalid())
8413         return StmtError();
8414 
8415       // return cmp;
8416       VDRef = getDecl(VD);
8417       if (VDRef.isInvalid())
8418         return StmtError();
8419       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8420       if (ReturnStmt.isInvalid())
8421         return StmtError();
8422 
8423       // if (...)
8424       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8425                            Loc, ReturnStmt.get(),
8426                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8427     }
8428 
8429     case DefaultedComparisonKind::NotEqual:
8430     case DefaultedComparisonKind::Relational:
8431       // C++2a [class.compare.secondary]p2:
8432       //   Otherwise, the operator function yields x @ y.
8433       return Op.get();
8434     }
8435     llvm_unreachable("");
8436   }
8437 
8438   /// Build "static_cast<R>(E)".
8439   ExprResult buildStaticCastToR(Expr *E) {
8440     QualType R = FD->getReturnType();
8441     assert(!R->isUndeducedType() && "type should have been deduced already");
8442 
8443     // Don't bother forming a no-op cast in the common case.
8444     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8445       return E;
8446     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8447                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8448                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8449   }
8450 };
8451 }
8452 
8453 /// Perform the unqualified lookups that might be needed to form a defaulted
8454 /// comparison function for the given operator.
8455 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8456                                                   UnresolvedSetImpl &Operators,
8457                                                   OverloadedOperatorKind Op) {
8458   auto Lookup = [&](OverloadedOperatorKind OO) {
8459     Self.LookupOverloadedOperatorName(OO, S, Operators);
8460   };
8461 
8462   // Every defaulted operator looks up itself.
8463   Lookup(Op);
8464   // ... and the rewritten form of itself, if any.
8465   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8466     Lookup(ExtraOp);
8467 
8468   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8469   // synthesize a three-way comparison from '<' and '=='. In a dependent
8470   // context, we also need to look up '==' in case we implicitly declare a
8471   // defaulted 'operator=='.
8472   if (Op == OO_Spaceship) {
8473     Lookup(OO_ExclaimEqual);
8474     Lookup(OO_Less);
8475     Lookup(OO_EqualEqual);
8476   }
8477 }
8478 
8479 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8480                                               DefaultedComparisonKind DCK) {
8481   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8482 
8483   // Perform any unqualified lookups we're going to need to default this
8484   // function.
8485   if (S) {
8486     UnresolvedSet<32> Operators;
8487     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8488                                           FD->getOverloadedOperator());
8489     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8490         Context, Operators.pairs()));
8491   }
8492 
8493   // C++2a [class.compare.default]p1:
8494   //   A defaulted comparison operator function for some class C shall be a
8495   //   non-template function declared in the member-specification of C that is
8496   //    -- a non-static const member of C having one parameter of type
8497   //       const C&, or
8498   //    -- a friend of C having two parameters of type const C& or two
8499   //       parameters of type C.
8500 
8501   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8502   bool IsMethod = isa<CXXMethodDecl>(FD);
8503   if (IsMethod) {
8504     auto *MD = cast<CXXMethodDecl>(FD);
8505     assert(!MD->isStatic() && "comparison function cannot be a static member");
8506 
8507     // If we're out-of-class, this is the class we're comparing.
8508     if (!RD)
8509       RD = MD->getParent();
8510 
8511     if (!MD->isConst()) {
8512       SourceLocation InsertLoc;
8513       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8514         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8515       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8516       // corresponding defaulted 'operator<=>' already.
8517       if (!MD->isImplicit()) {
8518         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8519             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8520       }
8521 
8522       // Add the 'const' to the type to recover.
8523       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8524       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8525       EPI.TypeQuals.addConst();
8526       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8527                                           FPT->getParamTypes(), EPI));
8528     }
8529   }
8530 
8531   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8532     // Let's not worry about using a variadic template pack here -- who would do
8533     // such a thing?
8534     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8535         << int(IsMethod) << int(DCK);
8536     return true;
8537   }
8538 
8539   const ParmVarDecl *KnownParm = nullptr;
8540   for (const ParmVarDecl *Param : FD->parameters()) {
8541     QualType ParmTy = Param->getType();
8542     if (ParmTy->isDependentType())
8543       continue;
8544     if (!KnownParm) {
8545       auto CTy = ParmTy;
8546       // Is it `T const &`?
8547       bool Ok = !IsMethod;
8548       QualType ExpectedTy;
8549       if (RD)
8550         ExpectedTy = Context.getRecordType(RD);
8551       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8552         CTy = Ref->getPointeeType();
8553         if (RD)
8554           ExpectedTy.addConst();
8555         Ok = true;
8556       }
8557 
8558       // Is T a class?
8559       if (!Ok) {
8560       } else if (RD) {
8561         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8562           Ok = false;
8563       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8564         RD = cast<CXXRecordDecl>(CRD);
8565       } else {
8566         Ok = false;
8567       }
8568 
8569       if (Ok) {
8570         KnownParm = Param;
8571       } else {
8572         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8573         // corresponding defaulted 'operator<=>' already.
8574         if (!FD->isImplicit()) {
8575           if (RD) {
8576             QualType PlainTy = Context.getRecordType(RD);
8577             QualType RefTy =
8578                 Context.getLValueReferenceType(PlainTy.withConst());
8579             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8580                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8581                 << Param->getSourceRange();
8582           } else {
8583             assert(!IsMethod && "should know expected type for method");
8584             Diag(FD->getLocation(),
8585                  diag::err_defaulted_comparison_param_unknown)
8586                 << int(DCK) << ParmTy << Param->getSourceRange();
8587           }
8588         }
8589         return true;
8590       }
8591     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8592       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8593           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8594           << ParmTy << Param->getSourceRange();
8595       return true;
8596     }
8597   }
8598 
8599   assert(RD && "must have determined class");
8600   if (IsMethod) {
8601   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8602     // In-class, must be a friend decl.
8603     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8604   } else {
8605     // Out of class, require the defaulted comparison to be a friend (of a
8606     // complete type).
8607     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8608                             diag::err_defaulted_comparison_not_friend, int(DCK),
8609                             int(1)))
8610       return true;
8611 
8612     if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8613           return FD->getCanonicalDecl() ==
8614                  F->getFriendDecl()->getCanonicalDecl();
8615         }) == RD->friends().end()) {
8616       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8617           << int(DCK) << int(0) << RD;
8618       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8619       return true;
8620     }
8621   }
8622 
8623   // C++2a [class.eq]p1, [class.rel]p1:
8624   //   A [defaulted comparison other than <=>] shall have a declared return
8625   //   type bool.
8626   if (DCK != DefaultedComparisonKind::ThreeWay &&
8627       !FD->getDeclaredReturnType()->isDependentType() &&
8628       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8629     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8630         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8631         << FD->getReturnTypeSourceRange();
8632     return true;
8633   }
8634   // C++2a [class.spaceship]p2 [P2002R0]:
8635   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8636   //   R shall not contain a placeholder type.
8637   if (DCK == DefaultedComparisonKind::ThreeWay &&
8638       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8639       !Context.hasSameType(FD->getDeclaredReturnType(),
8640                            Context.getAutoDeductType())) {
8641     Diag(FD->getLocation(),
8642          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8643         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8644         << FD->getReturnTypeSourceRange();
8645     return true;
8646   }
8647 
8648   // For a defaulted function in a dependent class, defer all remaining checks
8649   // until instantiation.
8650   if (RD->isDependentType())
8651     return false;
8652 
8653   // Determine whether the function should be defined as deleted.
8654   DefaultedComparisonInfo Info =
8655       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8656 
8657   bool First = FD == FD->getCanonicalDecl();
8658 
8659   // If we want to delete the function, then do so; there's nothing else to
8660   // check in that case.
8661   if (Info.Deleted) {
8662     if (!First) {
8663       // C++11 [dcl.fct.def.default]p4:
8664       //   [For a] user-provided explicitly-defaulted function [...] if such a
8665       //   function is implicitly defined as deleted, the program is ill-formed.
8666       //
8667       // This is really just a consequence of the general rule that you can
8668       // only delete a function on its first declaration.
8669       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8670           << FD->isImplicit() << (int)DCK;
8671       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8672                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8673           .visit();
8674       return true;
8675     }
8676 
8677     SetDeclDeleted(FD, FD->getLocation());
8678     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8679       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8680           << (int)DCK;
8681       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8682                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8683           .visit();
8684     }
8685     return false;
8686   }
8687 
8688   // C++2a [class.spaceship]p2:
8689   //   The return type is deduced as the common comparison type of R0, R1, ...
8690   if (DCK == DefaultedComparisonKind::ThreeWay &&
8691       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8692     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8693     if (RetLoc.isInvalid())
8694       RetLoc = FD->getBeginLoc();
8695     // FIXME: Should we really care whether we have the complete type and the
8696     // 'enumerator' constants here? A forward declaration seems sufficient.
8697     QualType Cat = CheckComparisonCategoryType(
8698         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8699     if (Cat.isNull())
8700       return true;
8701     Context.adjustDeducedFunctionResultType(
8702         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8703   }
8704 
8705   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8706   //   An explicitly-defaulted function that is not defined as deleted may be
8707   //   declared constexpr or consteval only if it is constexpr-compatible.
8708   // C++2a [class.compare.default]p3 [P2002R0]:
8709   //   A defaulted comparison function is constexpr-compatible if it satisfies
8710   //   the requirements for a constexpr function [...]
8711   // The only relevant requirements are that the parameter and return types are
8712   // literal types. The remaining conditions are checked by the analyzer.
8713   if (FD->isConstexpr()) {
8714     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8715         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8716         !Info.Constexpr) {
8717       Diag(FD->getBeginLoc(),
8718            diag::err_incorrect_defaulted_comparison_constexpr)
8719           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8720       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8721                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8722           .visit();
8723     }
8724   }
8725 
8726   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8727   //   If a constexpr-compatible function is explicitly defaulted on its first
8728   //   declaration, it is implicitly considered to be constexpr.
8729   // FIXME: Only applying this to the first declaration seems problematic, as
8730   // simple reorderings can affect the meaning of the program.
8731   if (First && !FD->isConstexpr() && Info.Constexpr)
8732     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8733 
8734   // C++2a [except.spec]p3:
8735   //   If a declaration of a function does not have a noexcept-specifier
8736   //   [and] is defaulted on its first declaration, [...] the exception
8737   //   specification is as specified below
8738   if (FD->getExceptionSpecType() == EST_None) {
8739     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8740     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8741     EPI.ExceptionSpec.Type = EST_Unevaluated;
8742     EPI.ExceptionSpec.SourceDecl = FD;
8743     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8744                                         FPT->getParamTypes(), EPI));
8745   }
8746 
8747   return false;
8748 }
8749 
8750 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8751                                              FunctionDecl *Spaceship) {
8752   Sema::CodeSynthesisContext Ctx;
8753   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8754   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8755   Ctx.Entity = Spaceship;
8756   pushCodeSynthesisContext(Ctx);
8757 
8758   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8759     EqualEqual->setImplicit();
8760 
8761   popCodeSynthesisContext();
8762 }
8763 
8764 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8765                                      DefaultedComparisonKind DCK) {
8766   assert(FD->isDefaulted() && !FD->isDeleted() &&
8767          !FD->doesThisDeclarationHaveABody());
8768   if (FD->willHaveBody() || FD->isInvalidDecl())
8769     return;
8770 
8771   SynthesizedFunctionScope Scope(*this, FD);
8772 
8773   // Add a context note for diagnostics produced after this point.
8774   Scope.addContextNote(UseLoc);
8775 
8776   {
8777     // Build and set up the function body.
8778     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8779     // the type of the class being compared.
8780     auto PT = FD->getParamDecl(0)->getType();
8781     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8782     SourceLocation BodyLoc =
8783         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8784     StmtResult Body =
8785         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8786     if (Body.isInvalid()) {
8787       FD->setInvalidDecl();
8788       return;
8789     }
8790     FD->setBody(Body.get());
8791     FD->markUsed(Context);
8792   }
8793 
8794   // The exception specification is needed because we are defining the
8795   // function. Note that this will reuse the body we just built.
8796   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8797 
8798   if (ASTMutationListener *L = getASTMutationListener())
8799     L->CompletedImplicitDefinition(FD);
8800 }
8801 
8802 static Sema::ImplicitExceptionSpecification
8803 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8804                                         FunctionDecl *FD,
8805                                         Sema::DefaultedComparisonKind DCK) {
8806   ComputingExceptionSpec CES(S, FD, Loc);
8807   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8808 
8809   if (FD->isInvalidDecl())
8810     return ExceptSpec;
8811 
8812   // The common case is that we just defined the comparison function. In that
8813   // case, just look at whether the body can throw.
8814   if (FD->hasBody()) {
8815     ExceptSpec.CalledStmt(FD->getBody());
8816   } else {
8817     // Otherwise, build a body so we can check it. This should ideally only
8818     // happen when we're not actually marking the function referenced. (This is
8819     // only really important for efficiency: we don't want to build and throw
8820     // away bodies for comparison functions more than we strictly need to.)
8821 
8822     // Pretend to synthesize the function body in an unevaluated context.
8823     // Note that we can't actually just go ahead and define the function here:
8824     // we are not permitted to mark its callees as referenced.
8825     Sema::SynthesizedFunctionScope Scope(S, FD);
8826     EnterExpressionEvaluationContext Context(
8827         S, Sema::ExpressionEvaluationContext::Unevaluated);
8828 
8829     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8830     SourceLocation BodyLoc =
8831         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8832     StmtResult Body =
8833         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8834     if (!Body.isInvalid())
8835       ExceptSpec.CalledStmt(Body.get());
8836 
8837     // FIXME: Can we hold onto this body and just transform it to potentially
8838     // evaluated when we're asked to define the function rather than rebuilding
8839     // it? Either that, or we should only build the bits of the body that we
8840     // need (the expressions, not the statements).
8841   }
8842 
8843   return ExceptSpec;
8844 }
8845 
8846 void Sema::CheckDelayedMemberExceptionSpecs() {
8847   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8848   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8849 
8850   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8851   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8852 
8853   // Perform any deferred checking of exception specifications for virtual
8854   // destructors.
8855   for (auto &Check : Overriding)
8856     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8857 
8858   // Perform any deferred checking of exception specifications for befriended
8859   // special members.
8860   for (auto &Check : Equivalent)
8861     CheckEquivalentExceptionSpec(Check.second, Check.first);
8862 }
8863 
8864 namespace {
8865 /// CRTP base class for visiting operations performed by a special member
8866 /// function (or inherited constructor).
8867 template<typename Derived>
8868 struct SpecialMemberVisitor {
8869   Sema &S;
8870   CXXMethodDecl *MD;
8871   Sema::CXXSpecialMember CSM;
8872   Sema::InheritedConstructorInfo *ICI;
8873 
8874   // Properties of the special member, computed for convenience.
8875   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8876 
8877   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8878                        Sema::InheritedConstructorInfo *ICI)
8879       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8880     switch (CSM) {
8881     case Sema::CXXDefaultConstructor:
8882     case Sema::CXXCopyConstructor:
8883     case Sema::CXXMoveConstructor:
8884       IsConstructor = true;
8885       break;
8886     case Sema::CXXCopyAssignment:
8887     case Sema::CXXMoveAssignment:
8888       IsAssignment = true;
8889       break;
8890     case Sema::CXXDestructor:
8891       break;
8892     case Sema::CXXInvalid:
8893       llvm_unreachable("invalid special member kind");
8894     }
8895 
8896     if (MD->getNumParams()) {
8897       if (const ReferenceType *RT =
8898               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8899         ConstArg = RT->getPointeeType().isConstQualified();
8900     }
8901   }
8902 
8903   Derived &getDerived() { return static_cast<Derived&>(*this); }
8904 
8905   /// Is this a "move" special member?
8906   bool isMove() const {
8907     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8908   }
8909 
8910   /// Look up the corresponding special member in the given class.
8911   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8912                                              unsigned Quals, bool IsMutable) {
8913     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8914                                        ConstArg && !IsMutable);
8915   }
8916 
8917   /// Look up the constructor for the specified base class to see if it's
8918   /// overridden due to this being an inherited constructor.
8919   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8920     if (!ICI)
8921       return {};
8922     assert(CSM == Sema::CXXDefaultConstructor);
8923     auto *BaseCtor =
8924       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8925     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8926       return MD;
8927     return {};
8928   }
8929 
8930   /// A base or member subobject.
8931   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8932 
8933   /// Get the location to use for a subobject in diagnostics.
8934   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8935     // FIXME: For an indirect virtual base, the direct base leading to
8936     // the indirect virtual base would be a more useful choice.
8937     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8938       return B->getBaseTypeLoc();
8939     else
8940       return Subobj.get<FieldDecl*>()->getLocation();
8941   }
8942 
8943   enum BasesToVisit {
8944     /// Visit all non-virtual (direct) bases.
8945     VisitNonVirtualBases,
8946     /// Visit all direct bases, virtual or not.
8947     VisitDirectBases,
8948     /// Visit all non-virtual bases, and all virtual bases if the class
8949     /// is not abstract.
8950     VisitPotentiallyConstructedBases,
8951     /// Visit all direct or virtual bases.
8952     VisitAllBases
8953   };
8954 
8955   // Visit the bases and members of the class.
8956   bool visit(BasesToVisit Bases) {
8957     CXXRecordDecl *RD = MD->getParent();
8958 
8959     if (Bases == VisitPotentiallyConstructedBases)
8960       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8961 
8962     for (auto &B : RD->bases())
8963       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8964           getDerived().visitBase(&B))
8965         return true;
8966 
8967     if (Bases == VisitAllBases)
8968       for (auto &B : RD->vbases())
8969         if (getDerived().visitBase(&B))
8970           return true;
8971 
8972     for (auto *F : RD->fields())
8973       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8974           getDerived().visitField(F))
8975         return true;
8976 
8977     return false;
8978   }
8979 };
8980 }
8981 
8982 namespace {
8983 struct SpecialMemberDeletionInfo
8984     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8985   bool Diagnose;
8986 
8987   SourceLocation Loc;
8988 
8989   bool AllFieldsAreConst;
8990 
8991   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8992                             Sema::CXXSpecialMember CSM,
8993                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8994       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8995         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8996 
8997   bool inUnion() const { return MD->getParent()->isUnion(); }
8998 
8999   Sema::CXXSpecialMember getEffectiveCSM() {
9000     return ICI ? Sema::CXXInvalid : CSM;
9001   }
9002 
9003   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9004 
9005   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9006   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9007 
9008   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9009   bool shouldDeleteForField(FieldDecl *FD);
9010   bool shouldDeleteForAllConstMembers();
9011 
9012   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9013                                      unsigned Quals);
9014   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9015                                     Sema::SpecialMemberOverloadResult SMOR,
9016                                     bool IsDtorCallInCtor);
9017 
9018   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9019 };
9020 }
9021 
9022 /// Is the given special member inaccessible when used on the given
9023 /// sub-object.
9024 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9025                                              CXXMethodDecl *target) {
9026   /// If we're operating on a base class, the object type is the
9027   /// type of this special member.
9028   QualType objectTy;
9029   AccessSpecifier access = target->getAccess();
9030   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9031     objectTy = S.Context.getTypeDeclType(MD->getParent());
9032     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9033 
9034   // If we're operating on a field, the object type is the type of the field.
9035   } else {
9036     objectTy = S.Context.getTypeDeclType(target->getParent());
9037   }
9038 
9039   return S.isMemberAccessibleForDeletion(
9040       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9041 }
9042 
9043 /// Check whether we should delete a special member due to the implicit
9044 /// definition containing a call to a special member of a subobject.
9045 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9046     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9047     bool IsDtorCallInCtor) {
9048   CXXMethodDecl *Decl = SMOR.getMethod();
9049   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9050 
9051   int DiagKind = -1;
9052 
9053   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9054     DiagKind = !Decl ? 0 : 1;
9055   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9056     DiagKind = 2;
9057   else if (!isAccessible(Subobj, Decl))
9058     DiagKind = 3;
9059   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9060            !Decl->isTrivial()) {
9061     // A member of a union must have a trivial corresponding special member.
9062     // As a weird special case, a destructor call from a union's constructor
9063     // must be accessible and non-deleted, but need not be trivial. Such a
9064     // destructor is never actually called, but is semantically checked as
9065     // if it were.
9066     DiagKind = 4;
9067   }
9068 
9069   if (DiagKind == -1)
9070     return false;
9071 
9072   if (Diagnose) {
9073     if (Field) {
9074       S.Diag(Field->getLocation(),
9075              diag::note_deleted_special_member_class_subobject)
9076         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9077         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9078     } else {
9079       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9080       S.Diag(Base->getBeginLoc(),
9081              diag::note_deleted_special_member_class_subobject)
9082           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9083           << Base->getType() << DiagKind << IsDtorCallInCtor
9084           << /*IsObjCPtr*/false;
9085     }
9086 
9087     if (DiagKind == 1)
9088       S.NoteDeletedFunction(Decl);
9089     // FIXME: Explain inaccessibility if DiagKind == 3.
9090   }
9091 
9092   return true;
9093 }
9094 
9095 /// Check whether we should delete a special member function due to having a
9096 /// direct or virtual base class or non-static data member of class type M.
9097 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9098     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9099   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9100   bool IsMutable = Field && Field->isMutable();
9101 
9102   // C++11 [class.ctor]p5:
9103   // -- any direct or virtual base class, or non-static data member with no
9104   //    brace-or-equal-initializer, has class type M (or array thereof) and
9105   //    either M has no default constructor or overload resolution as applied
9106   //    to M's default constructor results in an ambiguity or in a function
9107   //    that is deleted or inaccessible
9108   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9109   // -- a direct or virtual base class B that cannot be copied/moved because
9110   //    overload resolution, as applied to B's corresponding special member,
9111   //    results in an ambiguity or a function that is deleted or inaccessible
9112   //    from the defaulted special member
9113   // C++11 [class.dtor]p5:
9114   // -- any direct or virtual base class [...] has a type with a destructor
9115   //    that is deleted or inaccessible
9116   if (!(CSM == Sema::CXXDefaultConstructor &&
9117         Field && Field->hasInClassInitializer()) &&
9118       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9119                                    false))
9120     return true;
9121 
9122   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9123   // -- any direct or virtual base class or non-static data member has a
9124   //    type with a destructor that is deleted or inaccessible
9125   if (IsConstructor) {
9126     Sema::SpecialMemberOverloadResult SMOR =
9127         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9128                               false, false, false, false, false);
9129     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9130       return true;
9131   }
9132 
9133   return false;
9134 }
9135 
9136 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9137     FieldDecl *FD, QualType FieldType) {
9138   // The defaulted special functions are defined as deleted if this is a variant
9139   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9140   // type under ARC.
9141   if (!FieldType.hasNonTrivialObjCLifetime())
9142     return false;
9143 
9144   // Don't make the defaulted default constructor defined as deleted if the
9145   // member has an in-class initializer.
9146   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9147     return false;
9148 
9149   if (Diagnose) {
9150     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9151     S.Diag(FD->getLocation(),
9152            diag::note_deleted_special_member_class_subobject)
9153         << getEffectiveCSM() << ParentClass << /*IsField*/true
9154         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9155   }
9156 
9157   return true;
9158 }
9159 
9160 /// Check whether we should delete a special member function due to the class
9161 /// having a particular direct or virtual base class.
9162 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9163   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9164   // If program is correct, BaseClass cannot be null, but if it is, the error
9165   // must be reported elsewhere.
9166   if (!BaseClass)
9167     return false;
9168   // If we have an inheriting constructor, check whether we're calling an
9169   // inherited constructor instead of a default constructor.
9170   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9171   if (auto *BaseCtor = SMOR.getMethod()) {
9172     // Note that we do not check access along this path; other than that,
9173     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9174     // FIXME: Check that the base has a usable destructor! Sink this into
9175     // shouldDeleteForClassSubobject.
9176     if (BaseCtor->isDeleted() && Diagnose) {
9177       S.Diag(Base->getBeginLoc(),
9178              diag::note_deleted_special_member_class_subobject)
9179           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9180           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9181           << /*IsObjCPtr*/false;
9182       S.NoteDeletedFunction(BaseCtor);
9183     }
9184     return BaseCtor->isDeleted();
9185   }
9186   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9187 }
9188 
9189 /// Check whether we should delete a special member function due to the class
9190 /// having a particular non-static data member.
9191 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9192   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9193   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9194 
9195   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9196     return true;
9197 
9198   if (CSM == Sema::CXXDefaultConstructor) {
9199     // For a default constructor, all references must be initialized in-class
9200     // and, if a union, it must have a non-const member.
9201     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9202       if (Diagnose)
9203         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9204           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9205       return true;
9206     }
9207     // C++11 [class.ctor]p5: any non-variant non-static data member of
9208     // const-qualified type (or array thereof) with no
9209     // brace-or-equal-initializer does not have a user-provided default
9210     // constructor.
9211     if (!inUnion() && FieldType.isConstQualified() &&
9212         !FD->hasInClassInitializer() &&
9213         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9214       if (Diagnose)
9215         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9216           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9217       return true;
9218     }
9219 
9220     if (inUnion() && !FieldType.isConstQualified())
9221       AllFieldsAreConst = false;
9222   } else if (CSM == Sema::CXXCopyConstructor) {
9223     // For a copy constructor, data members must not be of rvalue reference
9224     // type.
9225     if (FieldType->isRValueReferenceType()) {
9226       if (Diagnose)
9227         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9228           << MD->getParent() << FD << FieldType;
9229       return true;
9230     }
9231   } else if (IsAssignment) {
9232     // For an assignment operator, data members must not be of reference type.
9233     if (FieldType->isReferenceType()) {
9234       if (Diagnose)
9235         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9236           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9237       return true;
9238     }
9239     if (!FieldRecord && FieldType.isConstQualified()) {
9240       // C++11 [class.copy]p23:
9241       // -- a non-static data member of const non-class type (or array thereof)
9242       if (Diagnose)
9243         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9244           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9245       return true;
9246     }
9247   }
9248 
9249   if (FieldRecord) {
9250     // Some additional restrictions exist on the variant members.
9251     if (!inUnion() && FieldRecord->isUnion() &&
9252         FieldRecord->isAnonymousStructOrUnion()) {
9253       bool AllVariantFieldsAreConst = true;
9254 
9255       // FIXME: Handle anonymous unions declared within anonymous unions.
9256       for (auto *UI : FieldRecord->fields()) {
9257         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9258 
9259         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9260           return true;
9261 
9262         if (!UnionFieldType.isConstQualified())
9263           AllVariantFieldsAreConst = false;
9264 
9265         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9266         if (UnionFieldRecord &&
9267             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9268                                           UnionFieldType.getCVRQualifiers()))
9269           return true;
9270       }
9271 
9272       // At least one member in each anonymous union must be non-const
9273       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9274           !FieldRecord->field_empty()) {
9275         if (Diagnose)
9276           S.Diag(FieldRecord->getLocation(),
9277                  diag::note_deleted_default_ctor_all_const)
9278             << !!ICI << MD->getParent() << /*anonymous union*/1;
9279         return true;
9280       }
9281 
9282       // Don't check the implicit member of the anonymous union type.
9283       // This is technically non-conformant but supported, and we have a
9284       // diagnostic for this elsewhere.
9285       return false;
9286     }
9287 
9288     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9289                                       FieldType.getCVRQualifiers()))
9290       return true;
9291   }
9292 
9293   return false;
9294 }
9295 
9296 /// C++11 [class.ctor] p5:
9297 ///   A defaulted default constructor for a class X is defined as deleted if
9298 /// X is a union and all of its variant members are of const-qualified type.
9299 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9300   // This is a silly definition, because it gives an empty union a deleted
9301   // default constructor. Don't do that.
9302   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9303     bool AnyFields = false;
9304     for (auto *F : MD->getParent()->fields())
9305       if ((AnyFields = !F->isUnnamedBitfield()))
9306         break;
9307     if (!AnyFields)
9308       return false;
9309     if (Diagnose)
9310       S.Diag(MD->getParent()->getLocation(),
9311              diag::note_deleted_default_ctor_all_const)
9312         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9313     return true;
9314   }
9315   return false;
9316 }
9317 
9318 /// Determine whether a defaulted special member function should be defined as
9319 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9320 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9321 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9322                                      InheritedConstructorInfo *ICI,
9323                                      bool Diagnose) {
9324   if (MD->isInvalidDecl())
9325     return false;
9326   CXXRecordDecl *RD = MD->getParent();
9327   assert(!RD->isDependentType() && "do deletion after instantiation");
9328   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9329     return false;
9330 
9331   // C++11 [expr.lambda.prim]p19:
9332   //   The closure type associated with a lambda-expression has a
9333   //   deleted (8.4.3) default constructor and a deleted copy
9334   //   assignment operator.
9335   // C++2a adds back these operators if the lambda has no lambda-capture.
9336   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9337       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9338     if (Diagnose)
9339       Diag(RD->getLocation(), diag::note_lambda_decl);
9340     return true;
9341   }
9342 
9343   // For an anonymous struct or union, the copy and assignment special members
9344   // will never be used, so skip the check. For an anonymous union declared at
9345   // namespace scope, the constructor and destructor are used.
9346   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9347       RD->isAnonymousStructOrUnion())
9348     return false;
9349 
9350   // C++11 [class.copy]p7, p18:
9351   //   If the class definition declares a move constructor or move assignment
9352   //   operator, an implicitly declared copy constructor or copy assignment
9353   //   operator is defined as deleted.
9354   if (MD->isImplicit() &&
9355       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9356     CXXMethodDecl *UserDeclaredMove = nullptr;
9357 
9358     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9359     // deletion of the corresponding copy operation, not both copy operations.
9360     // MSVC 2015 has adopted the standards conforming behavior.
9361     bool DeletesOnlyMatchingCopy =
9362         getLangOpts().MSVCCompat &&
9363         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9364 
9365     if (RD->hasUserDeclaredMoveConstructor() &&
9366         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9367       if (!Diagnose) return true;
9368 
9369       // Find any user-declared move constructor.
9370       for (auto *I : RD->ctors()) {
9371         if (I->isMoveConstructor()) {
9372           UserDeclaredMove = I;
9373           break;
9374         }
9375       }
9376       assert(UserDeclaredMove);
9377     } else if (RD->hasUserDeclaredMoveAssignment() &&
9378                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9379       if (!Diagnose) return true;
9380 
9381       // Find any user-declared move assignment operator.
9382       for (auto *I : RD->methods()) {
9383         if (I->isMoveAssignmentOperator()) {
9384           UserDeclaredMove = I;
9385           break;
9386         }
9387       }
9388       assert(UserDeclaredMove);
9389     }
9390 
9391     if (UserDeclaredMove) {
9392       Diag(UserDeclaredMove->getLocation(),
9393            diag::note_deleted_copy_user_declared_move)
9394         << (CSM == CXXCopyAssignment) << RD
9395         << UserDeclaredMove->isMoveAssignmentOperator();
9396       return true;
9397     }
9398   }
9399 
9400   // Do access control from the special member function
9401   ContextRAII MethodContext(*this, MD);
9402 
9403   // C++11 [class.dtor]p5:
9404   // -- for a virtual destructor, lookup of the non-array deallocation function
9405   //    results in an ambiguity or in a function that is deleted or inaccessible
9406   if (CSM == CXXDestructor && MD->isVirtual()) {
9407     FunctionDecl *OperatorDelete = nullptr;
9408     DeclarationName Name =
9409       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9410     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9411                                  OperatorDelete, /*Diagnose*/false)) {
9412       if (Diagnose)
9413         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9414       return true;
9415     }
9416   }
9417 
9418   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9419 
9420   // Per DR1611, do not consider virtual bases of constructors of abstract
9421   // classes, since we are not going to construct them.
9422   // Per DR1658, do not consider virtual bases of destructors of abstract
9423   // classes either.
9424   // Per DR2180, for assignment operators we only assign (and thus only
9425   // consider) direct bases.
9426   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9427                                  : SMI.VisitPotentiallyConstructedBases))
9428     return true;
9429 
9430   if (SMI.shouldDeleteForAllConstMembers())
9431     return true;
9432 
9433   if (getLangOpts().CUDA) {
9434     // We should delete the special member in CUDA mode if target inference
9435     // failed.
9436     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9437     // is treated as certain special member, which may not reflect what special
9438     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9439     // expects CSM to match MD, therefore recalculate CSM.
9440     assert(ICI || CSM == getSpecialMember(MD));
9441     auto RealCSM = CSM;
9442     if (ICI)
9443       RealCSM = getSpecialMember(MD);
9444 
9445     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9446                                                    SMI.ConstArg, Diagnose);
9447   }
9448 
9449   return false;
9450 }
9451 
9452 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9453   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9454   assert(DFK && "not a defaultable function");
9455   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9456 
9457   if (DFK.isSpecialMember()) {
9458     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9459                               nullptr, /*Diagnose=*/true);
9460   } else {
9461     DefaultedComparisonAnalyzer(
9462         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9463         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9464         .visit();
9465   }
9466 }
9467 
9468 /// Perform lookup for a special member of the specified kind, and determine
9469 /// whether it is trivial. If the triviality can be determined without the
9470 /// lookup, skip it. This is intended for use when determining whether a
9471 /// special member of a containing object is trivial, and thus does not ever
9472 /// perform overload resolution for default constructors.
9473 ///
9474 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9475 /// member that was most likely to be intended to be trivial, if any.
9476 ///
9477 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9478 /// determine whether the special member is trivial.
9479 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9480                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9481                                      bool ConstRHS,
9482                                      Sema::TrivialABIHandling TAH,
9483                                      CXXMethodDecl **Selected) {
9484   if (Selected)
9485     *Selected = nullptr;
9486 
9487   switch (CSM) {
9488   case Sema::CXXInvalid:
9489     llvm_unreachable("not a special member");
9490 
9491   case Sema::CXXDefaultConstructor:
9492     // C++11 [class.ctor]p5:
9493     //   A default constructor is trivial if:
9494     //    - all the [direct subobjects] have trivial default constructors
9495     //
9496     // Note, no overload resolution is performed in this case.
9497     if (RD->hasTrivialDefaultConstructor())
9498       return true;
9499 
9500     if (Selected) {
9501       // If there's a default constructor which could have been trivial, dig it
9502       // out. Otherwise, if there's any user-provided default constructor, point
9503       // to that as an example of why there's not a trivial one.
9504       CXXConstructorDecl *DefCtor = nullptr;
9505       if (RD->needsImplicitDefaultConstructor())
9506         S.DeclareImplicitDefaultConstructor(RD);
9507       for (auto *CI : RD->ctors()) {
9508         if (!CI->isDefaultConstructor())
9509           continue;
9510         DefCtor = CI;
9511         if (!DefCtor->isUserProvided())
9512           break;
9513       }
9514 
9515       *Selected = DefCtor;
9516     }
9517 
9518     return false;
9519 
9520   case Sema::CXXDestructor:
9521     // C++11 [class.dtor]p5:
9522     //   A destructor is trivial if:
9523     //    - all the direct [subobjects] have trivial destructors
9524     if (RD->hasTrivialDestructor() ||
9525         (TAH == Sema::TAH_ConsiderTrivialABI &&
9526          RD->hasTrivialDestructorForCall()))
9527       return true;
9528 
9529     if (Selected) {
9530       if (RD->needsImplicitDestructor())
9531         S.DeclareImplicitDestructor(RD);
9532       *Selected = RD->getDestructor();
9533     }
9534 
9535     return false;
9536 
9537   case Sema::CXXCopyConstructor:
9538     // C++11 [class.copy]p12:
9539     //   A copy constructor is trivial if:
9540     //    - the constructor selected to copy each direct [subobject] is trivial
9541     if (RD->hasTrivialCopyConstructor() ||
9542         (TAH == Sema::TAH_ConsiderTrivialABI &&
9543          RD->hasTrivialCopyConstructorForCall())) {
9544       if (Quals == Qualifiers::Const)
9545         // We must either select the trivial copy constructor or reach an
9546         // ambiguity; no need to actually perform overload resolution.
9547         return true;
9548     } else if (!Selected) {
9549       return false;
9550     }
9551     // In C++98, we are not supposed to perform overload resolution here, but we
9552     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9553     // cases like B as having a non-trivial copy constructor:
9554     //   struct A { template<typename T> A(T&); };
9555     //   struct B { mutable A a; };
9556     goto NeedOverloadResolution;
9557 
9558   case Sema::CXXCopyAssignment:
9559     // C++11 [class.copy]p25:
9560     //   A copy assignment operator is trivial if:
9561     //    - the assignment operator selected to copy each direct [subobject] is
9562     //      trivial
9563     if (RD->hasTrivialCopyAssignment()) {
9564       if (Quals == Qualifiers::Const)
9565         return true;
9566     } else if (!Selected) {
9567       return false;
9568     }
9569     // In C++98, we are not supposed to perform overload resolution here, but we
9570     // treat that as a language defect.
9571     goto NeedOverloadResolution;
9572 
9573   case Sema::CXXMoveConstructor:
9574   case Sema::CXXMoveAssignment:
9575   NeedOverloadResolution:
9576     Sema::SpecialMemberOverloadResult SMOR =
9577         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9578 
9579     // The standard doesn't describe how to behave if the lookup is ambiguous.
9580     // We treat it as not making the member non-trivial, just like the standard
9581     // mandates for the default constructor. This should rarely matter, because
9582     // the member will also be deleted.
9583     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9584       return true;
9585 
9586     if (!SMOR.getMethod()) {
9587       assert(SMOR.getKind() ==
9588              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9589       return false;
9590     }
9591 
9592     // We deliberately don't check if we found a deleted special member. We're
9593     // not supposed to!
9594     if (Selected)
9595       *Selected = SMOR.getMethod();
9596 
9597     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9598         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9599       return SMOR.getMethod()->isTrivialForCall();
9600     return SMOR.getMethod()->isTrivial();
9601   }
9602 
9603   llvm_unreachable("unknown special method kind");
9604 }
9605 
9606 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9607   for (auto *CI : RD->ctors())
9608     if (!CI->isImplicit())
9609       return CI;
9610 
9611   // Look for constructor templates.
9612   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9613   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9614     if (CXXConstructorDecl *CD =
9615           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9616       return CD;
9617   }
9618 
9619   return nullptr;
9620 }
9621 
9622 /// The kind of subobject we are checking for triviality. The values of this
9623 /// enumeration are used in diagnostics.
9624 enum TrivialSubobjectKind {
9625   /// The subobject is a base class.
9626   TSK_BaseClass,
9627   /// The subobject is a non-static data member.
9628   TSK_Field,
9629   /// The object is actually the complete object.
9630   TSK_CompleteObject
9631 };
9632 
9633 /// Check whether the special member selected for a given type would be trivial.
9634 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9635                                       QualType SubType, bool ConstRHS,
9636                                       Sema::CXXSpecialMember CSM,
9637                                       TrivialSubobjectKind Kind,
9638                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9639   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9640   if (!SubRD)
9641     return true;
9642 
9643   CXXMethodDecl *Selected;
9644   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9645                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9646     return true;
9647 
9648   if (Diagnose) {
9649     if (ConstRHS)
9650       SubType.addConst();
9651 
9652     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9653       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9654         << Kind << SubType.getUnqualifiedType();
9655       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9656         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9657     } else if (!Selected)
9658       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9659         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9660     else if (Selected->isUserProvided()) {
9661       if (Kind == TSK_CompleteObject)
9662         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9663           << Kind << SubType.getUnqualifiedType() << CSM;
9664       else {
9665         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9666           << Kind << SubType.getUnqualifiedType() << CSM;
9667         S.Diag(Selected->getLocation(), diag::note_declared_at);
9668       }
9669     } else {
9670       if (Kind != TSK_CompleteObject)
9671         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9672           << Kind << SubType.getUnqualifiedType() << CSM;
9673 
9674       // Explain why the defaulted or deleted special member isn't trivial.
9675       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9676                                Diagnose);
9677     }
9678   }
9679 
9680   return false;
9681 }
9682 
9683 /// Check whether the members of a class type allow a special member to be
9684 /// trivial.
9685 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9686                                      Sema::CXXSpecialMember CSM,
9687                                      bool ConstArg,
9688                                      Sema::TrivialABIHandling TAH,
9689                                      bool Diagnose) {
9690   for (const auto *FI : RD->fields()) {
9691     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9692       continue;
9693 
9694     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9695 
9696     // Pretend anonymous struct or union members are members of this class.
9697     if (FI->isAnonymousStructOrUnion()) {
9698       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9699                                     CSM, ConstArg, TAH, Diagnose))
9700         return false;
9701       continue;
9702     }
9703 
9704     // C++11 [class.ctor]p5:
9705     //   A default constructor is trivial if [...]
9706     //    -- no non-static data member of its class has a
9707     //       brace-or-equal-initializer
9708     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9709       if (Diagnose)
9710         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9711             << FI;
9712       return false;
9713     }
9714 
9715     // Objective C ARC 4.3.5:
9716     //   [...] nontrivally ownership-qualified types are [...] not trivially
9717     //   default constructible, copy constructible, move constructible, copy
9718     //   assignable, move assignable, or destructible [...]
9719     if (FieldType.hasNonTrivialObjCLifetime()) {
9720       if (Diagnose)
9721         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9722           << RD << FieldType.getObjCLifetime();
9723       return false;
9724     }
9725 
9726     bool ConstRHS = ConstArg && !FI->isMutable();
9727     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9728                                    CSM, TSK_Field, TAH, Diagnose))
9729       return false;
9730   }
9731 
9732   return true;
9733 }
9734 
9735 /// Diagnose why the specified class does not have a trivial special member of
9736 /// the given kind.
9737 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9738   QualType Ty = Context.getRecordType(RD);
9739 
9740   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9741   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9742                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9743                             /*Diagnose*/true);
9744 }
9745 
9746 /// Determine whether a defaulted or deleted special member function is trivial,
9747 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9748 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9749 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9750                                   TrivialABIHandling TAH, bool Diagnose) {
9751   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9752 
9753   CXXRecordDecl *RD = MD->getParent();
9754 
9755   bool ConstArg = false;
9756 
9757   // C++11 [class.copy]p12, p25: [DR1593]
9758   //   A [special member] is trivial if [...] its parameter-type-list is
9759   //   equivalent to the parameter-type-list of an implicit declaration [...]
9760   switch (CSM) {
9761   case CXXDefaultConstructor:
9762   case CXXDestructor:
9763     // Trivial default constructors and destructors cannot have parameters.
9764     break;
9765 
9766   case CXXCopyConstructor:
9767   case CXXCopyAssignment: {
9768     // Trivial copy operations always have const, non-volatile parameter types.
9769     ConstArg = true;
9770     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9771     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9772     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9773       if (Diagnose)
9774         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9775           << Param0->getSourceRange() << Param0->getType()
9776           << Context.getLValueReferenceType(
9777                Context.getRecordType(RD).withConst());
9778       return false;
9779     }
9780     break;
9781   }
9782 
9783   case CXXMoveConstructor:
9784   case CXXMoveAssignment: {
9785     // Trivial move operations always have non-cv-qualified parameters.
9786     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9787     const RValueReferenceType *RT =
9788       Param0->getType()->getAs<RValueReferenceType>();
9789     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9790       if (Diagnose)
9791         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9792           << Param0->getSourceRange() << Param0->getType()
9793           << Context.getRValueReferenceType(Context.getRecordType(RD));
9794       return false;
9795     }
9796     break;
9797   }
9798 
9799   case CXXInvalid:
9800     llvm_unreachable("not a special member");
9801   }
9802 
9803   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9804     if (Diagnose)
9805       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9806            diag::note_nontrivial_default_arg)
9807         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9808     return false;
9809   }
9810   if (MD->isVariadic()) {
9811     if (Diagnose)
9812       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9813     return false;
9814   }
9815 
9816   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9817   //   A copy/move [constructor or assignment operator] is trivial if
9818   //    -- the [member] selected to copy/move each direct base class subobject
9819   //       is trivial
9820   //
9821   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9822   //   A [default constructor or destructor] is trivial if
9823   //    -- all the direct base classes have trivial [default constructors or
9824   //       destructors]
9825   for (const auto &BI : RD->bases())
9826     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9827                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9828       return false;
9829 
9830   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9831   //   A copy/move [constructor or assignment operator] for a class X is
9832   //   trivial if
9833   //    -- for each non-static data member of X that is of class type (or array
9834   //       thereof), the constructor selected to copy/move that member is
9835   //       trivial
9836   //
9837   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9838   //   A [default constructor or destructor] is trivial if
9839   //    -- for all of the non-static data members of its class that are of class
9840   //       type (or array thereof), each such class has a trivial [default
9841   //       constructor or destructor]
9842   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9843     return false;
9844 
9845   // C++11 [class.dtor]p5:
9846   //   A destructor is trivial if [...]
9847   //    -- the destructor is not virtual
9848   if (CSM == CXXDestructor && MD->isVirtual()) {
9849     if (Diagnose)
9850       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9851     return false;
9852   }
9853 
9854   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9855   //   A [special member] for class X is trivial if [...]
9856   //    -- class X has no virtual functions and no virtual base classes
9857   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9858     if (!Diagnose)
9859       return false;
9860 
9861     if (RD->getNumVBases()) {
9862       // Check for virtual bases. We already know that the corresponding
9863       // member in all bases is trivial, so vbases must all be direct.
9864       CXXBaseSpecifier &BS = *RD->vbases_begin();
9865       assert(BS.isVirtual());
9866       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9867       return false;
9868     }
9869 
9870     // Must have a virtual method.
9871     for (const auto *MI : RD->methods()) {
9872       if (MI->isVirtual()) {
9873         SourceLocation MLoc = MI->getBeginLoc();
9874         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9875         return false;
9876       }
9877     }
9878 
9879     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9880   }
9881 
9882   // Looks like it's trivial!
9883   return true;
9884 }
9885 
9886 namespace {
9887 struct FindHiddenVirtualMethod {
9888   Sema *S;
9889   CXXMethodDecl *Method;
9890   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9891   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9892 
9893 private:
9894   /// Check whether any most overridden method from MD in Methods
9895   static bool CheckMostOverridenMethods(
9896       const CXXMethodDecl *MD,
9897       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9898     if (MD->size_overridden_methods() == 0)
9899       return Methods.count(MD->getCanonicalDecl());
9900     for (const CXXMethodDecl *O : MD->overridden_methods())
9901       if (CheckMostOverridenMethods(O, Methods))
9902         return true;
9903     return false;
9904   }
9905 
9906 public:
9907   /// Member lookup function that determines whether a given C++
9908   /// method overloads virtual methods in a base class without overriding any,
9909   /// to be used with CXXRecordDecl::lookupInBases().
9910   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9911     RecordDecl *BaseRecord =
9912         Specifier->getType()->castAs<RecordType>()->getDecl();
9913 
9914     DeclarationName Name = Method->getDeclName();
9915     assert(Name.getNameKind() == DeclarationName::Identifier);
9916 
9917     bool foundSameNameMethod = false;
9918     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9919     for (Path.Decls = BaseRecord->lookup(Name).begin();
9920          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9921       NamedDecl *D = *Path.Decls;
9922       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9923         MD = MD->getCanonicalDecl();
9924         foundSameNameMethod = true;
9925         // Interested only in hidden virtual methods.
9926         if (!MD->isVirtual())
9927           continue;
9928         // If the method we are checking overrides a method from its base
9929         // don't warn about the other overloaded methods. Clang deviates from
9930         // GCC by only diagnosing overloads of inherited virtual functions that
9931         // do not override any other virtual functions in the base. GCC's
9932         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9933         // function from a base class. These cases may be better served by a
9934         // warning (not specific to virtual functions) on call sites when the
9935         // call would select a different function from the base class, were it
9936         // visible.
9937         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9938         if (!S->IsOverload(Method, MD, false))
9939           return true;
9940         // Collect the overload only if its hidden.
9941         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9942           overloadedMethods.push_back(MD);
9943       }
9944     }
9945 
9946     if (foundSameNameMethod)
9947       OverloadedMethods.append(overloadedMethods.begin(),
9948                                overloadedMethods.end());
9949     return foundSameNameMethod;
9950   }
9951 };
9952 } // end anonymous namespace
9953 
9954 /// Add the most overridden methods from MD to Methods
9955 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9956                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9957   if (MD->size_overridden_methods() == 0)
9958     Methods.insert(MD->getCanonicalDecl());
9959   else
9960     for (const CXXMethodDecl *O : MD->overridden_methods())
9961       AddMostOverridenMethods(O, Methods);
9962 }
9963 
9964 /// Check if a method overloads virtual methods in a base class without
9965 /// overriding any.
9966 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9967                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9968   if (!MD->getDeclName().isIdentifier())
9969     return;
9970 
9971   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9972                      /*bool RecordPaths=*/false,
9973                      /*bool DetectVirtual=*/false);
9974   FindHiddenVirtualMethod FHVM;
9975   FHVM.Method = MD;
9976   FHVM.S = this;
9977 
9978   // Keep the base methods that were overridden or introduced in the subclass
9979   // by 'using' in a set. A base method not in this set is hidden.
9980   CXXRecordDecl *DC = MD->getParent();
9981   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9982   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9983     NamedDecl *ND = *I;
9984     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9985       ND = shad->getTargetDecl();
9986     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9987       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9988   }
9989 
9990   if (DC->lookupInBases(FHVM, Paths))
9991     OverloadedMethods = FHVM.OverloadedMethods;
9992 }
9993 
9994 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9995                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9996   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9997     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9998     PartialDiagnostic PD = PDiag(
9999          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10000     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10001     Diag(overloadedMD->getLocation(), PD);
10002   }
10003 }
10004 
10005 /// Diagnose methods which overload virtual methods in a base class
10006 /// without overriding any.
10007 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10008   if (MD->isInvalidDecl())
10009     return;
10010 
10011   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10012     return;
10013 
10014   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10015   FindHiddenVirtualMethods(MD, OverloadedMethods);
10016   if (!OverloadedMethods.empty()) {
10017     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10018       << MD << (OverloadedMethods.size() > 1);
10019 
10020     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10021   }
10022 }
10023 
10024 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10025   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10026     // No diagnostics if this is a template instantiation.
10027     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10028       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10029            diag::ext_cannot_use_trivial_abi) << &RD;
10030       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10031            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10032     }
10033     RD.dropAttr<TrivialABIAttr>();
10034   };
10035 
10036   // Ill-formed if the copy and move constructors are deleted.
10037   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10038     // If the type is dependent, then assume it might have
10039     // implicit copy or move ctor because we won't know yet at this point.
10040     if (RD.isDependentType())
10041       return true;
10042     if (RD.needsImplicitCopyConstructor() &&
10043         !RD.defaultedCopyConstructorIsDeleted())
10044       return true;
10045     if (RD.needsImplicitMoveConstructor() &&
10046         !RD.defaultedMoveConstructorIsDeleted())
10047       return true;
10048     for (const CXXConstructorDecl *CD : RD.ctors())
10049       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10050         return true;
10051     return false;
10052   };
10053 
10054   if (!HasNonDeletedCopyOrMoveConstructor()) {
10055     PrintDiagAndRemoveAttr(0);
10056     return;
10057   }
10058 
10059   // Ill-formed if the struct has virtual functions.
10060   if (RD.isPolymorphic()) {
10061     PrintDiagAndRemoveAttr(1);
10062     return;
10063   }
10064 
10065   for (const auto &B : RD.bases()) {
10066     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10067     // virtual base.
10068     if (!B.getType()->isDependentType() &&
10069         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10070       PrintDiagAndRemoveAttr(2);
10071       return;
10072     }
10073 
10074     if (B.isVirtual()) {
10075       PrintDiagAndRemoveAttr(3);
10076       return;
10077     }
10078   }
10079 
10080   for (const auto *FD : RD.fields()) {
10081     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10082     // non-trivial for the purpose of calls.
10083     QualType FT = FD->getType();
10084     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10085       PrintDiagAndRemoveAttr(4);
10086       return;
10087     }
10088 
10089     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10090       if (!RT->isDependentType() &&
10091           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10092         PrintDiagAndRemoveAttr(5);
10093         return;
10094       }
10095   }
10096 }
10097 
10098 void Sema::ActOnFinishCXXMemberSpecification(
10099     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10100     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10101   if (!TagDecl)
10102     return;
10103 
10104   AdjustDeclIfTemplate(TagDecl);
10105 
10106   for (const ParsedAttr &AL : AttrList) {
10107     if (AL.getKind() != ParsedAttr::AT_Visibility)
10108       continue;
10109     AL.setInvalid();
10110     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10111   }
10112 
10113   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10114               // strict aliasing violation!
10115               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10116               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10117 
10118   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10119 }
10120 
10121 /// Find the equality comparison functions that should be implicitly declared
10122 /// in a given class definition, per C++2a [class.compare.default]p3.
10123 static void findImplicitlyDeclaredEqualityComparisons(
10124     ASTContext &Ctx, CXXRecordDecl *RD,
10125     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10126   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10127   if (!RD->lookup(EqEq).empty())
10128     // Member operator== explicitly declared: no implicit operator==s.
10129     return;
10130 
10131   // Traverse friends looking for an '==' or a '<=>'.
10132   for (FriendDecl *Friend : RD->friends()) {
10133     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10134     if (!FD) continue;
10135 
10136     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10137       // Friend operator== explicitly declared: no implicit operator==s.
10138       Spaceships.clear();
10139       return;
10140     }
10141 
10142     if (FD->getOverloadedOperator() == OO_Spaceship &&
10143         FD->isExplicitlyDefaulted())
10144       Spaceships.push_back(FD);
10145   }
10146 
10147   // Look for members named 'operator<=>'.
10148   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10149   for (NamedDecl *ND : RD->lookup(Cmp)) {
10150     // Note that we could find a non-function here (either a function template
10151     // or a using-declaration). Neither case results in an implicit
10152     // 'operator=='.
10153     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10154       if (FD->isExplicitlyDefaulted())
10155         Spaceships.push_back(FD);
10156   }
10157 }
10158 
10159 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10160 /// special functions, such as the default constructor, copy
10161 /// constructor, or destructor, to the given C++ class (C++
10162 /// [special]p1).  This routine can only be executed just before the
10163 /// definition of the class is complete.
10164 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10165   // Don't add implicit special members to templated classes.
10166   // FIXME: This means unqualified lookups for 'operator=' within a class
10167   // template don't work properly.
10168   if (!ClassDecl->isDependentType()) {
10169     if (ClassDecl->needsImplicitDefaultConstructor()) {
10170       ++getASTContext().NumImplicitDefaultConstructors;
10171 
10172       if (ClassDecl->hasInheritedConstructor())
10173         DeclareImplicitDefaultConstructor(ClassDecl);
10174     }
10175 
10176     if (ClassDecl->needsImplicitCopyConstructor()) {
10177       ++getASTContext().NumImplicitCopyConstructors;
10178 
10179       // If the properties or semantics of the copy constructor couldn't be
10180       // determined while the class was being declared, force a declaration
10181       // of it now.
10182       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10183           ClassDecl->hasInheritedConstructor())
10184         DeclareImplicitCopyConstructor(ClassDecl);
10185       // For the MS ABI we need to know whether the copy ctor is deleted. A
10186       // prerequisite for deleting the implicit copy ctor is that the class has
10187       // a move ctor or move assignment that is either user-declared or whose
10188       // semantics are inherited from a subobject. FIXME: We should provide a
10189       // more direct way for CodeGen to ask whether the constructor was deleted.
10190       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10191                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10192                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10193                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10194                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10195         DeclareImplicitCopyConstructor(ClassDecl);
10196     }
10197 
10198     if (getLangOpts().CPlusPlus11 &&
10199         ClassDecl->needsImplicitMoveConstructor()) {
10200       ++getASTContext().NumImplicitMoveConstructors;
10201 
10202       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10203           ClassDecl->hasInheritedConstructor())
10204         DeclareImplicitMoveConstructor(ClassDecl);
10205     }
10206 
10207     if (ClassDecl->needsImplicitCopyAssignment()) {
10208       ++getASTContext().NumImplicitCopyAssignmentOperators;
10209 
10210       // If we have a dynamic class, then the copy assignment operator may be
10211       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10212       // it shows up in the right place in the vtable and that we diagnose
10213       // problems with the implicit exception specification.
10214       if (ClassDecl->isDynamicClass() ||
10215           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10216           ClassDecl->hasInheritedAssignment())
10217         DeclareImplicitCopyAssignment(ClassDecl);
10218     }
10219 
10220     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10221       ++getASTContext().NumImplicitMoveAssignmentOperators;
10222 
10223       // Likewise for the move assignment operator.
10224       if (ClassDecl->isDynamicClass() ||
10225           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10226           ClassDecl->hasInheritedAssignment())
10227         DeclareImplicitMoveAssignment(ClassDecl);
10228     }
10229 
10230     if (ClassDecl->needsImplicitDestructor()) {
10231       ++getASTContext().NumImplicitDestructors;
10232 
10233       // If we have a dynamic class, then the destructor may be virtual, so we
10234       // have to declare the destructor immediately. This ensures that, e.g., it
10235       // shows up in the right place in the vtable and that we diagnose problems
10236       // with the implicit exception specification.
10237       if (ClassDecl->isDynamicClass() ||
10238           ClassDecl->needsOverloadResolutionForDestructor())
10239         DeclareImplicitDestructor(ClassDecl);
10240     }
10241   }
10242 
10243   // C++2a [class.compare.default]p3:
10244   //   If the member-specification does not explicitly declare any member or
10245   //   friend named operator==, an == operator function is declared implicitly
10246   //   for each defaulted three-way comparison operator function defined in
10247   //   the member-specification
10248   // FIXME: Consider doing this lazily.
10249   // We do this during the initial parse for a class template, not during
10250   // instantiation, so that we can handle unqualified lookups for 'operator=='
10251   // when parsing the template.
10252   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10253     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10254     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10255                                               DefaultedSpaceships);
10256     for (auto *FD : DefaultedSpaceships)
10257       DeclareImplicitEqualityComparison(ClassDecl, FD);
10258   }
10259 }
10260 
10261 unsigned
10262 Sema::ActOnReenterTemplateScope(Decl *D,
10263                                 llvm::function_ref<Scope *()> EnterScope) {
10264   if (!D)
10265     return 0;
10266   AdjustDeclIfTemplate(D);
10267 
10268   // In order to get name lookup right, reenter template scopes in order from
10269   // outermost to innermost.
10270   SmallVector<TemplateParameterList *, 4> ParameterLists;
10271   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10272 
10273   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10274     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10275       ParameterLists.push_back(DD->getTemplateParameterList(i));
10276 
10277     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10278       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10279         ParameterLists.push_back(FTD->getTemplateParameters());
10280     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10281       LookupDC = VD->getDeclContext();
10282 
10283       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10284         ParameterLists.push_back(VTD->getTemplateParameters());
10285       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10286         ParameterLists.push_back(PSD->getTemplateParameters());
10287     }
10288   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10289     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10290       ParameterLists.push_back(TD->getTemplateParameterList(i));
10291 
10292     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10293       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10294         ParameterLists.push_back(CTD->getTemplateParameters());
10295       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10296         ParameterLists.push_back(PSD->getTemplateParameters());
10297     }
10298   }
10299   // FIXME: Alias declarations and concepts.
10300 
10301   unsigned Count = 0;
10302   Scope *InnermostTemplateScope = nullptr;
10303   for (TemplateParameterList *Params : ParameterLists) {
10304     // Ignore explicit specializations; they don't contribute to the template
10305     // depth.
10306     if (Params->size() == 0)
10307       continue;
10308 
10309     InnermostTemplateScope = EnterScope();
10310     for (NamedDecl *Param : *Params) {
10311       if (Param->getDeclName()) {
10312         InnermostTemplateScope->AddDecl(Param);
10313         IdResolver.AddDecl(Param);
10314       }
10315     }
10316     ++Count;
10317   }
10318 
10319   // Associate the new template scopes with the corresponding entities.
10320   if (InnermostTemplateScope) {
10321     assert(LookupDC && "no enclosing DeclContext for template lookup");
10322     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10323   }
10324 
10325   return Count;
10326 }
10327 
10328 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10329   if (!RecordD) return;
10330   AdjustDeclIfTemplate(RecordD);
10331   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10332   PushDeclContext(S, Record);
10333 }
10334 
10335 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10336   if (!RecordD) return;
10337   PopDeclContext();
10338 }
10339 
10340 /// This is used to implement the constant expression evaluation part of the
10341 /// attribute enable_if extension. There is nothing in standard C++ which would
10342 /// require reentering parameters.
10343 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10344   if (!Param)
10345     return;
10346 
10347   S->AddDecl(Param);
10348   if (Param->getDeclName())
10349     IdResolver.AddDecl(Param);
10350 }
10351 
10352 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10353 /// parsing a top-level (non-nested) C++ class, and we are now
10354 /// parsing those parts of the given Method declaration that could
10355 /// not be parsed earlier (C++ [class.mem]p2), such as default
10356 /// arguments. This action should enter the scope of the given
10357 /// Method declaration as if we had just parsed the qualified method
10358 /// name. However, it should not bring the parameters into scope;
10359 /// that will be performed by ActOnDelayedCXXMethodParameter.
10360 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10361 }
10362 
10363 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10364 /// C++ method declaration. We're (re-)introducing the given
10365 /// function parameter into scope for use in parsing later parts of
10366 /// the method declaration. For example, we could see an
10367 /// ActOnParamDefaultArgument event for this parameter.
10368 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10369   if (!ParamD)
10370     return;
10371 
10372   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10373 
10374   S->AddDecl(Param);
10375   if (Param->getDeclName())
10376     IdResolver.AddDecl(Param);
10377 }
10378 
10379 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10380 /// processing the delayed method declaration for Method. The method
10381 /// declaration is now considered finished. There may be a separate
10382 /// ActOnStartOfFunctionDef action later (not necessarily
10383 /// immediately!) for this method, if it was also defined inside the
10384 /// class body.
10385 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10386   if (!MethodD)
10387     return;
10388 
10389   AdjustDeclIfTemplate(MethodD);
10390 
10391   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10392 
10393   // Now that we have our default arguments, check the constructor
10394   // again. It could produce additional diagnostics or affect whether
10395   // the class has implicitly-declared destructors, among other
10396   // things.
10397   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10398     CheckConstructor(Constructor);
10399 
10400   // Check the default arguments, which we may have added.
10401   if (!Method->isInvalidDecl())
10402     CheckCXXDefaultArguments(Method);
10403 }
10404 
10405 // Emit the given diagnostic for each non-address-space qualifier.
10406 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10407 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10408   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10409   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10410     bool DiagOccured = false;
10411     FTI.MethodQualifiers->forEachQualifier(
10412         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10413                                    SourceLocation SL) {
10414           // This diagnostic should be emitted on any qualifier except an addr
10415           // space qualifier. However, forEachQualifier currently doesn't visit
10416           // addr space qualifiers, so there's no way to write this condition
10417           // right now; we just diagnose on everything.
10418           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10419           DiagOccured = true;
10420         });
10421     if (DiagOccured)
10422       D.setInvalidType();
10423   }
10424 }
10425 
10426 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10427 /// the well-formedness of the constructor declarator @p D with type @p
10428 /// R. If there are any errors in the declarator, this routine will
10429 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10430 /// will be updated to reflect a well-formed type for the constructor and
10431 /// returned.
10432 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10433                                           StorageClass &SC) {
10434   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10435 
10436   // C++ [class.ctor]p3:
10437   //   A constructor shall not be virtual (10.3) or static (9.4). A
10438   //   constructor can be invoked for a const, volatile or const
10439   //   volatile object. A constructor shall not be declared const,
10440   //   volatile, or const volatile (9.3.2).
10441   if (isVirtual) {
10442     if (!D.isInvalidType())
10443       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10444         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10445         << SourceRange(D.getIdentifierLoc());
10446     D.setInvalidType();
10447   }
10448   if (SC == SC_Static) {
10449     if (!D.isInvalidType())
10450       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10451         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10452         << SourceRange(D.getIdentifierLoc());
10453     D.setInvalidType();
10454     SC = SC_None;
10455   }
10456 
10457   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10458     diagnoseIgnoredQualifiers(
10459         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10460         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10461         D.getDeclSpec().getRestrictSpecLoc(),
10462         D.getDeclSpec().getAtomicSpecLoc());
10463     D.setInvalidType();
10464   }
10465 
10466   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10467 
10468   // C++0x [class.ctor]p4:
10469   //   A constructor shall not be declared with a ref-qualifier.
10470   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10471   if (FTI.hasRefQualifier()) {
10472     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10473       << FTI.RefQualifierIsLValueRef
10474       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10475     D.setInvalidType();
10476   }
10477 
10478   // Rebuild the function type "R" without any type qualifiers (in
10479   // case any of the errors above fired) and with "void" as the
10480   // return type, since constructors don't have return types.
10481   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10482   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10483     return R;
10484 
10485   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10486   EPI.TypeQuals = Qualifiers();
10487   EPI.RefQualifier = RQ_None;
10488 
10489   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10490 }
10491 
10492 /// CheckConstructor - Checks a fully-formed constructor for
10493 /// well-formedness, issuing any diagnostics required. Returns true if
10494 /// the constructor declarator is invalid.
10495 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10496   CXXRecordDecl *ClassDecl
10497     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10498   if (!ClassDecl)
10499     return Constructor->setInvalidDecl();
10500 
10501   // C++ [class.copy]p3:
10502   //   A declaration of a constructor for a class X is ill-formed if
10503   //   its first parameter is of type (optionally cv-qualified) X and
10504   //   either there are no other parameters or else all other
10505   //   parameters have default arguments.
10506   if (!Constructor->isInvalidDecl() &&
10507       Constructor->hasOneParamOrDefaultArgs() &&
10508       Constructor->getTemplateSpecializationKind() !=
10509           TSK_ImplicitInstantiation) {
10510     QualType ParamType = Constructor->getParamDecl(0)->getType();
10511     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10512     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10513       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10514       const char *ConstRef
10515         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10516                                                         : " const &";
10517       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10518         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10519 
10520       // FIXME: Rather that making the constructor invalid, we should endeavor
10521       // to fix the type.
10522       Constructor->setInvalidDecl();
10523     }
10524   }
10525 }
10526 
10527 /// CheckDestructor - Checks a fully-formed destructor definition for
10528 /// well-formedness, issuing any diagnostics required.  Returns true
10529 /// on error.
10530 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10531   CXXRecordDecl *RD = Destructor->getParent();
10532 
10533   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10534     SourceLocation Loc;
10535 
10536     if (!Destructor->isImplicit())
10537       Loc = Destructor->getLocation();
10538     else
10539       Loc = RD->getLocation();
10540 
10541     // If we have a virtual destructor, look up the deallocation function
10542     if (FunctionDecl *OperatorDelete =
10543             FindDeallocationFunctionForDestructor(Loc, RD)) {
10544       Expr *ThisArg = nullptr;
10545 
10546       // If the notional 'delete this' expression requires a non-trivial
10547       // conversion from 'this' to the type of a destroying operator delete's
10548       // first parameter, perform that conversion now.
10549       if (OperatorDelete->isDestroyingOperatorDelete()) {
10550         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10551         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10552           // C++ [class.dtor]p13:
10553           //   ... as if for the expression 'delete this' appearing in a
10554           //   non-virtual destructor of the destructor's class.
10555           ContextRAII SwitchContext(*this, Destructor);
10556           ExprResult This =
10557               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10558           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10559           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10560           if (This.isInvalid()) {
10561             // FIXME: Register this as a context note so that it comes out
10562             // in the right order.
10563             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10564             return true;
10565           }
10566           ThisArg = This.get();
10567         }
10568       }
10569 
10570       DiagnoseUseOfDecl(OperatorDelete, Loc);
10571       MarkFunctionReferenced(Loc, OperatorDelete);
10572       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10573     }
10574   }
10575 
10576   return false;
10577 }
10578 
10579 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10580 /// the well-formednes of the destructor declarator @p D with type @p
10581 /// R. If there are any errors in the declarator, this routine will
10582 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10583 /// will be updated to reflect a well-formed type for the destructor and
10584 /// returned.
10585 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10586                                          StorageClass& SC) {
10587   // C++ [class.dtor]p1:
10588   //   [...] A typedef-name that names a class is a class-name
10589   //   (7.1.3); however, a typedef-name that names a class shall not
10590   //   be used as the identifier in the declarator for a destructor
10591   //   declaration.
10592   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10593   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10594     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10595       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10596   else if (const TemplateSpecializationType *TST =
10597              DeclaratorType->getAs<TemplateSpecializationType>())
10598     if (TST->isTypeAlias())
10599       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10600         << DeclaratorType << 1;
10601 
10602   // C++ [class.dtor]p2:
10603   //   A destructor is used to destroy objects of its class type. A
10604   //   destructor takes no parameters, and no return type can be
10605   //   specified for it (not even void). The address of a destructor
10606   //   shall not be taken. A destructor shall not be static. A
10607   //   destructor can be invoked for a const, volatile or const
10608   //   volatile object. A destructor shall not be declared const,
10609   //   volatile or const volatile (9.3.2).
10610   if (SC == SC_Static) {
10611     if (!D.isInvalidType())
10612       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10613         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10614         << SourceRange(D.getIdentifierLoc())
10615         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10616 
10617     SC = SC_None;
10618   }
10619   if (!D.isInvalidType()) {
10620     // Destructors don't have return types, but the parser will
10621     // happily parse something like:
10622     //
10623     //   class X {
10624     //     float ~X();
10625     //   };
10626     //
10627     // The return type will be eliminated later.
10628     if (D.getDeclSpec().hasTypeSpecifier())
10629       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10630         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10631         << SourceRange(D.getIdentifierLoc());
10632     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10633       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10634                                 SourceLocation(),
10635                                 D.getDeclSpec().getConstSpecLoc(),
10636                                 D.getDeclSpec().getVolatileSpecLoc(),
10637                                 D.getDeclSpec().getRestrictSpecLoc(),
10638                                 D.getDeclSpec().getAtomicSpecLoc());
10639       D.setInvalidType();
10640     }
10641   }
10642 
10643   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10644 
10645   // C++0x [class.dtor]p2:
10646   //   A destructor shall not be declared with a ref-qualifier.
10647   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10648   if (FTI.hasRefQualifier()) {
10649     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10650       << FTI.RefQualifierIsLValueRef
10651       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10652     D.setInvalidType();
10653   }
10654 
10655   // Make sure we don't have any parameters.
10656   if (FTIHasNonVoidParameters(FTI)) {
10657     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10658 
10659     // Delete the parameters.
10660     FTI.freeParams();
10661     D.setInvalidType();
10662   }
10663 
10664   // Make sure the destructor isn't variadic.
10665   if (FTI.isVariadic) {
10666     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10667     D.setInvalidType();
10668   }
10669 
10670   // Rebuild the function type "R" without any type qualifiers or
10671   // parameters (in case any of the errors above fired) and with
10672   // "void" as the return type, since destructors don't have return
10673   // types.
10674   if (!D.isInvalidType())
10675     return R;
10676 
10677   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10678   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10679   EPI.Variadic = false;
10680   EPI.TypeQuals = Qualifiers();
10681   EPI.RefQualifier = RQ_None;
10682   return Context.getFunctionType(Context.VoidTy, None, EPI);
10683 }
10684 
10685 static void extendLeft(SourceRange &R, SourceRange Before) {
10686   if (Before.isInvalid())
10687     return;
10688   R.setBegin(Before.getBegin());
10689   if (R.getEnd().isInvalid())
10690     R.setEnd(Before.getEnd());
10691 }
10692 
10693 static void extendRight(SourceRange &R, SourceRange After) {
10694   if (After.isInvalid())
10695     return;
10696   if (R.getBegin().isInvalid())
10697     R.setBegin(After.getBegin());
10698   R.setEnd(After.getEnd());
10699 }
10700 
10701 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10702 /// well-formednes of the conversion function declarator @p D with
10703 /// type @p R. If there are any errors in the declarator, this routine
10704 /// will emit diagnostics and return true. Otherwise, it will return
10705 /// false. Either way, the type @p R will be updated to reflect a
10706 /// well-formed type for the conversion operator.
10707 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10708                                      StorageClass& SC) {
10709   // C++ [class.conv.fct]p1:
10710   //   Neither parameter types nor return type can be specified. The
10711   //   type of a conversion function (8.3.5) is "function taking no
10712   //   parameter returning conversion-type-id."
10713   if (SC == SC_Static) {
10714     if (!D.isInvalidType())
10715       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10716         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10717         << D.getName().getSourceRange();
10718     D.setInvalidType();
10719     SC = SC_None;
10720   }
10721 
10722   TypeSourceInfo *ConvTSI = nullptr;
10723   QualType ConvType =
10724       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10725 
10726   const DeclSpec &DS = D.getDeclSpec();
10727   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10728     // Conversion functions don't have return types, but the parser will
10729     // happily parse something like:
10730     //
10731     //   class X {
10732     //     float operator bool();
10733     //   };
10734     //
10735     // The return type will be changed later anyway.
10736     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10737       << SourceRange(DS.getTypeSpecTypeLoc())
10738       << SourceRange(D.getIdentifierLoc());
10739     D.setInvalidType();
10740   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10741     // It's also plausible that the user writes type qualifiers in the wrong
10742     // place, such as:
10743     //   struct S { const operator int(); };
10744     // FIXME: we could provide a fixit to move the qualifiers onto the
10745     // conversion type.
10746     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10747         << SourceRange(D.getIdentifierLoc()) << 0;
10748     D.setInvalidType();
10749   }
10750 
10751   const auto *Proto = R->castAs<FunctionProtoType>();
10752 
10753   // Make sure we don't have any parameters.
10754   if (Proto->getNumParams() > 0) {
10755     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10756 
10757     // Delete the parameters.
10758     D.getFunctionTypeInfo().freeParams();
10759     D.setInvalidType();
10760   } else if (Proto->isVariadic()) {
10761     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10762     D.setInvalidType();
10763   }
10764 
10765   // Diagnose "&operator bool()" and other such nonsense.  This
10766   // is actually a gcc extension which we don't support.
10767   if (Proto->getReturnType() != ConvType) {
10768     bool NeedsTypedef = false;
10769     SourceRange Before, After;
10770 
10771     // Walk the chunks and extract information on them for our diagnostic.
10772     bool PastFunctionChunk = false;
10773     for (auto &Chunk : D.type_objects()) {
10774       switch (Chunk.Kind) {
10775       case DeclaratorChunk::Function:
10776         if (!PastFunctionChunk) {
10777           if (Chunk.Fun.HasTrailingReturnType) {
10778             TypeSourceInfo *TRT = nullptr;
10779             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10780             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10781           }
10782           PastFunctionChunk = true;
10783           break;
10784         }
10785         LLVM_FALLTHROUGH;
10786       case DeclaratorChunk::Array:
10787         NeedsTypedef = true;
10788         extendRight(After, Chunk.getSourceRange());
10789         break;
10790 
10791       case DeclaratorChunk::Pointer:
10792       case DeclaratorChunk::BlockPointer:
10793       case DeclaratorChunk::Reference:
10794       case DeclaratorChunk::MemberPointer:
10795       case DeclaratorChunk::Pipe:
10796         extendLeft(Before, Chunk.getSourceRange());
10797         break;
10798 
10799       case DeclaratorChunk::Paren:
10800         extendLeft(Before, Chunk.Loc);
10801         extendRight(After, Chunk.EndLoc);
10802         break;
10803       }
10804     }
10805 
10806     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10807                          After.isValid()  ? After.getBegin() :
10808                                             D.getIdentifierLoc();
10809     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10810     DB << Before << After;
10811 
10812     if (!NeedsTypedef) {
10813       DB << /*don't need a typedef*/0;
10814 
10815       // If we can provide a correct fix-it hint, do so.
10816       if (After.isInvalid() && ConvTSI) {
10817         SourceLocation InsertLoc =
10818             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10819         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10820            << FixItHint::CreateInsertionFromRange(
10821                   InsertLoc, CharSourceRange::getTokenRange(Before))
10822            << FixItHint::CreateRemoval(Before);
10823       }
10824     } else if (!Proto->getReturnType()->isDependentType()) {
10825       DB << /*typedef*/1 << Proto->getReturnType();
10826     } else if (getLangOpts().CPlusPlus11) {
10827       DB << /*alias template*/2 << Proto->getReturnType();
10828     } else {
10829       DB << /*might not be fixable*/3;
10830     }
10831 
10832     // Recover by incorporating the other type chunks into the result type.
10833     // Note, this does *not* change the name of the function. This is compatible
10834     // with the GCC extension:
10835     //   struct S { &operator int(); } s;
10836     //   int &r = s.operator int(); // ok in GCC
10837     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10838     ConvType = Proto->getReturnType();
10839   }
10840 
10841   // C++ [class.conv.fct]p4:
10842   //   The conversion-type-id shall not represent a function type nor
10843   //   an array type.
10844   if (ConvType->isArrayType()) {
10845     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10846     ConvType = Context.getPointerType(ConvType);
10847     D.setInvalidType();
10848   } else if (ConvType->isFunctionType()) {
10849     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10850     ConvType = Context.getPointerType(ConvType);
10851     D.setInvalidType();
10852   }
10853 
10854   // Rebuild the function type "R" without any parameters (in case any
10855   // of the errors above fired) and with the conversion type as the
10856   // return type.
10857   if (D.isInvalidType())
10858     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10859 
10860   // C++0x explicit conversion operators.
10861   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10862     Diag(DS.getExplicitSpecLoc(),
10863          getLangOpts().CPlusPlus11
10864              ? diag::warn_cxx98_compat_explicit_conversion_functions
10865              : diag::ext_explicit_conversion_functions)
10866         << SourceRange(DS.getExplicitSpecRange());
10867 }
10868 
10869 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10870 /// the declaration of the given C++ conversion function. This routine
10871 /// is responsible for recording the conversion function in the C++
10872 /// class, if possible.
10873 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10874   assert(Conversion && "Expected to receive a conversion function declaration");
10875 
10876   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10877 
10878   // Make sure we aren't redeclaring the conversion function.
10879   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10880   // C++ [class.conv.fct]p1:
10881   //   [...] A conversion function is never used to convert a
10882   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10883   //   same object type (or a reference to it), to a (possibly
10884   //   cv-qualified) base class of that type (or a reference to it),
10885   //   or to (possibly cv-qualified) void.
10886   QualType ClassType
10887     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10888   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10889     ConvType = ConvTypeRef->getPointeeType();
10890   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10891       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10892     /* Suppress diagnostics for instantiations. */;
10893   else if (Conversion->size_overridden_methods() != 0)
10894     /* Suppress diagnostics for overriding virtual function in a base class. */;
10895   else if (ConvType->isRecordType()) {
10896     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10897     if (ConvType == ClassType)
10898       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10899         << ClassType;
10900     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10901       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10902         <<  ClassType << ConvType;
10903   } else if (ConvType->isVoidType()) {
10904     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10905       << ClassType << ConvType;
10906   }
10907 
10908   if (FunctionTemplateDecl *ConversionTemplate
10909                                 = Conversion->getDescribedFunctionTemplate())
10910     return ConversionTemplate;
10911 
10912   return Conversion;
10913 }
10914 
10915 namespace {
10916 /// Utility class to accumulate and print a diagnostic listing the invalid
10917 /// specifier(s) on a declaration.
10918 struct BadSpecifierDiagnoser {
10919   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10920       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10921   ~BadSpecifierDiagnoser() {
10922     Diagnostic << Specifiers;
10923   }
10924 
10925   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10926     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10927   }
10928   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10929     return check(SpecLoc,
10930                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10931   }
10932   void check(SourceLocation SpecLoc, const char *Spec) {
10933     if (SpecLoc.isInvalid()) return;
10934     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10935     if (!Specifiers.empty()) Specifiers += " ";
10936     Specifiers += Spec;
10937   }
10938 
10939   Sema &S;
10940   Sema::SemaDiagnosticBuilder Diagnostic;
10941   std::string Specifiers;
10942 };
10943 }
10944 
10945 /// Check the validity of a declarator that we parsed for a deduction-guide.
10946 /// These aren't actually declarators in the grammar, so we need to check that
10947 /// the user didn't specify any pieces that are not part of the deduction-guide
10948 /// grammar.
10949 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10950                                          StorageClass &SC) {
10951   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10952   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10953   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10954 
10955   // C++ [temp.deduct.guide]p3:
10956   //   A deduction-gide shall be declared in the same scope as the
10957   //   corresponding class template.
10958   if (!CurContext->getRedeclContext()->Equals(
10959           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10960     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10961       << GuidedTemplateDecl;
10962     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10963   }
10964 
10965   auto &DS = D.getMutableDeclSpec();
10966   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10967   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10968       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10969       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10970     BadSpecifierDiagnoser Diagnoser(
10971         *this, D.getIdentifierLoc(),
10972         diag::err_deduction_guide_invalid_specifier);
10973 
10974     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10975     DS.ClearStorageClassSpecs();
10976     SC = SC_None;
10977 
10978     // 'explicit' is permitted.
10979     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10980     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10981     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10982     DS.ClearConstexprSpec();
10983 
10984     Diagnoser.check(DS.getConstSpecLoc(), "const");
10985     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10986     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10987     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10988     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10989     DS.ClearTypeQualifiers();
10990 
10991     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10992     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10993     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10994     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10995     DS.ClearTypeSpecType();
10996   }
10997 
10998   if (D.isInvalidType())
10999     return;
11000 
11001   // Check the declarator is simple enough.
11002   bool FoundFunction = false;
11003   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11004     if (Chunk.Kind == DeclaratorChunk::Paren)
11005       continue;
11006     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11007       Diag(D.getDeclSpec().getBeginLoc(),
11008            diag::err_deduction_guide_with_complex_decl)
11009           << D.getSourceRange();
11010       break;
11011     }
11012     if (!Chunk.Fun.hasTrailingReturnType()) {
11013       Diag(D.getName().getBeginLoc(),
11014            diag::err_deduction_guide_no_trailing_return_type);
11015       break;
11016     }
11017 
11018     // Check that the return type is written as a specialization of
11019     // the template specified as the deduction-guide's name.
11020     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11021     TypeSourceInfo *TSI = nullptr;
11022     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11023     assert(TSI && "deduction guide has valid type but invalid return type?");
11024     bool AcceptableReturnType = false;
11025     bool MightInstantiateToSpecialization = false;
11026     if (auto RetTST =
11027             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
11028       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11029       bool TemplateMatches =
11030           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11031       // FIXME: We should consider other template kinds (using, qualified),
11032       // otherwise we will emit bogus diagnostics.
11033       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11034         AcceptableReturnType = true;
11035       else {
11036         // This could still instantiate to the right type, unless we know it
11037         // names the wrong class template.
11038         auto *TD = SpecifiedName.getAsTemplateDecl();
11039         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11040                                              !TemplateMatches);
11041       }
11042     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11043       MightInstantiateToSpecialization = true;
11044     }
11045 
11046     if (!AcceptableReturnType) {
11047       Diag(TSI->getTypeLoc().getBeginLoc(),
11048            diag::err_deduction_guide_bad_trailing_return_type)
11049           << GuidedTemplate << TSI->getType()
11050           << MightInstantiateToSpecialization
11051           << TSI->getTypeLoc().getSourceRange();
11052     }
11053 
11054     // Keep going to check that we don't have any inner declarator pieces (we
11055     // could still have a function returning a pointer to a function).
11056     FoundFunction = true;
11057   }
11058 
11059   if (D.isFunctionDefinition())
11060     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11061 }
11062 
11063 //===----------------------------------------------------------------------===//
11064 // Namespace Handling
11065 //===----------------------------------------------------------------------===//
11066 
11067 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11068 /// reopened.
11069 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11070                                             SourceLocation Loc,
11071                                             IdentifierInfo *II, bool *IsInline,
11072                                             NamespaceDecl *PrevNS) {
11073   assert(*IsInline != PrevNS->isInline());
11074 
11075   // 'inline' must appear on the original definition, but not necessarily
11076   // on all extension definitions, so the note should point to the first
11077   // definition to avoid confusion.
11078   PrevNS = PrevNS->getFirstDecl();
11079 
11080   if (PrevNS->isInline())
11081     // The user probably just forgot the 'inline', so suggest that it
11082     // be added back.
11083     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11084       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11085   else
11086     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11087 
11088   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11089   *IsInline = PrevNS->isInline();
11090 }
11091 
11092 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11093 /// definition.
11094 Decl *Sema::ActOnStartNamespaceDef(
11095     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11096     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11097     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11098   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11099   // For anonymous namespace, take the location of the left brace.
11100   SourceLocation Loc = II ? IdentLoc : LBrace;
11101   bool IsInline = InlineLoc.isValid();
11102   bool IsInvalid = false;
11103   bool IsStd = false;
11104   bool AddToKnown = false;
11105   Scope *DeclRegionScope = NamespcScope->getParent();
11106 
11107   NamespaceDecl *PrevNS = nullptr;
11108   if (II) {
11109     // C++ [namespace.def]p2:
11110     //   The identifier in an original-namespace-definition shall not
11111     //   have been previously defined in the declarative region in
11112     //   which the original-namespace-definition appears. The
11113     //   identifier in an original-namespace-definition is the name of
11114     //   the namespace. Subsequently in that declarative region, it is
11115     //   treated as an original-namespace-name.
11116     //
11117     // Since namespace names are unique in their scope, and we don't
11118     // look through using directives, just look for any ordinary names
11119     // as if by qualified name lookup.
11120     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11121                    ForExternalRedeclaration);
11122     LookupQualifiedName(R, CurContext->getRedeclContext());
11123     NamedDecl *PrevDecl =
11124         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11125     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11126 
11127     if (PrevNS) {
11128       // This is an extended namespace definition.
11129       if (IsInline != PrevNS->isInline())
11130         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11131                                         &IsInline, PrevNS);
11132     } else if (PrevDecl) {
11133       // This is an invalid name redefinition.
11134       Diag(Loc, diag::err_redefinition_different_kind)
11135         << II;
11136       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11137       IsInvalid = true;
11138       // Continue on to push Namespc as current DeclContext and return it.
11139     } else if (II->isStr("std") &&
11140                CurContext->getRedeclContext()->isTranslationUnit()) {
11141       // This is the first "real" definition of the namespace "std", so update
11142       // our cache of the "std" namespace to point at this definition.
11143       PrevNS = getStdNamespace();
11144       IsStd = true;
11145       AddToKnown = !IsInline;
11146     } else {
11147       // We've seen this namespace for the first time.
11148       AddToKnown = !IsInline;
11149     }
11150   } else {
11151     // Anonymous namespaces.
11152 
11153     // Determine whether the parent already has an anonymous namespace.
11154     DeclContext *Parent = CurContext->getRedeclContext();
11155     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11156       PrevNS = TU->getAnonymousNamespace();
11157     } else {
11158       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11159       PrevNS = ND->getAnonymousNamespace();
11160     }
11161 
11162     if (PrevNS && IsInline != PrevNS->isInline())
11163       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11164                                       &IsInline, PrevNS);
11165   }
11166 
11167   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11168                                                  StartLoc, Loc, II, PrevNS);
11169   if (IsInvalid)
11170     Namespc->setInvalidDecl();
11171 
11172   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11173   AddPragmaAttributes(DeclRegionScope, Namespc);
11174 
11175   // FIXME: Should we be merging attributes?
11176   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11177     PushNamespaceVisibilityAttr(Attr, Loc);
11178 
11179   if (IsStd)
11180     StdNamespace = Namespc;
11181   if (AddToKnown)
11182     KnownNamespaces[Namespc] = false;
11183 
11184   if (II) {
11185     PushOnScopeChains(Namespc, DeclRegionScope);
11186   } else {
11187     // Link the anonymous namespace into its parent.
11188     DeclContext *Parent = CurContext->getRedeclContext();
11189     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11190       TU->setAnonymousNamespace(Namespc);
11191     } else {
11192       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11193     }
11194 
11195     CurContext->addDecl(Namespc);
11196 
11197     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11198     //   behaves as if it were replaced by
11199     //     namespace unique { /* empty body */ }
11200     //     using namespace unique;
11201     //     namespace unique { namespace-body }
11202     //   where all occurrences of 'unique' in a translation unit are
11203     //   replaced by the same identifier and this identifier differs
11204     //   from all other identifiers in the entire program.
11205 
11206     // We just create the namespace with an empty name and then add an
11207     // implicit using declaration, just like the standard suggests.
11208     //
11209     // CodeGen enforces the "universally unique" aspect by giving all
11210     // declarations semantically contained within an anonymous
11211     // namespace internal linkage.
11212 
11213     if (!PrevNS) {
11214       UD = UsingDirectiveDecl::Create(Context, Parent,
11215                                       /* 'using' */ LBrace,
11216                                       /* 'namespace' */ SourceLocation(),
11217                                       /* qualifier */ NestedNameSpecifierLoc(),
11218                                       /* identifier */ SourceLocation(),
11219                                       Namespc,
11220                                       /* Ancestor */ Parent);
11221       UD->setImplicit();
11222       Parent->addDecl(UD);
11223     }
11224   }
11225 
11226   ActOnDocumentableDecl(Namespc);
11227 
11228   // Although we could have an invalid decl (i.e. the namespace name is a
11229   // redefinition), push it as current DeclContext and try to continue parsing.
11230   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11231   // for the namespace has the declarations that showed up in that particular
11232   // namespace definition.
11233   PushDeclContext(NamespcScope, Namespc);
11234   return Namespc;
11235 }
11236 
11237 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11238 /// is a namespace alias, returns the namespace it points to.
11239 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11240   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11241     return AD->getNamespace();
11242   return dyn_cast_or_null<NamespaceDecl>(D);
11243 }
11244 
11245 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11246 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11247 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11248   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11249   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11250   Namespc->setRBraceLoc(RBrace);
11251   PopDeclContext();
11252   if (Namespc->hasAttr<VisibilityAttr>())
11253     PopPragmaVisibility(true, RBrace);
11254   // If this namespace contains an export-declaration, export it now.
11255   if (DeferredExportedNamespaces.erase(Namespc))
11256     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11257 }
11258 
11259 CXXRecordDecl *Sema::getStdBadAlloc() const {
11260   return cast_or_null<CXXRecordDecl>(
11261                                   StdBadAlloc.get(Context.getExternalSource()));
11262 }
11263 
11264 EnumDecl *Sema::getStdAlignValT() const {
11265   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11266 }
11267 
11268 NamespaceDecl *Sema::getStdNamespace() const {
11269   return cast_or_null<NamespaceDecl>(
11270                                  StdNamespace.get(Context.getExternalSource()));
11271 }
11272 
11273 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11274   if (!StdExperimentalNamespaceCache) {
11275     if (auto Std = getStdNamespace()) {
11276       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11277                           SourceLocation(), LookupNamespaceName);
11278       if (!LookupQualifiedName(Result, Std) ||
11279           !(StdExperimentalNamespaceCache =
11280                 Result.getAsSingle<NamespaceDecl>()))
11281         Result.suppressDiagnostics();
11282     }
11283   }
11284   return StdExperimentalNamespaceCache;
11285 }
11286 
11287 namespace {
11288 
11289 enum UnsupportedSTLSelect {
11290   USS_InvalidMember,
11291   USS_MissingMember,
11292   USS_NonTrivial,
11293   USS_Other
11294 };
11295 
11296 struct InvalidSTLDiagnoser {
11297   Sema &S;
11298   SourceLocation Loc;
11299   QualType TyForDiags;
11300 
11301   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11302                       const VarDecl *VD = nullptr) {
11303     {
11304       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11305                << TyForDiags << ((int)Sel);
11306       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11307         assert(!Name.empty());
11308         D << Name;
11309       }
11310     }
11311     if (Sel == USS_InvalidMember) {
11312       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11313           << VD << VD->getSourceRange();
11314     }
11315     return QualType();
11316   }
11317 };
11318 } // namespace
11319 
11320 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11321                                            SourceLocation Loc,
11322                                            ComparisonCategoryUsage Usage) {
11323   assert(getLangOpts().CPlusPlus &&
11324          "Looking for comparison category type outside of C++.");
11325 
11326   // Use an elaborated type for diagnostics which has a name containing the
11327   // prepended 'std' namespace but not any inline namespace names.
11328   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11329     auto *NNS =
11330         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11331     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11332   };
11333 
11334   // Check if we've already successfully checked the comparison category type
11335   // before. If so, skip checking it again.
11336   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11337   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11338     // The only thing we need to check is that the type has a reachable
11339     // definition in the current context.
11340     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11341       return QualType();
11342 
11343     return Info->getType();
11344   }
11345 
11346   // If lookup failed
11347   if (!Info) {
11348     std::string NameForDiags = "std::";
11349     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11350     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11351         << NameForDiags << (int)Usage;
11352     return QualType();
11353   }
11354 
11355   assert(Info->Kind == Kind);
11356   assert(Info->Record);
11357 
11358   // Update the Record decl in case we encountered a forward declaration on our
11359   // first pass. FIXME: This is a bit of a hack.
11360   if (Info->Record->hasDefinition())
11361     Info->Record = Info->Record->getDefinition();
11362 
11363   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11364     return QualType();
11365 
11366   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11367 
11368   if (!Info->Record->isTriviallyCopyable())
11369     return UnsupportedSTLError(USS_NonTrivial);
11370 
11371   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11372     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11373     // Tolerate empty base classes.
11374     if (Base->isEmpty())
11375       continue;
11376     // Reject STL implementations which have at least one non-empty base.
11377     return UnsupportedSTLError();
11378   }
11379 
11380   // Check that the STL has implemented the types using a single integer field.
11381   // This expectation allows better codegen for builtin operators. We require:
11382   //   (1) The class has exactly one field.
11383   //   (2) The field is an integral or enumeration type.
11384   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11385   if (std::distance(FIt, FEnd) != 1 ||
11386       !FIt->getType()->isIntegralOrEnumerationType()) {
11387     return UnsupportedSTLError();
11388   }
11389 
11390   // Build each of the require values and store them in Info.
11391   for (ComparisonCategoryResult CCR :
11392        ComparisonCategories::getPossibleResultsForType(Kind)) {
11393     StringRef MemName = ComparisonCategories::getResultString(CCR);
11394     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11395 
11396     if (!ValInfo)
11397       return UnsupportedSTLError(USS_MissingMember, MemName);
11398 
11399     VarDecl *VD = ValInfo->VD;
11400     assert(VD && "should not be null!");
11401 
11402     // Attempt to diagnose reasons why the STL definition of this type
11403     // might be foobar, including it failing to be a constant expression.
11404     // TODO Handle more ways the lookup or result can be invalid.
11405     if (!VD->isStaticDataMember() ||
11406         !VD->isUsableInConstantExpressions(Context))
11407       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11408 
11409     // Attempt to evaluate the var decl as a constant expression and extract
11410     // the value of its first field as a ICE. If this fails, the STL
11411     // implementation is not supported.
11412     if (!ValInfo->hasValidIntValue())
11413       return UnsupportedSTLError();
11414 
11415     MarkVariableReferenced(Loc, VD);
11416   }
11417 
11418   // We've successfully built the required types and expressions. Update
11419   // the cache and return the newly cached value.
11420   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11421   return Info->getType();
11422 }
11423 
11424 /// Retrieve the special "std" namespace, which may require us to
11425 /// implicitly define the namespace.
11426 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11427   if (!StdNamespace) {
11428     // The "std" namespace has not yet been defined, so build one implicitly.
11429     StdNamespace = NamespaceDecl::Create(Context,
11430                                          Context.getTranslationUnitDecl(),
11431                                          /*Inline=*/false,
11432                                          SourceLocation(), SourceLocation(),
11433                                          &PP.getIdentifierTable().get("std"),
11434                                          /*PrevDecl=*/nullptr);
11435     getStdNamespace()->setImplicit(true);
11436   }
11437 
11438   return getStdNamespace();
11439 }
11440 
11441 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11442   assert(getLangOpts().CPlusPlus &&
11443          "Looking for std::initializer_list outside of C++.");
11444 
11445   // We're looking for implicit instantiations of
11446   // template <typename E> class std::initializer_list.
11447 
11448   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11449     return false;
11450 
11451   ClassTemplateDecl *Template = nullptr;
11452   const TemplateArgument *Arguments = nullptr;
11453 
11454   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11455 
11456     ClassTemplateSpecializationDecl *Specialization =
11457         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11458     if (!Specialization)
11459       return false;
11460 
11461     Template = Specialization->getSpecializedTemplate();
11462     Arguments = Specialization->getTemplateArgs().data();
11463   } else if (const TemplateSpecializationType *TST =
11464                  Ty->getAs<TemplateSpecializationType>()) {
11465     Template = dyn_cast_or_null<ClassTemplateDecl>(
11466         TST->getTemplateName().getAsTemplateDecl());
11467     Arguments = TST->getArgs();
11468   }
11469   if (!Template)
11470     return false;
11471 
11472   if (!StdInitializerList) {
11473     // Haven't recognized std::initializer_list yet, maybe this is it.
11474     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11475     if (TemplateClass->getIdentifier() !=
11476             &PP.getIdentifierTable().get("initializer_list") ||
11477         !getStdNamespace()->InEnclosingNamespaceSetOf(
11478             TemplateClass->getDeclContext()))
11479       return false;
11480     // This is a template called std::initializer_list, but is it the right
11481     // template?
11482     TemplateParameterList *Params = Template->getTemplateParameters();
11483     if (Params->getMinRequiredArguments() != 1)
11484       return false;
11485     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11486       return false;
11487 
11488     // It's the right template.
11489     StdInitializerList = Template;
11490   }
11491 
11492   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11493     return false;
11494 
11495   // This is an instance of std::initializer_list. Find the argument type.
11496   if (Element)
11497     *Element = Arguments[0].getAsType();
11498   return true;
11499 }
11500 
11501 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11502   NamespaceDecl *Std = S.getStdNamespace();
11503   if (!Std) {
11504     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11505     return nullptr;
11506   }
11507 
11508   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11509                       Loc, Sema::LookupOrdinaryName);
11510   if (!S.LookupQualifiedName(Result, Std)) {
11511     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11512     return nullptr;
11513   }
11514   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11515   if (!Template) {
11516     Result.suppressDiagnostics();
11517     // We found something weird. Complain about the first thing we found.
11518     NamedDecl *Found = *Result.begin();
11519     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11520     return nullptr;
11521   }
11522 
11523   // We found some template called std::initializer_list. Now verify that it's
11524   // correct.
11525   TemplateParameterList *Params = Template->getTemplateParameters();
11526   if (Params->getMinRequiredArguments() != 1 ||
11527       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11528     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11529     return nullptr;
11530   }
11531 
11532   return Template;
11533 }
11534 
11535 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11536   if (!StdInitializerList) {
11537     StdInitializerList = LookupStdInitializerList(*this, Loc);
11538     if (!StdInitializerList)
11539       return QualType();
11540   }
11541 
11542   TemplateArgumentListInfo Args(Loc, Loc);
11543   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11544                                        Context.getTrivialTypeSourceInfo(Element,
11545                                                                         Loc)));
11546   return Context.getCanonicalType(
11547       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11548 }
11549 
11550 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11551   // C++ [dcl.init.list]p2:
11552   //   A constructor is an initializer-list constructor if its first parameter
11553   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11554   //   std::initializer_list<E> for some type E, and either there are no other
11555   //   parameters or else all other parameters have default arguments.
11556   if (!Ctor->hasOneParamOrDefaultArgs())
11557     return false;
11558 
11559   QualType ArgType = Ctor->getParamDecl(0)->getType();
11560   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11561     ArgType = RT->getPointeeType().getUnqualifiedType();
11562 
11563   return isStdInitializerList(ArgType, nullptr);
11564 }
11565 
11566 /// Determine whether a using statement is in a context where it will be
11567 /// apply in all contexts.
11568 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11569   switch (CurContext->getDeclKind()) {
11570     case Decl::TranslationUnit:
11571       return true;
11572     case Decl::LinkageSpec:
11573       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11574     default:
11575       return false;
11576   }
11577 }
11578 
11579 namespace {
11580 
11581 // Callback to only accept typo corrections that are namespaces.
11582 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11583 public:
11584   bool ValidateCandidate(const TypoCorrection &candidate) override {
11585     if (NamedDecl *ND = candidate.getCorrectionDecl())
11586       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11587     return false;
11588   }
11589 
11590   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11591     return std::make_unique<NamespaceValidatorCCC>(*this);
11592   }
11593 };
11594 
11595 }
11596 
11597 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11598                                        CXXScopeSpec &SS,
11599                                        SourceLocation IdentLoc,
11600                                        IdentifierInfo *Ident) {
11601   R.clear();
11602   NamespaceValidatorCCC CCC{};
11603   if (TypoCorrection Corrected =
11604           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11605                         Sema::CTK_ErrorRecovery)) {
11606     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11607       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11608       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11609                               Ident->getName().equals(CorrectedStr);
11610       S.diagnoseTypo(Corrected,
11611                      S.PDiag(diag::err_using_directive_member_suggest)
11612                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11613                      S.PDiag(diag::note_namespace_defined_here));
11614     } else {
11615       S.diagnoseTypo(Corrected,
11616                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11617                      S.PDiag(diag::note_namespace_defined_here));
11618     }
11619     R.addDecl(Corrected.getFoundDecl());
11620     return true;
11621   }
11622   return false;
11623 }
11624 
11625 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11626                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11627                                 SourceLocation IdentLoc,
11628                                 IdentifierInfo *NamespcName,
11629                                 const ParsedAttributesView &AttrList) {
11630   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11631   assert(NamespcName && "Invalid NamespcName.");
11632   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11633 
11634   // This can only happen along a recovery path.
11635   while (S->isTemplateParamScope())
11636     S = S->getParent();
11637   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11638 
11639   UsingDirectiveDecl *UDir = nullptr;
11640   NestedNameSpecifier *Qualifier = nullptr;
11641   if (SS.isSet())
11642     Qualifier = SS.getScopeRep();
11643 
11644   // Lookup namespace name.
11645   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11646   LookupParsedName(R, S, &SS);
11647   if (R.isAmbiguous())
11648     return nullptr;
11649 
11650   if (R.empty()) {
11651     R.clear();
11652     // Allow "using namespace std;" or "using namespace ::std;" even if
11653     // "std" hasn't been defined yet, for GCC compatibility.
11654     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11655         NamespcName->isStr("std")) {
11656       Diag(IdentLoc, diag::ext_using_undefined_std);
11657       R.addDecl(getOrCreateStdNamespace());
11658       R.resolveKind();
11659     }
11660     // Otherwise, attempt typo correction.
11661     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11662   }
11663 
11664   if (!R.empty()) {
11665     NamedDecl *Named = R.getRepresentativeDecl();
11666     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11667     assert(NS && "expected namespace decl");
11668 
11669     // The use of a nested name specifier may trigger deprecation warnings.
11670     DiagnoseUseOfDecl(Named, IdentLoc);
11671 
11672     // C++ [namespace.udir]p1:
11673     //   A using-directive specifies that the names in the nominated
11674     //   namespace can be used in the scope in which the
11675     //   using-directive appears after the using-directive. During
11676     //   unqualified name lookup (3.4.1), the names appear as if they
11677     //   were declared in the nearest enclosing namespace which
11678     //   contains both the using-directive and the nominated
11679     //   namespace. [Note: in this context, "contains" means "contains
11680     //   directly or indirectly". ]
11681 
11682     // Find enclosing context containing both using-directive and
11683     // nominated namespace.
11684     DeclContext *CommonAncestor = NS;
11685     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11686       CommonAncestor = CommonAncestor->getParent();
11687 
11688     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11689                                       SS.getWithLocInContext(Context),
11690                                       IdentLoc, Named, CommonAncestor);
11691 
11692     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11693         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11694       Diag(IdentLoc, diag::warn_using_directive_in_header);
11695     }
11696 
11697     PushUsingDirective(S, UDir);
11698   } else {
11699     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11700   }
11701 
11702   if (UDir)
11703     ProcessDeclAttributeList(S, UDir, AttrList);
11704 
11705   return UDir;
11706 }
11707 
11708 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11709   // If the scope has an associated entity and the using directive is at
11710   // namespace or translation unit scope, add the UsingDirectiveDecl into
11711   // its lookup structure so qualified name lookup can find it.
11712   DeclContext *Ctx = S->getEntity();
11713   if (Ctx && !Ctx->isFunctionOrMethod())
11714     Ctx->addDecl(UDir);
11715   else
11716     // Otherwise, it is at block scope. The using-directives will affect lookup
11717     // only to the end of the scope.
11718     S->PushUsingDirective(UDir);
11719 }
11720 
11721 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11722                                   SourceLocation UsingLoc,
11723                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11724                                   UnqualifiedId &Name,
11725                                   SourceLocation EllipsisLoc,
11726                                   const ParsedAttributesView &AttrList) {
11727   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11728 
11729   if (SS.isEmpty()) {
11730     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11731     return nullptr;
11732   }
11733 
11734   switch (Name.getKind()) {
11735   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11736   case UnqualifiedIdKind::IK_Identifier:
11737   case UnqualifiedIdKind::IK_OperatorFunctionId:
11738   case UnqualifiedIdKind::IK_LiteralOperatorId:
11739   case UnqualifiedIdKind::IK_ConversionFunctionId:
11740     break;
11741 
11742   case UnqualifiedIdKind::IK_ConstructorName:
11743   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11744     // C++11 inheriting constructors.
11745     Diag(Name.getBeginLoc(),
11746          getLangOpts().CPlusPlus11
11747              ? diag::warn_cxx98_compat_using_decl_constructor
11748              : diag::err_using_decl_constructor)
11749         << SS.getRange();
11750 
11751     if (getLangOpts().CPlusPlus11) break;
11752 
11753     return nullptr;
11754 
11755   case UnqualifiedIdKind::IK_DestructorName:
11756     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11757     return nullptr;
11758 
11759   case UnqualifiedIdKind::IK_TemplateId:
11760     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11761         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11762     return nullptr;
11763 
11764   case UnqualifiedIdKind::IK_DeductionGuideName:
11765     llvm_unreachable("cannot parse qualified deduction guide name");
11766   }
11767 
11768   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11769   DeclarationName TargetName = TargetNameInfo.getName();
11770   if (!TargetName)
11771     return nullptr;
11772 
11773   // Warn about access declarations.
11774   if (UsingLoc.isInvalid()) {
11775     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11776                                  ? diag::err_access_decl
11777                                  : diag::warn_access_decl_deprecated)
11778         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11779   }
11780 
11781   if (EllipsisLoc.isInvalid()) {
11782     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11783         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11784       return nullptr;
11785   } else {
11786     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11787         !TargetNameInfo.containsUnexpandedParameterPack()) {
11788       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11789         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11790       EllipsisLoc = SourceLocation();
11791     }
11792   }
11793 
11794   NamedDecl *UD =
11795       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11796                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11797                             /*IsInstantiation*/ false,
11798                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11799   if (UD)
11800     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11801 
11802   return UD;
11803 }
11804 
11805 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11806                                       SourceLocation UsingLoc,
11807                                       SourceLocation EnumLoc,
11808                                       const DeclSpec &DS) {
11809   switch (DS.getTypeSpecType()) {
11810   case DeclSpec::TST_error:
11811     // This will already have been diagnosed
11812     return nullptr;
11813 
11814   case DeclSpec::TST_enum:
11815     break;
11816 
11817   case DeclSpec::TST_typename:
11818     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11819     return nullptr;
11820 
11821   default:
11822     llvm_unreachable("unexpected DeclSpec type");
11823   }
11824 
11825   // As with enum-decls, we ignore attributes for now.
11826   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11827   if (auto *Def = Enum->getDefinition())
11828     Enum = Def;
11829 
11830   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11831                                        DS.getTypeSpecTypeNameLoc(), Enum);
11832   if (UD)
11833     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11834 
11835   return UD;
11836 }
11837 
11838 /// Determine whether a using declaration considers the given
11839 /// declarations as "equivalent", e.g., if they are redeclarations of
11840 /// the same entity or are both typedefs of the same type.
11841 static bool
11842 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11843   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11844     return true;
11845 
11846   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11847     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11848       return Context.hasSameType(TD1->getUnderlyingType(),
11849                                  TD2->getUnderlyingType());
11850 
11851   // Two using_if_exists using-declarations are equivalent if both are
11852   // unresolved.
11853   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11854       isa<UnresolvedUsingIfExistsDecl>(D2))
11855     return true;
11856 
11857   return false;
11858 }
11859 
11860 
11861 /// Determines whether to create a using shadow decl for a particular
11862 /// decl, given the set of decls existing prior to this using lookup.
11863 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11864                                 const LookupResult &Previous,
11865                                 UsingShadowDecl *&PrevShadow) {
11866   // Diagnose finding a decl which is not from a base class of the
11867   // current class.  We do this now because there are cases where this
11868   // function will silently decide not to build a shadow decl, which
11869   // will pre-empt further diagnostics.
11870   //
11871   // We don't need to do this in C++11 because we do the check once on
11872   // the qualifier.
11873   //
11874   // FIXME: diagnose the following if we care enough:
11875   //   struct A { int foo; };
11876   //   struct B : A { using A::foo; };
11877   //   template <class T> struct C : A {};
11878   //   template <class T> struct D : C<T> { using B::foo; } // <---
11879   // This is invalid (during instantiation) in C++03 because B::foo
11880   // resolves to the using decl in B, which is not a base class of D<T>.
11881   // We can't diagnose it immediately because C<T> is an unknown
11882   // specialization. The UsingShadowDecl in D<T> then points directly
11883   // to A::foo, which will look well-formed when we instantiate.
11884   // The right solution is to not collapse the shadow-decl chain.
11885   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11886     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11887       DeclContext *OrigDC = Orig->getDeclContext();
11888 
11889       // Handle enums and anonymous structs.
11890       if (isa<EnumDecl>(OrigDC))
11891         OrigDC = OrigDC->getParent();
11892       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11893       while (OrigRec->isAnonymousStructOrUnion())
11894         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11895 
11896       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11897         if (OrigDC == CurContext) {
11898           Diag(Using->getLocation(),
11899                diag::err_using_decl_nested_name_specifier_is_current_class)
11900               << Using->getQualifierLoc().getSourceRange();
11901           Diag(Orig->getLocation(), diag::note_using_decl_target);
11902           Using->setInvalidDecl();
11903           return true;
11904         }
11905 
11906         Diag(Using->getQualifierLoc().getBeginLoc(),
11907              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11908             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11909             << Using->getQualifierLoc().getSourceRange();
11910         Diag(Orig->getLocation(), diag::note_using_decl_target);
11911         Using->setInvalidDecl();
11912         return true;
11913       }
11914     }
11915 
11916   if (Previous.empty()) return false;
11917 
11918   NamedDecl *Target = Orig;
11919   if (isa<UsingShadowDecl>(Target))
11920     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11921 
11922   // If the target happens to be one of the previous declarations, we
11923   // don't have a conflict.
11924   //
11925   // FIXME: but we might be increasing its access, in which case we
11926   // should redeclare it.
11927   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11928   bool FoundEquivalentDecl = false;
11929   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11930          I != E; ++I) {
11931     NamedDecl *D = (*I)->getUnderlyingDecl();
11932     // We can have UsingDecls in our Previous results because we use the same
11933     // LookupResult for checking whether the UsingDecl itself is a valid
11934     // redeclaration.
11935     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11936       continue;
11937 
11938     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11939       // C++ [class.mem]p19:
11940       //   If T is the name of a class, then [every named member other than
11941       //   a non-static data member] shall have a name different from T
11942       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11943           !isa<IndirectFieldDecl>(Target) &&
11944           !isa<UnresolvedUsingValueDecl>(Target) &&
11945           DiagnoseClassNameShadow(
11946               CurContext,
11947               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11948         return true;
11949     }
11950 
11951     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11952       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11953         PrevShadow = Shadow;
11954       FoundEquivalentDecl = true;
11955     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11956       // We don't conflict with an existing using shadow decl of an equivalent
11957       // declaration, but we're not a redeclaration of it.
11958       FoundEquivalentDecl = true;
11959     }
11960 
11961     if (isVisible(D))
11962       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11963   }
11964 
11965   if (FoundEquivalentDecl)
11966     return false;
11967 
11968   // Always emit a diagnostic for a mismatch between an unresolved
11969   // using_if_exists and a resolved using declaration in either direction.
11970   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11971       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11972     if (!NonTag && !Tag)
11973       return false;
11974     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11975     Diag(Target->getLocation(), diag::note_using_decl_target);
11976     Diag((NonTag ? NonTag : Tag)->getLocation(),
11977          diag::note_using_decl_conflict);
11978     BUD->setInvalidDecl();
11979     return true;
11980   }
11981 
11982   if (FunctionDecl *FD = Target->getAsFunction()) {
11983     NamedDecl *OldDecl = nullptr;
11984     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11985                           /*IsForUsingDecl*/ true)) {
11986     case Ovl_Overload:
11987       return false;
11988 
11989     case Ovl_NonFunction:
11990       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11991       break;
11992 
11993     // We found a decl with the exact signature.
11994     case Ovl_Match:
11995       // If we're in a record, we want to hide the target, so we
11996       // return true (without a diagnostic) to tell the caller not to
11997       // build a shadow decl.
11998       if (CurContext->isRecord())
11999         return true;
12000 
12001       // If we're not in a record, this is an error.
12002       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12003       break;
12004     }
12005 
12006     Diag(Target->getLocation(), diag::note_using_decl_target);
12007     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12008     BUD->setInvalidDecl();
12009     return true;
12010   }
12011 
12012   // Target is not a function.
12013 
12014   if (isa<TagDecl>(Target)) {
12015     // No conflict between a tag and a non-tag.
12016     if (!Tag) return false;
12017 
12018     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12019     Diag(Target->getLocation(), diag::note_using_decl_target);
12020     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12021     BUD->setInvalidDecl();
12022     return true;
12023   }
12024 
12025   // No conflict between a tag and a non-tag.
12026   if (!NonTag) return false;
12027 
12028   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12029   Diag(Target->getLocation(), diag::note_using_decl_target);
12030   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12031   BUD->setInvalidDecl();
12032   return true;
12033 }
12034 
12035 /// Determine whether a direct base class is a virtual base class.
12036 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12037   if (!Derived->getNumVBases())
12038     return false;
12039   for (auto &B : Derived->bases())
12040     if (B.getType()->getAsCXXRecordDecl() == Base)
12041       return B.isVirtual();
12042   llvm_unreachable("not a direct base class");
12043 }
12044 
12045 /// Builds a shadow declaration corresponding to a 'using' declaration.
12046 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12047                                             NamedDecl *Orig,
12048                                             UsingShadowDecl *PrevDecl) {
12049   // If we resolved to another shadow declaration, just coalesce them.
12050   NamedDecl *Target = Orig;
12051   if (isa<UsingShadowDecl>(Target)) {
12052     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12053     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12054   }
12055 
12056   NamedDecl *NonTemplateTarget = Target;
12057   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12058     NonTemplateTarget = TargetTD->getTemplatedDecl();
12059 
12060   UsingShadowDecl *Shadow;
12061   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12062     UsingDecl *Using = cast<UsingDecl>(BUD);
12063     bool IsVirtualBase =
12064         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12065                             Using->getQualifier()->getAsRecordDecl());
12066     Shadow = ConstructorUsingShadowDecl::Create(
12067         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12068   } else {
12069     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12070                                      Target->getDeclName(), BUD, Target);
12071   }
12072   BUD->addShadowDecl(Shadow);
12073 
12074   Shadow->setAccess(BUD->getAccess());
12075   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12076     Shadow->setInvalidDecl();
12077 
12078   Shadow->setPreviousDecl(PrevDecl);
12079 
12080   if (S)
12081     PushOnScopeChains(Shadow, S);
12082   else
12083     CurContext->addDecl(Shadow);
12084 
12085 
12086   return Shadow;
12087 }
12088 
12089 /// Hides a using shadow declaration.  This is required by the current
12090 /// using-decl implementation when a resolvable using declaration in a
12091 /// class is followed by a declaration which would hide or override
12092 /// one or more of the using decl's targets; for example:
12093 ///
12094 ///   struct Base { void foo(int); };
12095 ///   struct Derived : Base {
12096 ///     using Base::foo;
12097 ///     void foo(int);
12098 ///   };
12099 ///
12100 /// The governing language is C++03 [namespace.udecl]p12:
12101 ///
12102 ///   When a using-declaration brings names from a base class into a
12103 ///   derived class scope, member functions in the derived class
12104 ///   override and/or hide member functions with the same name and
12105 ///   parameter types in a base class (rather than conflicting).
12106 ///
12107 /// There are two ways to implement this:
12108 ///   (1) optimistically create shadow decls when they're not hidden
12109 ///       by existing declarations, or
12110 ///   (2) don't create any shadow decls (or at least don't make them
12111 ///       visible) until we've fully parsed/instantiated the class.
12112 /// The problem with (1) is that we might have to retroactively remove
12113 /// a shadow decl, which requires several O(n) operations because the
12114 /// decl structures are (very reasonably) not designed for removal.
12115 /// (2) avoids this but is very fiddly and phase-dependent.
12116 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12117   if (Shadow->getDeclName().getNameKind() ==
12118         DeclarationName::CXXConversionFunctionName)
12119     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12120 
12121   // Remove it from the DeclContext...
12122   Shadow->getDeclContext()->removeDecl(Shadow);
12123 
12124   // ...and the scope, if applicable...
12125   if (S) {
12126     S->RemoveDecl(Shadow);
12127     IdResolver.RemoveDecl(Shadow);
12128   }
12129 
12130   // ...and the using decl.
12131   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12132 
12133   // TODO: complain somehow if Shadow was used.  It shouldn't
12134   // be possible for this to happen, because...?
12135 }
12136 
12137 /// Find the base specifier for a base class with the given type.
12138 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12139                                                 QualType DesiredBase,
12140                                                 bool &AnyDependentBases) {
12141   // Check whether the named type is a direct base class.
12142   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12143     .getUnqualifiedType();
12144   for (auto &Base : Derived->bases()) {
12145     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12146     if (CanonicalDesiredBase == BaseType)
12147       return &Base;
12148     if (BaseType->isDependentType())
12149       AnyDependentBases = true;
12150   }
12151   return nullptr;
12152 }
12153 
12154 namespace {
12155 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12156 public:
12157   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12158                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12159       : HasTypenameKeyword(HasTypenameKeyword),
12160         IsInstantiation(IsInstantiation), OldNNS(NNS),
12161         RequireMemberOf(RequireMemberOf) {}
12162 
12163   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12164     NamedDecl *ND = Candidate.getCorrectionDecl();
12165 
12166     // Keywords are not valid here.
12167     if (!ND || isa<NamespaceDecl>(ND))
12168       return false;
12169 
12170     // Completely unqualified names are invalid for a 'using' declaration.
12171     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12172       return false;
12173 
12174     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12175     // reject.
12176 
12177     if (RequireMemberOf) {
12178       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12179       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12180         // No-one ever wants a using-declaration to name an injected-class-name
12181         // of a base class, unless they're declaring an inheriting constructor.
12182         ASTContext &Ctx = ND->getASTContext();
12183         if (!Ctx.getLangOpts().CPlusPlus11)
12184           return false;
12185         QualType FoundType = Ctx.getRecordType(FoundRecord);
12186 
12187         // Check that the injected-class-name is named as a member of its own
12188         // type; we don't want to suggest 'using Derived::Base;', since that
12189         // means something else.
12190         NestedNameSpecifier *Specifier =
12191             Candidate.WillReplaceSpecifier()
12192                 ? Candidate.getCorrectionSpecifier()
12193                 : OldNNS;
12194         if (!Specifier->getAsType() ||
12195             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12196           return false;
12197 
12198         // Check that this inheriting constructor declaration actually names a
12199         // direct base class of the current class.
12200         bool AnyDependentBases = false;
12201         if (!findDirectBaseWithType(RequireMemberOf,
12202                                     Ctx.getRecordType(FoundRecord),
12203                                     AnyDependentBases) &&
12204             !AnyDependentBases)
12205           return false;
12206       } else {
12207         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12208         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12209           return false;
12210 
12211         // FIXME: Check that the base class member is accessible?
12212       }
12213     } else {
12214       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12215       if (FoundRecord && FoundRecord->isInjectedClassName())
12216         return false;
12217     }
12218 
12219     if (isa<TypeDecl>(ND))
12220       return HasTypenameKeyword || !IsInstantiation;
12221 
12222     return !HasTypenameKeyword;
12223   }
12224 
12225   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12226     return std::make_unique<UsingValidatorCCC>(*this);
12227   }
12228 
12229 private:
12230   bool HasTypenameKeyword;
12231   bool IsInstantiation;
12232   NestedNameSpecifier *OldNNS;
12233   CXXRecordDecl *RequireMemberOf;
12234 };
12235 } // end anonymous namespace
12236 
12237 /// Remove decls we can't actually see from a lookup being used to declare
12238 /// shadow using decls.
12239 ///
12240 /// \param S - The scope of the potential shadow decl
12241 /// \param Previous - The lookup of a potential shadow decl's name.
12242 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12243   // It is really dumb that we have to do this.
12244   LookupResult::Filter F = Previous.makeFilter();
12245   while (F.hasNext()) {
12246     NamedDecl *D = F.next();
12247     if (!isDeclInScope(D, CurContext, S))
12248       F.erase();
12249     // If we found a local extern declaration that's not ordinarily visible,
12250     // and this declaration is being added to a non-block scope, ignore it.
12251     // We're only checking for scope conflicts here, not also for violations
12252     // of the linkage rules.
12253     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12254              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12255       F.erase();
12256   }
12257   F.done();
12258 }
12259 
12260 /// Builds a using declaration.
12261 ///
12262 /// \param IsInstantiation - Whether this call arises from an
12263 ///   instantiation of an unresolved using declaration.  We treat
12264 ///   the lookup differently for these declarations.
12265 NamedDecl *Sema::BuildUsingDeclaration(
12266     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12267     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12268     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12269     const ParsedAttributesView &AttrList, bool IsInstantiation,
12270     bool IsUsingIfExists) {
12271   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12272   SourceLocation IdentLoc = NameInfo.getLoc();
12273   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12274 
12275   // FIXME: We ignore attributes for now.
12276 
12277   // For an inheriting constructor declaration, the name of the using
12278   // declaration is the name of a constructor in this class, not in the
12279   // base class.
12280   DeclarationNameInfo UsingName = NameInfo;
12281   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12282     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12283       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12284           Context.getCanonicalType(Context.getRecordType(RD))));
12285 
12286   // Do the redeclaration lookup in the current scope.
12287   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12288                         ForVisibleRedeclaration);
12289   Previous.setHideTags(false);
12290   if (S) {
12291     LookupName(Previous, S);
12292 
12293     FilterUsingLookup(S, Previous);
12294   } else {
12295     assert(IsInstantiation && "no scope in non-instantiation");
12296     if (CurContext->isRecord())
12297       LookupQualifiedName(Previous, CurContext);
12298     else {
12299       // No redeclaration check is needed here; in non-member contexts we
12300       // diagnosed all possible conflicts with other using-declarations when
12301       // building the template:
12302       //
12303       // For a dependent non-type using declaration, the only valid case is
12304       // if we instantiate to a single enumerator. We check for conflicts
12305       // between shadow declarations we introduce, and we check in the template
12306       // definition for conflicts between a non-type using declaration and any
12307       // other declaration, which together covers all cases.
12308       //
12309       // A dependent typename using declaration will never successfully
12310       // instantiate, since it will always name a class member, so we reject
12311       // that in the template definition.
12312     }
12313   }
12314 
12315   // Check for invalid redeclarations.
12316   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12317                                   SS, IdentLoc, Previous))
12318     return nullptr;
12319 
12320   // 'using_if_exists' doesn't make sense on an inherited constructor.
12321   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12322                              DeclarationName::CXXConstructorName) {
12323     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12324     return nullptr;
12325   }
12326 
12327   DeclContext *LookupContext = computeDeclContext(SS);
12328   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12329   if (!LookupContext || EllipsisLoc.isValid()) {
12330     NamedDecl *D;
12331     // Dependent scope, or an unexpanded pack
12332     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12333                                                   SS, NameInfo, IdentLoc))
12334       return nullptr;
12335 
12336     if (HasTypenameKeyword) {
12337       // FIXME: not all declaration name kinds are legal here
12338       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12339                                               UsingLoc, TypenameLoc,
12340                                               QualifierLoc,
12341                                               IdentLoc, NameInfo.getName(),
12342                                               EllipsisLoc);
12343     } else {
12344       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12345                                            QualifierLoc, NameInfo, EllipsisLoc);
12346     }
12347     D->setAccess(AS);
12348     CurContext->addDecl(D);
12349     ProcessDeclAttributeList(S, D, AttrList);
12350     return D;
12351   }
12352 
12353   auto Build = [&](bool Invalid) {
12354     UsingDecl *UD =
12355         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12356                           UsingName, HasTypenameKeyword);
12357     UD->setAccess(AS);
12358     CurContext->addDecl(UD);
12359     ProcessDeclAttributeList(S, UD, AttrList);
12360     UD->setInvalidDecl(Invalid);
12361     return UD;
12362   };
12363   auto BuildInvalid = [&]{ return Build(true); };
12364   auto BuildValid = [&]{ return Build(false); };
12365 
12366   if (RequireCompleteDeclContext(SS, LookupContext))
12367     return BuildInvalid();
12368 
12369   // Look up the target name.
12370   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12371 
12372   // Unlike most lookups, we don't always want to hide tag
12373   // declarations: tag names are visible through the using declaration
12374   // even if hidden by ordinary names, *except* in a dependent context
12375   // where they may be used by two-phase lookup.
12376   if (!IsInstantiation)
12377     R.setHideTags(false);
12378 
12379   // For the purposes of this lookup, we have a base object type
12380   // equal to that of the current context.
12381   if (CurContext->isRecord()) {
12382     R.setBaseObjectType(
12383                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12384   }
12385 
12386   LookupQualifiedName(R, LookupContext);
12387 
12388   // Validate the context, now we have a lookup
12389   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12390                               IdentLoc, &R))
12391     return nullptr;
12392 
12393   if (R.empty() && IsUsingIfExists)
12394     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12395                                                   UsingName.getName()),
12396               AS_public);
12397 
12398   // Try to correct typos if possible. If constructor name lookup finds no
12399   // results, that means the named class has no explicit constructors, and we
12400   // suppressed declaring implicit ones (probably because it's dependent or
12401   // invalid).
12402   if (R.empty() &&
12403       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12404     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12405     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12406     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12407     auto *II = NameInfo.getName().getAsIdentifierInfo();
12408     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12409         CurContext->isStdNamespace() &&
12410         isa<TranslationUnitDecl>(LookupContext) &&
12411         getSourceManager().isInSystemHeader(UsingLoc))
12412       return nullptr;
12413     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12414                           dyn_cast<CXXRecordDecl>(CurContext));
12415     if (TypoCorrection Corrected =
12416             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12417                         CTK_ErrorRecovery)) {
12418       // We reject candidates where DroppedSpecifier == true, hence the
12419       // literal '0' below.
12420       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12421                                 << NameInfo.getName() << LookupContext << 0
12422                                 << SS.getRange());
12423 
12424       // If we picked a correction with no attached Decl we can't do anything
12425       // useful with it, bail out.
12426       NamedDecl *ND = Corrected.getCorrectionDecl();
12427       if (!ND)
12428         return BuildInvalid();
12429 
12430       // If we corrected to an inheriting constructor, handle it as one.
12431       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12432       if (RD && RD->isInjectedClassName()) {
12433         // The parent of the injected class name is the class itself.
12434         RD = cast<CXXRecordDecl>(RD->getParent());
12435 
12436         // Fix up the information we'll use to build the using declaration.
12437         if (Corrected.WillReplaceSpecifier()) {
12438           NestedNameSpecifierLocBuilder Builder;
12439           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12440                               QualifierLoc.getSourceRange());
12441           QualifierLoc = Builder.getWithLocInContext(Context);
12442         }
12443 
12444         // In this case, the name we introduce is the name of a derived class
12445         // constructor.
12446         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12447         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12448             Context.getCanonicalType(Context.getRecordType(CurClass))));
12449         UsingName.setNamedTypeInfo(nullptr);
12450         for (auto *Ctor : LookupConstructors(RD))
12451           R.addDecl(Ctor);
12452         R.resolveKind();
12453       } else {
12454         // FIXME: Pick up all the declarations if we found an overloaded
12455         // function.
12456         UsingName.setName(ND->getDeclName());
12457         R.addDecl(ND);
12458       }
12459     } else {
12460       Diag(IdentLoc, diag::err_no_member)
12461         << NameInfo.getName() << LookupContext << SS.getRange();
12462       return BuildInvalid();
12463     }
12464   }
12465 
12466   if (R.isAmbiguous())
12467     return BuildInvalid();
12468 
12469   if (HasTypenameKeyword) {
12470     // If we asked for a typename and got a non-type decl, error out.
12471     if (!R.getAsSingle<TypeDecl>() &&
12472         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12473       Diag(IdentLoc, diag::err_using_typename_non_type);
12474       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12475         Diag((*I)->getUnderlyingDecl()->getLocation(),
12476              diag::note_using_decl_target);
12477       return BuildInvalid();
12478     }
12479   } else {
12480     // If we asked for a non-typename and we got a type, error out,
12481     // but only if this is an instantiation of an unresolved using
12482     // decl.  Otherwise just silently find the type name.
12483     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12484       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12485       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12486       return BuildInvalid();
12487     }
12488   }
12489 
12490   // C++14 [namespace.udecl]p6:
12491   // A using-declaration shall not name a namespace.
12492   if (R.getAsSingle<NamespaceDecl>()) {
12493     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12494       << SS.getRange();
12495     return BuildInvalid();
12496   }
12497 
12498   UsingDecl *UD = BuildValid();
12499 
12500   // Some additional rules apply to inheriting constructors.
12501   if (UsingName.getName().getNameKind() ==
12502         DeclarationName::CXXConstructorName) {
12503     // Suppress access diagnostics; the access check is instead performed at the
12504     // point of use for an inheriting constructor.
12505     R.suppressDiagnostics();
12506     if (CheckInheritingConstructorUsingDecl(UD))
12507       return UD;
12508   }
12509 
12510   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12511     UsingShadowDecl *PrevDecl = nullptr;
12512     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12513       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12514   }
12515 
12516   return UD;
12517 }
12518 
12519 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12520                                            SourceLocation UsingLoc,
12521                                            SourceLocation EnumLoc,
12522                                            SourceLocation NameLoc,
12523                                            EnumDecl *ED) {
12524   bool Invalid = false;
12525 
12526   if (CurContext->getRedeclContext()->isRecord()) {
12527     /// In class scope, check if this is a duplicate, for better a diagnostic.
12528     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12529     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12530                           ForVisibleRedeclaration);
12531 
12532     LookupName(Previous, S);
12533 
12534     for (NamedDecl *D : Previous)
12535       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12536         if (UED->getEnumDecl() == ED) {
12537           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12538               << SourceRange(EnumLoc, NameLoc);
12539           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12540           Invalid = true;
12541           break;
12542         }
12543   }
12544 
12545   if (RequireCompleteEnumDecl(ED, NameLoc))
12546     Invalid = true;
12547 
12548   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12549                                             EnumLoc, NameLoc, ED);
12550   UD->setAccess(AS);
12551   CurContext->addDecl(UD);
12552 
12553   if (Invalid) {
12554     UD->setInvalidDecl();
12555     return UD;
12556   }
12557 
12558   // Create the shadow decls for each enumerator
12559   for (EnumConstantDecl *EC : ED->enumerators()) {
12560     UsingShadowDecl *PrevDecl = nullptr;
12561     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12562     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12563                           ForVisibleRedeclaration);
12564     LookupName(Previous, S);
12565     FilterUsingLookup(S, Previous);
12566 
12567     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12568       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12569   }
12570 
12571   return UD;
12572 }
12573 
12574 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12575                                     ArrayRef<NamedDecl *> Expansions) {
12576   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12577          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12578          isa<UsingPackDecl>(InstantiatedFrom));
12579 
12580   auto *UPD =
12581       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12582   UPD->setAccess(InstantiatedFrom->getAccess());
12583   CurContext->addDecl(UPD);
12584   return UPD;
12585 }
12586 
12587 /// Additional checks for a using declaration referring to a constructor name.
12588 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12589   assert(!UD->hasTypename() && "expecting a constructor name");
12590 
12591   const Type *SourceType = UD->getQualifier()->getAsType();
12592   assert(SourceType &&
12593          "Using decl naming constructor doesn't have type in scope spec.");
12594   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12595 
12596   // Check whether the named type is a direct base class.
12597   bool AnyDependentBases = false;
12598   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12599                                       AnyDependentBases);
12600   if (!Base && !AnyDependentBases) {
12601     Diag(UD->getUsingLoc(),
12602          diag::err_using_decl_constructor_not_in_direct_base)
12603       << UD->getNameInfo().getSourceRange()
12604       << QualType(SourceType, 0) << TargetClass;
12605     UD->setInvalidDecl();
12606     return true;
12607   }
12608 
12609   if (Base)
12610     Base->setInheritConstructors();
12611 
12612   return false;
12613 }
12614 
12615 /// Checks that the given using declaration is not an invalid
12616 /// redeclaration.  Note that this is checking only for the using decl
12617 /// itself, not for any ill-formedness among the UsingShadowDecls.
12618 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12619                                        bool HasTypenameKeyword,
12620                                        const CXXScopeSpec &SS,
12621                                        SourceLocation NameLoc,
12622                                        const LookupResult &Prev) {
12623   NestedNameSpecifier *Qual = SS.getScopeRep();
12624 
12625   // C++03 [namespace.udecl]p8:
12626   // C++0x [namespace.udecl]p10:
12627   //   A using-declaration is a declaration and can therefore be used
12628   //   repeatedly where (and only where) multiple declarations are
12629   //   allowed.
12630   //
12631   // That's in non-member contexts.
12632   if (!CurContext->getRedeclContext()->isRecord()) {
12633     // A dependent qualifier outside a class can only ever resolve to an
12634     // enumeration type. Therefore it conflicts with any other non-type
12635     // declaration in the same scope.
12636     // FIXME: How should we check for dependent type-type conflicts at block
12637     // scope?
12638     if (Qual->isDependent() && !HasTypenameKeyword) {
12639       for (auto *D : Prev) {
12640         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12641           bool OldCouldBeEnumerator =
12642               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12643           Diag(NameLoc,
12644                OldCouldBeEnumerator ? diag::err_redefinition
12645                                     : diag::err_redefinition_different_kind)
12646               << Prev.getLookupName();
12647           Diag(D->getLocation(), diag::note_previous_definition);
12648           return true;
12649         }
12650       }
12651     }
12652     return false;
12653   }
12654 
12655   const NestedNameSpecifier *CNNS =
12656       Context.getCanonicalNestedNameSpecifier(Qual);
12657   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12658     NamedDecl *D = *I;
12659 
12660     bool DTypename;
12661     NestedNameSpecifier *DQual;
12662     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12663       DTypename = UD->hasTypename();
12664       DQual = UD->getQualifier();
12665     } else if (UnresolvedUsingValueDecl *UD
12666                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12667       DTypename = false;
12668       DQual = UD->getQualifier();
12669     } else if (UnresolvedUsingTypenameDecl *UD
12670                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12671       DTypename = true;
12672       DQual = UD->getQualifier();
12673     } else continue;
12674 
12675     // using decls differ if one says 'typename' and the other doesn't.
12676     // FIXME: non-dependent using decls?
12677     if (HasTypenameKeyword != DTypename) continue;
12678 
12679     // using decls differ if they name different scopes (but note that
12680     // template instantiation can cause this check to trigger when it
12681     // didn't before instantiation).
12682     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12683       continue;
12684 
12685     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12686     Diag(D->getLocation(), diag::note_using_decl) << 1;
12687     return true;
12688   }
12689 
12690   return false;
12691 }
12692 
12693 /// Checks that the given nested-name qualifier used in a using decl
12694 /// in the current context is appropriately related to the current
12695 /// scope.  If an error is found, diagnoses it and returns true.
12696 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12697 /// result of that lookup. UD is likewise nullptr, except when we have an
12698 /// already-populated UsingDecl whose shadow decls contain the same information
12699 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12700 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12701                                    const CXXScopeSpec &SS,
12702                                    const DeclarationNameInfo &NameInfo,
12703                                    SourceLocation NameLoc,
12704                                    const LookupResult *R, const UsingDecl *UD) {
12705   DeclContext *NamedContext = computeDeclContext(SS);
12706   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12707          "resolvable context must have exactly one set of decls");
12708 
12709   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12710   // relationship.
12711   bool Cxx20Enumerator = false;
12712   if (NamedContext) {
12713     EnumConstantDecl *EC = nullptr;
12714     if (R)
12715       EC = R->getAsSingle<EnumConstantDecl>();
12716     else if (UD && UD->shadow_size() == 1)
12717       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12718     if (EC)
12719       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12720 
12721     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12722       // C++14 [namespace.udecl]p7:
12723       // A using-declaration shall not name a scoped enumerator.
12724       // C++20 p1099 permits enumerators.
12725       if (EC && R && ED->isScoped())
12726         Diag(SS.getBeginLoc(),
12727              getLangOpts().CPlusPlus20
12728                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12729                  : diag::ext_using_decl_scoped_enumerator)
12730             << SS.getRange();
12731 
12732       // We want to consider the scope of the enumerator
12733       NamedContext = ED->getDeclContext();
12734     }
12735   }
12736 
12737   if (!CurContext->isRecord()) {
12738     // C++03 [namespace.udecl]p3:
12739     // C++0x [namespace.udecl]p8:
12740     //   A using-declaration for a class member shall be a member-declaration.
12741     // C++20 [namespace.udecl]p7
12742     //   ... other than an enumerator ...
12743 
12744     // If we weren't able to compute a valid scope, it might validly be a
12745     // dependent class or enumeration scope. If we have a 'typename' keyword,
12746     // the scope must resolve to a class type.
12747     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12748                      : !HasTypename)
12749       return false; // OK
12750 
12751     Diag(NameLoc,
12752          Cxx20Enumerator
12753              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12754              : diag::err_using_decl_can_not_refer_to_class_member)
12755         << SS.getRange();
12756 
12757     if (Cxx20Enumerator)
12758       return false; // OK
12759 
12760     auto *RD = NamedContext
12761                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12762                    : nullptr;
12763     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12764       // See if there's a helpful fixit
12765 
12766       if (!R) {
12767         // We will have already diagnosed the problem on the template
12768         // definition,  Maybe we should do so again?
12769       } else if (R->getAsSingle<TypeDecl>()) {
12770         if (getLangOpts().CPlusPlus11) {
12771           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12772           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12773             << 0 // alias declaration
12774             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12775                                           NameInfo.getName().getAsString() +
12776                                               " = ");
12777         } else {
12778           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12779           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12780           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12781             << 1 // typedef declaration
12782             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12783             << FixItHint::CreateInsertion(
12784                    InsertLoc, " " + NameInfo.getName().getAsString());
12785         }
12786       } else if (R->getAsSingle<VarDecl>()) {
12787         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12788         // repeating the type of the static data member here.
12789         FixItHint FixIt;
12790         if (getLangOpts().CPlusPlus11) {
12791           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12792           FixIt = FixItHint::CreateReplacement(
12793               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12794         }
12795 
12796         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12797           << 2 // reference declaration
12798           << FixIt;
12799       } else if (R->getAsSingle<EnumConstantDecl>()) {
12800         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12801         // repeating the type of the enumeration here, and we can't do so if
12802         // the type is anonymous.
12803         FixItHint FixIt;
12804         if (getLangOpts().CPlusPlus11) {
12805           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12806           FixIt = FixItHint::CreateReplacement(
12807               UsingLoc,
12808               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12809         }
12810 
12811         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12812           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12813           << FixIt;
12814       }
12815     }
12816 
12817     return true; // Fail
12818   }
12819 
12820   // If the named context is dependent, we can't decide much.
12821   if (!NamedContext) {
12822     // FIXME: in C++0x, we can diagnose if we can prove that the
12823     // nested-name-specifier does not refer to a base class, which is
12824     // still possible in some cases.
12825 
12826     // Otherwise we have to conservatively report that things might be
12827     // okay.
12828     return false;
12829   }
12830 
12831   // The current scope is a record.
12832   if (!NamedContext->isRecord()) {
12833     // Ideally this would point at the last name in the specifier,
12834     // but we don't have that level of source info.
12835     Diag(SS.getBeginLoc(),
12836          Cxx20Enumerator
12837              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12838              : diag::err_using_decl_nested_name_specifier_is_not_class)
12839         << SS.getScopeRep() << SS.getRange();
12840 
12841     if (Cxx20Enumerator)
12842       return false; // OK
12843 
12844     return true;
12845   }
12846 
12847   if (!NamedContext->isDependentContext() &&
12848       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12849     return true;
12850 
12851   if (getLangOpts().CPlusPlus11) {
12852     // C++11 [namespace.udecl]p3:
12853     //   In a using-declaration used as a member-declaration, the
12854     //   nested-name-specifier shall name a base class of the class
12855     //   being defined.
12856 
12857     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12858                                  cast<CXXRecordDecl>(NamedContext))) {
12859 
12860       if (Cxx20Enumerator) {
12861         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12862             << SS.getRange();
12863         return false;
12864       }
12865 
12866       if (CurContext == NamedContext) {
12867         Diag(SS.getBeginLoc(),
12868              diag::err_using_decl_nested_name_specifier_is_current_class)
12869             << SS.getRange();
12870         return !getLangOpts().CPlusPlus20;
12871       }
12872 
12873       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12874         Diag(SS.getBeginLoc(),
12875              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12876             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12877             << SS.getRange();
12878       }
12879       return true;
12880     }
12881 
12882     return false;
12883   }
12884 
12885   // C++03 [namespace.udecl]p4:
12886   //   A using-declaration used as a member-declaration shall refer
12887   //   to a member of a base class of the class being defined [etc.].
12888 
12889   // Salient point: SS doesn't have to name a base class as long as
12890   // lookup only finds members from base classes.  Therefore we can
12891   // diagnose here only if we can prove that that can't happen,
12892   // i.e. if the class hierarchies provably don't intersect.
12893 
12894   // TODO: it would be nice if "definitely valid" results were cached
12895   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12896   // need to be repeated.
12897 
12898   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12899   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12900     Bases.insert(Base);
12901     return true;
12902   };
12903 
12904   // Collect all bases. Return false if we find a dependent base.
12905   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12906     return false;
12907 
12908   // Returns true if the base is dependent or is one of the accumulated base
12909   // classes.
12910   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12911     return !Bases.count(Base);
12912   };
12913 
12914   // Return false if the class has a dependent base or if it or one
12915   // of its bases is present in the base set of the current context.
12916   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12917       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12918     return false;
12919 
12920   Diag(SS.getRange().getBegin(),
12921        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12922     << SS.getScopeRep()
12923     << cast<CXXRecordDecl>(CurContext)
12924     << SS.getRange();
12925 
12926   return true;
12927 }
12928 
12929 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12930                                   MultiTemplateParamsArg TemplateParamLists,
12931                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12932                                   const ParsedAttributesView &AttrList,
12933                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12934   // Skip up to the relevant declaration scope.
12935   while (S->isTemplateParamScope())
12936     S = S->getParent();
12937   assert((S->getFlags() & Scope::DeclScope) &&
12938          "got alias-declaration outside of declaration scope");
12939 
12940   if (Type.isInvalid())
12941     return nullptr;
12942 
12943   bool Invalid = false;
12944   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12945   TypeSourceInfo *TInfo = nullptr;
12946   GetTypeFromParser(Type.get(), &TInfo);
12947 
12948   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12949     return nullptr;
12950 
12951   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12952                                       UPPC_DeclarationType)) {
12953     Invalid = true;
12954     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12955                                              TInfo->getTypeLoc().getBeginLoc());
12956   }
12957 
12958   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12959                         TemplateParamLists.size()
12960                             ? forRedeclarationInCurContext()
12961                             : ForVisibleRedeclaration);
12962   LookupName(Previous, S);
12963 
12964   // Warn about shadowing the name of a template parameter.
12965   if (Previous.isSingleResult() &&
12966       Previous.getFoundDecl()->isTemplateParameter()) {
12967     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12968     Previous.clear();
12969   }
12970 
12971   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12972          "name in alias declaration must be an identifier");
12973   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12974                                                Name.StartLocation,
12975                                                Name.Identifier, TInfo);
12976 
12977   NewTD->setAccess(AS);
12978 
12979   if (Invalid)
12980     NewTD->setInvalidDecl();
12981 
12982   ProcessDeclAttributeList(S, NewTD, AttrList);
12983   AddPragmaAttributes(S, NewTD);
12984 
12985   CheckTypedefForVariablyModifiedType(S, NewTD);
12986   Invalid |= NewTD->isInvalidDecl();
12987 
12988   bool Redeclaration = false;
12989 
12990   NamedDecl *NewND;
12991   if (TemplateParamLists.size()) {
12992     TypeAliasTemplateDecl *OldDecl = nullptr;
12993     TemplateParameterList *OldTemplateParams = nullptr;
12994 
12995     if (TemplateParamLists.size() != 1) {
12996       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12997         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12998          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12999     }
13000     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13001 
13002     // Check that we can declare a template here.
13003     if (CheckTemplateDeclScope(S, TemplateParams))
13004       return nullptr;
13005 
13006     // Only consider previous declarations in the same scope.
13007     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13008                          /*ExplicitInstantiationOrSpecialization*/false);
13009     if (!Previous.empty()) {
13010       Redeclaration = true;
13011 
13012       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13013       if (!OldDecl && !Invalid) {
13014         Diag(UsingLoc, diag::err_redefinition_different_kind)
13015           << Name.Identifier;
13016 
13017         NamedDecl *OldD = Previous.getRepresentativeDecl();
13018         if (OldD->getLocation().isValid())
13019           Diag(OldD->getLocation(), diag::note_previous_definition);
13020 
13021         Invalid = true;
13022       }
13023 
13024       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13025         if (TemplateParameterListsAreEqual(TemplateParams,
13026                                            OldDecl->getTemplateParameters(),
13027                                            /*Complain=*/true,
13028                                            TPL_TemplateMatch))
13029           OldTemplateParams =
13030               OldDecl->getMostRecentDecl()->getTemplateParameters();
13031         else
13032           Invalid = true;
13033 
13034         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13035         if (!Invalid &&
13036             !Context.hasSameType(OldTD->getUnderlyingType(),
13037                                  NewTD->getUnderlyingType())) {
13038           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13039           // but we can't reasonably accept it.
13040           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13041             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13042           if (OldTD->getLocation().isValid())
13043             Diag(OldTD->getLocation(), diag::note_previous_definition);
13044           Invalid = true;
13045         }
13046       }
13047     }
13048 
13049     // Merge any previous default template arguments into our parameters,
13050     // and check the parameter list.
13051     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13052                                    TPC_TypeAliasTemplate))
13053       return nullptr;
13054 
13055     TypeAliasTemplateDecl *NewDecl =
13056       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13057                                     Name.Identifier, TemplateParams,
13058                                     NewTD);
13059     NewTD->setDescribedAliasTemplate(NewDecl);
13060 
13061     NewDecl->setAccess(AS);
13062 
13063     if (Invalid)
13064       NewDecl->setInvalidDecl();
13065     else if (OldDecl) {
13066       NewDecl->setPreviousDecl(OldDecl);
13067       CheckRedeclarationInModule(NewDecl, OldDecl);
13068     }
13069 
13070     NewND = NewDecl;
13071   } else {
13072     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13073       setTagNameForLinkagePurposes(TD, NewTD);
13074       handleTagNumbering(TD, S);
13075     }
13076     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13077     NewND = NewTD;
13078   }
13079 
13080   PushOnScopeChains(NewND, S);
13081   ActOnDocumentableDecl(NewND);
13082   return NewND;
13083 }
13084 
13085 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13086                                    SourceLocation AliasLoc,
13087                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13088                                    SourceLocation IdentLoc,
13089                                    IdentifierInfo *Ident) {
13090 
13091   // Lookup the namespace name.
13092   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13093   LookupParsedName(R, S, &SS);
13094 
13095   if (R.isAmbiguous())
13096     return nullptr;
13097 
13098   if (R.empty()) {
13099     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13100       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13101       return nullptr;
13102     }
13103   }
13104   assert(!R.isAmbiguous() && !R.empty());
13105   NamedDecl *ND = R.getRepresentativeDecl();
13106 
13107   // Check if we have a previous declaration with the same name.
13108   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13109                      ForVisibleRedeclaration);
13110   LookupName(PrevR, S);
13111 
13112   // Check we're not shadowing a template parameter.
13113   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13114     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13115     PrevR.clear();
13116   }
13117 
13118   // Filter out any other lookup result from an enclosing scope.
13119   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13120                        /*AllowInlineNamespace*/false);
13121 
13122   // Find the previous declaration and check that we can redeclare it.
13123   NamespaceAliasDecl *Prev = nullptr;
13124   if (PrevR.isSingleResult()) {
13125     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13126     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13127       // We already have an alias with the same name that points to the same
13128       // namespace; check that it matches.
13129       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13130         Prev = AD;
13131       } else if (isVisible(PrevDecl)) {
13132         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13133           << Alias;
13134         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13135           << AD->getNamespace();
13136         return nullptr;
13137       }
13138     } else if (isVisible(PrevDecl)) {
13139       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13140                             ? diag::err_redefinition
13141                             : diag::err_redefinition_different_kind;
13142       Diag(AliasLoc, DiagID) << Alias;
13143       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13144       return nullptr;
13145     }
13146   }
13147 
13148   // The use of a nested name specifier may trigger deprecation warnings.
13149   DiagnoseUseOfDecl(ND, IdentLoc);
13150 
13151   NamespaceAliasDecl *AliasDecl =
13152     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13153                                Alias, SS.getWithLocInContext(Context),
13154                                IdentLoc, ND);
13155   if (Prev)
13156     AliasDecl->setPreviousDecl(Prev);
13157 
13158   PushOnScopeChains(AliasDecl, S);
13159   return AliasDecl;
13160 }
13161 
13162 namespace {
13163 struct SpecialMemberExceptionSpecInfo
13164     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13165   SourceLocation Loc;
13166   Sema::ImplicitExceptionSpecification ExceptSpec;
13167 
13168   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13169                                  Sema::CXXSpecialMember CSM,
13170                                  Sema::InheritedConstructorInfo *ICI,
13171                                  SourceLocation Loc)
13172       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13173 
13174   bool visitBase(CXXBaseSpecifier *Base);
13175   bool visitField(FieldDecl *FD);
13176 
13177   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13178                            unsigned Quals);
13179 
13180   void visitSubobjectCall(Subobject Subobj,
13181                           Sema::SpecialMemberOverloadResult SMOR);
13182 };
13183 }
13184 
13185 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13186   auto *RT = Base->getType()->getAs<RecordType>();
13187   if (!RT)
13188     return false;
13189 
13190   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13191   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13192   if (auto *BaseCtor = SMOR.getMethod()) {
13193     visitSubobjectCall(Base, BaseCtor);
13194     return false;
13195   }
13196 
13197   visitClassSubobject(BaseClass, Base, 0);
13198   return false;
13199 }
13200 
13201 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13202   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13203     Expr *E = FD->getInClassInitializer();
13204     if (!E)
13205       // FIXME: It's a little wasteful to build and throw away a
13206       // CXXDefaultInitExpr here.
13207       // FIXME: We should have a single context note pointing at Loc, and
13208       // this location should be MD->getLocation() instead, since that's
13209       // the location where we actually use the default init expression.
13210       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13211     if (E)
13212       ExceptSpec.CalledExpr(E);
13213   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13214                             ->getAs<RecordType>()) {
13215     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13216                         FD->getType().getCVRQualifiers());
13217   }
13218   return false;
13219 }
13220 
13221 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13222                                                          Subobject Subobj,
13223                                                          unsigned Quals) {
13224   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13225   bool IsMutable = Field && Field->isMutable();
13226   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13227 }
13228 
13229 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13230     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13231   // Note, if lookup fails, it doesn't matter what exception specification we
13232   // choose because the special member will be deleted.
13233   if (CXXMethodDecl *MD = SMOR.getMethod())
13234     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13235 }
13236 
13237 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13238   llvm::APSInt Result;
13239   ExprResult Converted = CheckConvertedConstantExpression(
13240       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13241   ExplicitSpec.setExpr(Converted.get());
13242   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13243     ExplicitSpec.setKind(Result.getBoolValue()
13244                              ? ExplicitSpecKind::ResolvedTrue
13245                              : ExplicitSpecKind::ResolvedFalse);
13246     return true;
13247   }
13248   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13249   return false;
13250 }
13251 
13252 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13253   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13254   if (!ExplicitExpr->isTypeDependent())
13255     tryResolveExplicitSpecifier(ES);
13256   return ES;
13257 }
13258 
13259 static Sema::ImplicitExceptionSpecification
13260 ComputeDefaultedSpecialMemberExceptionSpec(
13261     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13262     Sema::InheritedConstructorInfo *ICI) {
13263   ComputingExceptionSpec CES(S, MD, Loc);
13264 
13265   CXXRecordDecl *ClassDecl = MD->getParent();
13266 
13267   // C++ [except.spec]p14:
13268   //   An implicitly declared special member function (Clause 12) shall have an
13269   //   exception-specification. [...]
13270   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13271   if (ClassDecl->isInvalidDecl())
13272     return Info.ExceptSpec;
13273 
13274   // FIXME: If this diagnostic fires, we're probably missing a check for
13275   // attempting to resolve an exception specification before it's known
13276   // at a higher level.
13277   if (S.RequireCompleteType(MD->getLocation(),
13278                             S.Context.getRecordType(ClassDecl),
13279                             diag::err_exception_spec_incomplete_type))
13280     return Info.ExceptSpec;
13281 
13282   // C++1z [except.spec]p7:
13283   //   [Look for exceptions thrown by] a constructor selected [...] to
13284   //   initialize a potentially constructed subobject,
13285   // C++1z [except.spec]p8:
13286   //   The exception specification for an implicitly-declared destructor, or a
13287   //   destructor without a noexcept-specifier, is potentially-throwing if and
13288   //   only if any of the destructors for any of its potentially constructed
13289   //   subojects is potentially throwing.
13290   // FIXME: We respect the first rule but ignore the "potentially constructed"
13291   // in the second rule to resolve a core issue (no number yet) that would have
13292   // us reject:
13293   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13294   //   struct B : A {};
13295   //   struct C : B { void f(); };
13296   // ... due to giving B::~B() a non-throwing exception specification.
13297   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13298                                 : Info.VisitAllBases);
13299 
13300   return Info.ExceptSpec;
13301 }
13302 
13303 namespace {
13304 /// RAII object to register a special member as being currently declared.
13305 struct DeclaringSpecialMember {
13306   Sema &S;
13307   Sema::SpecialMemberDecl D;
13308   Sema::ContextRAII SavedContext;
13309   bool WasAlreadyBeingDeclared;
13310 
13311   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13312       : S(S), D(RD, CSM), SavedContext(S, RD) {
13313     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13314     if (WasAlreadyBeingDeclared)
13315       // This almost never happens, but if it does, ensure that our cache
13316       // doesn't contain a stale result.
13317       S.SpecialMemberCache.clear();
13318     else {
13319       // Register a note to be produced if we encounter an error while
13320       // declaring the special member.
13321       Sema::CodeSynthesisContext Ctx;
13322       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13323       // FIXME: We don't have a location to use here. Using the class's
13324       // location maintains the fiction that we declare all special members
13325       // with the class, but (1) it's not clear that lying about that helps our
13326       // users understand what's going on, and (2) there may be outer contexts
13327       // on the stack (some of which are relevant) and printing them exposes
13328       // our lies.
13329       Ctx.PointOfInstantiation = RD->getLocation();
13330       Ctx.Entity = RD;
13331       Ctx.SpecialMember = CSM;
13332       S.pushCodeSynthesisContext(Ctx);
13333     }
13334   }
13335   ~DeclaringSpecialMember() {
13336     if (!WasAlreadyBeingDeclared) {
13337       S.SpecialMembersBeingDeclared.erase(D);
13338       S.popCodeSynthesisContext();
13339     }
13340   }
13341 
13342   /// Are we already trying to declare this special member?
13343   bool isAlreadyBeingDeclared() const {
13344     return WasAlreadyBeingDeclared;
13345   }
13346 };
13347 }
13348 
13349 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13350   // Look up any existing declarations, but don't trigger declaration of all
13351   // implicit special members with this name.
13352   DeclarationName Name = FD->getDeclName();
13353   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13354                  ForExternalRedeclaration);
13355   for (auto *D : FD->getParent()->lookup(Name))
13356     if (auto *Acceptable = R.getAcceptableDecl(D))
13357       R.addDecl(Acceptable);
13358   R.resolveKind();
13359   R.suppressDiagnostics();
13360 
13361   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13362                            FD->isThisDeclarationADefinition());
13363 }
13364 
13365 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13366                                           QualType ResultTy,
13367                                           ArrayRef<QualType> Args) {
13368   // Build an exception specification pointing back at this constructor.
13369   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13370 
13371   LangAS AS = getDefaultCXXMethodAddrSpace();
13372   if (AS != LangAS::Default) {
13373     EPI.TypeQuals.addAddressSpace(AS);
13374   }
13375 
13376   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13377   SpecialMem->setType(QT);
13378 
13379   // During template instantiation of implicit special member functions we need
13380   // a reliable TypeSourceInfo for the function prototype in order to allow
13381   // functions to be substituted.
13382   if (inTemplateInstantiation() &&
13383       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13384     TypeSourceInfo *TSI =
13385         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13386     SpecialMem->setTypeSourceInfo(TSI);
13387   }
13388 }
13389 
13390 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13391                                                      CXXRecordDecl *ClassDecl) {
13392   // C++ [class.ctor]p5:
13393   //   A default constructor for a class X is a constructor of class X
13394   //   that can be called without an argument. If there is no
13395   //   user-declared constructor for class X, a default constructor is
13396   //   implicitly declared. An implicitly-declared default constructor
13397   //   is an inline public member of its class.
13398   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13399          "Should not build implicit default constructor!");
13400 
13401   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13402   if (DSM.isAlreadyBeingDeclared())
13403     return nullptr;
13404 
13405   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13406                                                      CXXDefaultConstructor,
13407                                                      false);
13408 
13409   // Create the actual constructor declaration.
13410   CanQualType ClassType
13411     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13412   SourceLocation ClassLoc = ClassDecl->getLocation();
13413   DeclarationName Name
13414     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13415   DeclarationNameInfo NameInfo(Name, ClassLoc);
13416   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13417       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13418       /*TInfo=*/nullptr, ExplicitSpecifier(),
13419       getCurFPFeatures().isFPConstrained(),
13420       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13421       Constexpr ? ConstexprSpecKind::Constexpr
13422                 : ConstexprSpecKind::Unspecified);
13423   DefaultCon->setAccess(AS_public);
13424   DefaultCon->setDefaulted();
13425 
13426   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13427 
13428   if (getLangOpts().CUDA)
13429     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13430                                             DefaultCon,
13431                                             /* ConstRHS */ false,
13432                                             /* Diagnose */ false);
13433 
13434   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13435   // constructors is easy to compute.
13436   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13437 
13438   // Note that we have declared this constructor.
13439   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13440 
13441   Scope *S = getScopeForContext(ClassDecl);
13442   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13443 
13444   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13445     SetDeclDeleted(DefaultCon, ClassLoc);
13446 
13447   if (S)
13448     PushOnScopeChains(DefaultCon, S, false);
13449   ClassDecl->addDecl(DefaultCon);
13450 
13451   return DefaultCon;
13452 }
13453 
13454 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13455                                             CXXConstructorDecl *Constructor) {
13456   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13457           !Constructor->doesThisDeclarationHaveABody() &&
13458           !Constructor->isDeleted()) &&
13459     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13460   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13461     return;
13462 
13463   CXXRecordDecl *ClassDecl = Constructor->getParent();
13464   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13465 
13466   SynthesizedFunctionScope Scope(*this, Constructor);
13467 
13468   // The exception specification is needed because we are defining the
13469   // function.
13470   ResolveExceptionSpec(CurrentLocation,
13471                        Constructor->getType()->castAs<FunctionProtoType>());
13472   MarkVTableUsed(CurrentLocation, ClassDecl);
13473 
13474   // Add a context note for diagnostics produced after this point.
13475   Scope.addContextNote(CurrentLocation);
13476 
13477   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13478     Constructor->setInvalidDecl();
13479     return;
13480   }
13481 
13482   SourceLocation Loc = Constructor->getEndLoc().isValid()
13483                            ? Constructor->getEndLoc()
13484                            : Constructor->getLocation();
13485   Constructor->setBody(new (Context) CompoundStmt(Loc));
13486   Constructor->markUsed(Context);
13487 
13488   if (ASTMutationListener *L = getASTMutationListener()) {
13489     L->CompletedImplicitDefinition(Constructor);
13490   }
13491 
13492   DiagnoseUninitializedFields(*this, Constructor);
13493 }
13494 
13495 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13496   // Perform any delayed checks on exception specifications.
13497   CheckDelayedMemberExceptionSpecs();
13498 }
13499 
13500 /// Find or create the fake constructor we synthesize to model constructing an
13501 /// object of a derived class via a constructor of a base class.
13502 CXXConstructorDecl *
13503 Sema::findInheritingConstructor(SourceLocation Loc,
13504                                 CXXConstructorDecl *BaseCtor,
13505                                 ConstructorUsingShadowDecl *Shadow) {
13506   CXXRecordDecl *Derived = Shadow->getParent();
13507   SourceLocation UsingLoc = Shadow->getLocation();
13508 
13509   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13510   // For now we use the name of the base class constructor as a member of the
13511   // derived class to indicate a (fake) inherited constructor name.
13512   DeclarationName Name = BaseCtor->getDeclName();
13513 
13514   // Check to see if we already have a fake constructor for this inherited
13515   // constructor call.
13516   for (NamedDecl *Ctor : Derived->lookup(Name))
13517     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13518                                ->getInheritedConstructor()
13519                                .getConstructor(),
13520                            BaseCtor))
13521       return cast<CXXConstructorDecl>(Ctor);
13522 
13523   DeclarationNameInfo NameInfo(Name, UsingLoc);
13524   TypeSourceInfo *TInfo =
13525       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13526   FunctionProtoTypeLoc ProtoLoc =
13527       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13528 
13529   // Check the inherited constructor is valid and find the list of base classes
13530   // from which it was inherited.
13531   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13532 
13533   bool Constexpr =
13534       BaseCtor->isConstexpr() &&
13535       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13536                                         false, BaseCtor, &ICI);
13537 
13538   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13539       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13540       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13541       /*isInline=*/true,
13542       /*isImplicitlyDeclared=*/true,
13543       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13544       InheritedConstructor(Shadow, BaseCtor),
13545       BaseCtor->getTrailingRequiresClause());
13546   if (Shadow->isInvalidDecl())
13547     DerivedCtor->setInvalidDecl();
13548 
13549   // Build an unevaluated exception specification for this fake constructor.
13550   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13551   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13552   EPI.ExceptionSpec.Type = EST_Unevaluated;
13553   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13554   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13555                                                FPT->getParamTypes(), EPI));
13556 
13557   // Build the parameter declarations.
13558   SmallVector<ParmVarDecl *, 16> ParamDecls;
13559   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13560     TypeSourceInfo *TInfo =
13561         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13562     ParmVarDecl *PD = ParmVarDecl::Create(
13563         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13564         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13565     PD->setScopeInfo(0, I);
13566     PD->setImplicit();
13567     // Ensure attributes are propagated onto parameters (this matters for
13568     // format, pass_object_size, ...).
13569     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13570     ParamDecls.push_back(PD);
13571     ProtoLoc.setParam(I, PD);
13572   }
13573 
13574   // Set up the new constructor.
13575   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13576   DerivedCtor->setAccess(BaseCtor->getAccess());
13577   DerivedCtor->setParams(ParamDecls);
13578   Derived->addDecl(DerivedCtor);
13579 
13580   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13581     SetDeclDeleted(DerivedCtor, UsingLoc);
13582 
13583   return DerivedCtor;
13584 }
13585 
13586 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13587   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13588                                Ctor->getInheritedConstructor().getShadowDecl());
13589   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13590                             /*Diagnose*/true);
13591 }
13592 
13593 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13594                                        CXXConstructorDecl *Constructor) {
13595   CXXRecordDecl *ClassDecl = Constructor->getParent();
13596   assert(Constructor->getInheritedConstructor() &&
13597          !Constructor->doesThisDeclarationHaveABody() &&
13598          !Constructor->isDeleted());
13599   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13600     return;
13601 
13602   // Initializations are performed "as if by a defaulted default constructor",
13603   // so enter the appropriate scope.
13604   SynthesizedFunctionScope Scope(*this, Constructor);
13605 
13606   // The exception specification is needed because we are defining the
13607   // function.
13608   ResolveExceptionSpec(CurrentLocation,
13609                        Constructor->getType()->castAs<FunctionProtoType>());
13610   MarkVTableUsed(CurrentLocation, ClassDecl);
13611 
13612   // Add a context note for diagnostics produced after this point.
13613   Scope.addContextNote(CurrentLocation);
13614 
13615   ConstructorUsingShadowDecl *Shadow =
13616       Constructor->getInheritedConstructor().getShadowDecl();
13617   CXXConstructorDecl *InheritedCtor =
13618       Constructor->getInheritedConstructor().getConstructor();
13619 
13620   // [class.inhctor.init]p1:
13621   //   initialization proceeds as if a defaulted default constructor is used to
13622   //   initialize the D object and each base class subobject from which the
13623   //   constructor was inherited
13624 
13625   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13626   CXXRecordDecl *RD = Shadow->getParent();
13627   SourceLocation InitLoc = Shadow->getLocation();
13628 
13629   // Build explicit initializers for all base classes from which the
13630   // constructor was inherited.
13631   SmallVector<CXXCtorInitializer*, 8> Inits;
13632   for (bool VBase : {false, true}) {
13633     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13634       if (B.isVirtual() != VBase)
13635         continue;
13636 
13637       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13638       if (!BaseRD)
13639         continue;
13640 
13641       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13642       if (!BaseCtor.first)
13643         continue;
13644 
13645       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13646       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13647           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13648 
13649       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13650       Inits.push_back(new (Context) CXXCtorInitializer(
13651           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13652           SourceLocation()));
13653     }
13654   }
13655 
13656   // We now proceed as if for a defaulted default constructor, with the relevant
13657   // initializers replaced.
13658 
13659   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13660     Constructor->setInvalidDecl();
13661     return;
13662   }
13663 
13664   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13665   Constructor->markUsed(Context);
13666 
13667   if (ASTMutationListener *L = getASTMutationListener()) {
13668     L->CompletedImplicitDefinition(Constructor);
13669   }
13670 
13671   DiagnoseUninitializedFields(*this, Constructor);
13672 }
13673 
13674 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13675   // C++ [class.dtor]p2:
13676   //   If a class has no user-declared destructor, a destructor is
13677   //   declared implicitly. An implicitly-declared destructor is an
13678   //   inline public member of its class.
13679   assert(ClassDecl->needsImplicitDestructor());
13680 
13681   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13682   if (DSM.isAlreadyBeingDeclared())
13683     return nullptr;
13684 
13685   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13686                                                      CXXDestructor,
13687                                                      false);
13688 
13689   // Create the actual destructor declaration.
13690   CanQualType ClassType
13691     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13692   SourceLocation ClassLoc = ClassDecl->getLocation();
13693   DeclarationName Name
13694     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13695   DeclarationNameInfo NameInfo(Name, ClassLoc);
13696   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13697       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13698       getCurFPFeatures().isFPConstrained(),
13699       /*isInline=*/true,
13700       /*isImplicitlyDeclared=*/true,
13701       Constexpr ? ConstexprSpecKind::Constexpr
13702                 : ConstexprSpecKind::Unspecified);
13703   Destructor->setAccess(AS_public);
13704   Destructor->setDefaulted();
13705 
13706   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13707 
13708   if (getLangOpts().CUDA)
13709     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13710                                             Destructor,
13711                                             /* ConstRHS */ false,
13712                                             /* Diagnose */ false);
13713 
13714   // We don't need to use SpecialMemberIsTrivial here; triviality for
13715   // destructors is easy to compute.
13716   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13717   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13718                                 ClassDecl->hasTrivialDestructorForCall());
13719 
13720   // Note that we have declared this destructor.
13721   ++getASTContext().NumImplicitDestructorsDeclared;
13722 
13723   Scope *S = getScopeForContext(ClassDecl);
13724   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13725 
13726   // We can't check whether an implicit destructor is deleted before we complete
13727   // the definition of the class, because its validity depends on the alignment
13728   // of the class. We'll check this from ActOnFields once the class is complete.
13729   if (ClassDecl->isCompleteDefinition() &&
13730       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13731     SetDeclDeleted(Destructor, ClassLoc);
13732 
13733   // Introduce this destructor into its scope.
13734   if (S)
13735     PushOnScopeChains(Destructor, S, false);
13736   ClassDecl->addDecl(Destructor);
13737 
13738   return Destructor;
13739 }
13740 
13741 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13742                                     CXXDestructorDecl *Destructor) {
13743   assert((Destructor->isDefaulted() &&
13744           !Destructor->doesThisDeclarationHaveABody() &&
13745           !Destructor->isDeleted()) &&
13746          "DefineImplicitDestructor - call it for implicit default dtor");
13747   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13748     return;
13749 
13750   CXXRecordDecl *ClassDecl = Destructor->getParent();
13751   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13752 
13753   SynthesizedFunctionScope Scope(*this, Destructor);
13754 
13755   // The exception specification is needed because we are defining the
13756   // function.
13757   ResolveExceptionSpec(CurrentLocation,
13758                        Destructor->getType()->castAs<FunctionProtoType>());
13759   MarkVTableUsed(CurrentLocation, ClassDecl);
13760 
13761   // Add a context note for diagnostics produced after this point.
13762   Scope.addContextNote(CurrentLocation);
13763 
13764   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13765                                          Destructor->getParent());
13766 
13767   if (CheckDestructor(Destructor)) {
13768     Destructor->setInvalidDecl();
13769     return;
13770   }
13771 
13772   SourceLocation Loc = Destructor->getEndLoc().isValid()
13773                            ? Destructor->getEndLoc()
13774                            : Destructor->getLocation();
13775   Destructor->setBody(new (Context) CompoundStmt(Loc));
13776   Destructor->markUsed(Context);
13777 
13778   if (ASTMutationListener *L = getASTMutationListener()) {
13779     L->CompletedImplicitDefinition(Destructor);
13780   }
13781 }
13782 
13783 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13784                                           CXXDestructorDecl *Destructor) {
13785   if (Destructor->isInvalidDecl())
13786     return;
13787 
13788   CXXRecordDecl *ClassDecl = Destructor->getParent();
13789   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13790          "implicit complete dtors unneeded outside MS ABI");
13791   assert(ClassDecl->getNumVBases() > 0 &&
13792          "complete dtor only exists for classes with vbases");
13793 
13794   SynthesizedFunctionScope Scope(*this, Destructor);
13795 
13796   // Add a context note for diagnostics produced after this point.
13797   Scope.addContextNote(CurrentLocation);
13798 
13799   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13800 }
13801 
13802 /// Perform any semantic analysis which needs to be delayed until all
13803 /// pending class member declarations have been parsed.
13804 void Sema::ActOnFinishCXXMemberDecls() {
13805   // If the context is an invalid C++ class, just suppress these checks.
13806   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13807     if (Record->isInvalidDecl()) {
13808       DelayedOverridingExceptionSpecChecks.clear();
13809       DelayedEquivalentExceptionSpecChecks.clear();
13810       return;
13811     }
13812     checkForMultipleExportedDefaultConstructors(*this, Record);
13813   }
13814 }
13815 
13816 void Sema::ActOnFinishCXXNonNestedClass() {
13817   referenceDLLExportedClassMethods();
13818 
13819   if (!DelayedDllExportMemberFunctions.empty()) {
13820     SmallVector<CXXMethodDecl*, 4> WorkList;
13821     std::swap(DelayedDllExportMemberFunctions, WorkList);
13822     for (CXXMethodDecl *M : WorkList) {
13823       DefineDefaultedFunction(*this, M, M->getLocation());
13824 
13825       // Pass the method to the consumer to get emitted. This is not necessary
13826       // for explicit instantiation definitions, as they will get emitted
13827       // anyway.
13828       if (M->getParent()->getTemplateSpecializationKind() !=
13829           TSK_ExplicitInstantiationDefinition)
13830         ActOnFinishInlineFunctionDef(M);
13831     }
13832   }
13833 }
13834 
13835 void Sema::referenceDLLExportedClassMethods() {
13836   if (!DelayedDllExportClasses.empty()) {
13837     // Calling ReferenceDllExportedMembers might cause the current function to
13838     // be called again, so use a local copy of DelayedDllExportClasses.
13839     SmallVector<CXXRecordDecl *, 4> WorkList;
13840     std::swap(DelayedDllExportClasses, WorkList);
13841     for (CXXRecordDecl *Class : WorkList)
13842       ReferenceDllExportedMembers(*this, Class);
13843   }
13844 }
13845 
13846 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13847   assert(getLangOpts().CPlusPlus11 &&
13848          "adjusting dtor exception specs was introduced in c++11");
13849 
13850   if (Destructor->isDependentContext())
13851     return;
13852 
13853   // C++11 [class.dtor]p3:
13854   //   A declaration of a destructor that does not have an exception-
13855   //   specification is implicitly considered to have the same exception-
13856   //   specification as an implicit declaration.
13857   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13858   if (DtorType->hasExceptionSpec())
13859     return;
13860 
13861   // Replace the destructor's type, building off the existing one. Fortunately,
13862   // the only thing of interest in the destructor type is its extended info.
13863   // The return and arguments are fixed.
13864   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13865   EPI.ExceptionSpec.Type = EST_Unevaluated;
13866   EPI.ExceptionSpec.SourceDecl = Destructor;
13867   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13868 
13869   // FIXME: If the destructor has a body that could throw, and the newly created
13870   // spec doesn't allow exceptions, we should emit a warning, because this
13871   // change in behavior can break conforming C++03 programs at runtime.
13872   // However, we don't have a body or an exception specification yet, so it
13873   // needs to be done somewhere else.
13874 }
13875 
13876 namespace {
13877 /// An abstract base class for all helper classes used in building the
13878 //  copy/move operators. These classes serve as factory functions and help us
13879 //  avoid using the same Expr* in the AST twice.
13880 class ExprBuilder {
13881   ExprBuilder(const ExprBuilder&) = delete;
13882   ExprBuilder &operator=(const ExprBuilder&) = delete;
13883 
13884 protected:
13885   static Expr *assertNotNull(Expr *E) {
13886     assert(E && "Expression construction must not fail.");
13887     return E;
13888   }
13889 
13890 public:
13891   ExprBuilder() {}
13892   virtual ~ExprBuilder() {}
13893 
13894   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13895 };
13896 
13897 class RefBuilder: public ExprBuilder {
13898   VarDecl *Var;
13899   QualType VarType;
13900 
13901 public:
13902   Expr *build(Sema &S, SourceLocation Loc) const override {
13903     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13904   }
13905 
13906   RefBuilder(VarDecl *Var, QualType VarType)
13907       : Var(Var), VarType(VarType) {}
13908 };
13909 
13910 class ThisBuilder: public ExprBuilder {
13911 public:
13912   Expr *build(Sema &S, SourceLocation Loc) const override {
13913     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13914   }
13915 };
13916 
13917 class CastBuilder: public ExprBuilder {
13918   const ExprBuilder &Builder;
13919   QualType Type;
13920   ExprValueKind Kind;
13921   const CXXCastPath &Path;
13922 
13923 public:
13924   Expr *build(Sema &S, SourceLocation Loc) const override {
13925     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13926                                              CK_UncheckedDerivedToBase, Kind,
13927                                              &Path).get());
13928   }
13929 
13930   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13931               const CXXCastPath &Path)
13932       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13933 };
13934 
13935 class DerefBuilder: public ExprBuilder {
13936   const ExprBuilder &Builder;
13937 
13938 public:
13939   Expr *build(Sema &S, SourceLocation Loc) const override {
13940     return assertNotNull(
13941         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13942   }
13943 
13944   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13945 };
13946 
13947 class MemberBuilder: public ExprBuilder {
13948   const ExprBuilder &Builder;
13949   QualType Type;
13950   CXXScopeSpec SS;
13951   bool IsArrow;
13952   LookupResult &MemberLookup;
13953 
13954 public:
13955   Expr *build(Sema &S, SourceLocation Loc) const override {
13956     return assertNotNull(S.BuildMemberReferenceExpr(
13957         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13958         nullptr, MemberLookup, nullptr, nullptr).get());
13959   }
13960 
13961   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13962                 LookupResult &MemberLookup)
13963       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13964         MemberLookup(MemberLookup) {}
13965 };
13966 
13967 class MoveCastBuilder: public ExprBuilder {
13968   const ExprBuilder &Builder;
13969 
13970 public:
13971   Expr *build(Sema &S, SourceLocation Loc) const override {
13972     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13973   }
13974 
13975   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13976 };
13977 
13978 class LvalueConvBuilder: public ExprBuilder {
13979   const ExprBuilder &Builder;
13980 
13981 public:
13982   Expr *build(Sema &S, SourceLocation Loc) const override {
13983     return assertNotNull(
13984         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13985   }
13986 
13987   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13988 };
13989 
13990 class SubscriptBuilder: public ExprBuilder {
13991   const ExprBuilder &Base;
13992   const ExprBuilder &Index;
13993 
13994 public:
13995   Expr *build(Sema &S, SourceLocation Loc) const override {
13996     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13997         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13998   }
13999 
14000   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14001       : Base(Base), Index(Index) {}
14002 };
14003 
14004 } // end anonymous namespace
14005 
14006 /// When generating a defaulted copy or move assignment operator, if a field
14007 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14008 /// do so. This optimization only applies for arrays of scalars, and for arrays
14009 /// of class type where the selected copy/move-assignment operator is trivial.
14010 static StmtResult
14011 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14012                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14013   // Compute the size of the memory buffer to be copied.
14014   QualType SizeType = S.Context.getSizeType();
14015   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14016                    S.Context.getTypeSizeInChars(T).getQuantity());
14017 
14018   // Take the address of the field references for "from" and "to". We
14019   // directly construct UnaryOperators here because semantic analysis
14020   // does not permit us to take the address of an xvalue.
14021   Expr *From = FromB.build(S, Loc);
14022   From = UnaryOperator::Create(
14023       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14024       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14025   Expr *To = ToB.build(S, Loc);
14026   To = UnaryOperator::Create(
14027       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14028       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14029 
14030   const Type *E = T->getBaseElementTypeUnsafe();
14031   bool NeedsCollectableMemCpy =
14032       E->isRecordType() &&
14033       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14034 
14035   // Create a reference to the __builtin_objc_memmove_collectable function
14036   StringRef MemCpyName = NeedsCollectableMemCpy ?
14037     "__builtin_objc_memmove_collectable" :
14038     "__builtin_memcpy";
14039   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14040                  Sema::LookupOrdinaryName);
14041   S.LookupName(R, S.TUScope, true);
14042 
14043   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14044   if (!MemCpy)
14045     // Something went horribly wrong earlier, and we will have complained
14046     // about it.
14047     return StmtError();
14048 
14049   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14050                                             VK_PRValue, Loc, nullptr);
14051   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14052 
14053   Expr *CallArgs[] = {
14054     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14055   };
14056   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14057                                     Loc, CallArgs, Loc);
14058 
14059   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14060   return Call.getAs<Stmt>();
14061 }
14062 
14063 /// Builds a statement that copies/moves the given entity from \p From to
14064 /// \c To.
14065 ///
14066 /// This routine is used to copy/move the members of a class with an
14067 /// implicitly-declared copy/move assignment operator. When the entities being
14068 /// copied are arrays, this routine builds for loops to copy them.
14069 ///
14070 /// \param S The Sema object used for type-checking.
14071 ///
14072 /// \param Loc The location where the implicit copy/move is being generated.
14073 ///
14074 /// \param T The type of the expressions being copied/moved. Both expressions
14075 /// must have this type.
14076 ///
14077 /// \param To The expression we are copying/moving to.
14078 ///
14079 /// \param From The expression we are copying/moving from.
14080 ///
14081 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14082 /// Otherwise, it's a non-static member subobject.
14083 ///
14084 /// \param Copying Whether we're copying or moving.
14085 ///
14086 /// \param Depth Internal parameter recording the depth of the recursion.
14087 ///
14088 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14089 /// if a memcpy should be used instead.
14090 static StmtResult
14091 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14092                                  const ExprBuilder &To, const ExprBuilder &From,
14093                                  bool CopyingBaseSubobject, bool Copying,
14094                                  unsigned Depth = 0) {
14095   // C++11 [class.copy]p28:
14096   //   Each subobject is assigned in the manner appropriate to its type:
14097   //
14098   //     - if the subobject is of class type, as if by a call to operator= with
14099   //       the subobject as the object expression and the corresponding
14100   //       subobject of x as a single function argument (as if by explicit
14101   //       qualification; that is, ignoring any possible virtual overriding
14102   //       functions in more derived classes);
14103   //
14104   // C++03 [class.copy]p13:
14105   //     - if the subobject is of class type, the copy assignment operator for
14106   //       the class is used (as if by explicit qualification; that is,
14107   //       ignoring any possible virtual overriding functions in more derived
14108   //       classes);
14109   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14110     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14111 
14112     // Look for operator=.
14113     DeclarationName Name
14114       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14115     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14116     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14117 
14118     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14119     // operator.
14120     if (!S.getLangOpts().CPlusPlus11) {
14121       LookupResult::Filter F = OpLookup.makeFilter();
14122       while (F.hasNext()) {
14123         NamedDecl *D = F.next();
14124         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14125           if (Method->isCopyAssignmentOperator() ||
14126               (!Copying && Method->isMoveAssignmentOperator()))
14127             continue;
14128 
14129         F.erase();
14130       }
14131       F.done();
14132     }
14133 
14134     // Suppress the protected check (C++ [class.protected]) for each of the
14135     // assignment operators we found. This strange dance is required when
14136     // we're assigning via a base classes's copy-assignment operator. To
14137     // ensure that we're getting the right base class subobject (without
14138     // ambiguities), we need to cast "this" to that subobject type; to
14139     // ensure that we don't go through the virtual call mechanism, we need
14140     // to qualify the operator= name with the base class (see below). However,
14141     // this means that if the base class has a protected copy assignment
14142     // operator, the protected member access check will fail. So, we
14143     // rewrite "protected" access to "public" access in this case, since we
14144     // know by construction that we're calling from a derived class.
14145     if (CopyingBaseSubobject) {
14146       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14147            L != LEnd; ++L) {
14148         if (L.getAccess() == AS_protected)
14149           L.setAccess(AS_public);
14150       }
14151     }
14152 
14153     // Create the nested-name-specifier that will be used to qualify the
14154     // reference to operator=; this is required to suppress the virtual
14155     // call mechanism.
14156     CXXScopeSpec SS;
14157     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14158     SS.MakeTrivial(S.Context,
14159                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14160                                                CanonicalT),
14161                    Loc);
14162 
14163     // Create the reference to operator=.
14164     ExprResult OpEqualRef
14165       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14166                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14167                                    /*FirstQualifierInScope=*/nullptr,
14168                                    OpLookup,
14169                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14170                                    /*SuppressQualifierCheck=*/true);
14171     if (OpEqualRef.isInvalid())
14172       return StmtError();
14173 
14174     // Build the call to the assignment operator.
14175 
14176     Expr *FromInst = From.build(S, Loc);
14177     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14178                                                   OpEqualRef.getAs<Expr>(),
14179                                                   Loc, FromInst, Loc);
14180     if (Call.isInvalid())
14181       return StmtError();
14182 
14183     // If we built a call to a trivial 'operator=' while copying an array,
14184     // bail out. We'll replace the whole shebang with a memcpy.
14185     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14186     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14187       return StmtResult((Stmt*)nullptr);
14188 
14189     // Convert to an expression-statement, and clean up any produced
14190     // temporaries.
14191     return S.ActOnExprStmt(Call);
14192   }
14193 
14194   //     - if the subobject is of scalar type, the built-in assignment
14195   //       operator is used.
14196   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14197   if (!ArrayTy) {
14198     ExprResult Assignment = S.CreateBuiltinBinOp(
14199         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14200     if (Assignment.isInvalid())
14201       return StmtError();
14202     return S.ActOnExprStmt(Assignment);
14203   }
14204 
14205   //     - if the subobject is an array, each element is assigned, in the
14206   //       manner appropriate to the element type;
14207 
14208   // Construct a loop over the array bounds, e.g.,
14209   //
14210   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14211   //
14212   // that will copy each of the array elements.
14213   QualType SizeType = S.Context.getSizeType();
14214 
14215   // Create the iteration variable.
14216   IdentifierInfo *IterationVarName = nullptr;
14217   {
14218     SmallString<8> Str;
14219     llvm::raw_svector_ostream OS(Str);
14220     OS << "__i" << Depth;
14221     IterationVarName = &S.Context.Idents.get(OS.str());
14222   }
14223   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14224                                           IterationVarName, SizeType,
14225                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14226                                           SC_None);
14227 
14228   // Initialize the iteration variable to zero.
14229   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14230   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14231 
14232   // Creates a reference to the iteration variable.
14233   RefBuilder IterationVarRef(IterationVar, SizeType);
14234   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14235 
14236   // Create the DeclStmt that holds the iteration variable.
14237   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14238 
14239   // Subscript the "from" and "to" expressions with the iteration variable.
14240   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14241   MoveCastBuilder FromIndexMove(FromIndexCopy);
14242   const ExprBuilder *FromIndex;
14243   if (Copying)
14244     FromIndex = &FromIndexCopy;
14245   else
14246     FromIndex = &FromIndexMove;
14247 
14248   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14249 
14250   // Build the copy/move for an individual element of the array.
14251   StmtResult Copy =
14252     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14253                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14254                                      Copying, Depth + 1);
14255   // Bail out if copying fails or if we determined that we should use memcpy.
14256   if (Copy.isInvalid() || !Copy.get())
14257     return Copy;
14258 
14259   // Create the comparison against the array bound.
14260   llvm::APInt Upper
14261     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14262   Expr *Comparison = BinaryOperator::Create(
14263       S.Context, IterationVarRefRVal.build(S, Loc),
14264       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14265       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14266       S.CurFPFeatureOverrides());
14267 
14268   // Create the pre-increment of the iteration variable. We can determine
14269   // whether the increment will overflow based on the value of the array
14270   // bound.
14271   Expr *Increment = UnaryOperator::Create(
14272       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14273       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14274 
14275   // Construct the loop that copies all elements of this array.
14276   return S.ActOnForStmt(
14277       Loc, Loc, InitStmt,
14278       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14279       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14280 }
14281 
14282 static StmtResult
14283 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14284                       const ExprBuilder &To, const ExprBuilder &From,
14285                       bool CopyingBaseSubobject, bool Copying) {
14286   // Maybe we should use a memcpy?
14287   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14288       T.isTriviallyCopyableType(S.Context))
14289     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14290 
14291   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14292                                                      CopyingBaseSubobject,
14293                                                      Copying, 0));
14294 
14295   // If we ended up picking a trivial assignment operator for an array of a
14296   // non-trivially-copyable class type, just emit a memcpy.
14297   if (!Result.isInvalid() && !Result.get())
14298     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14299 
14300   return Result;
14301 }
14302 
14303 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14304   // Note: The following rules are largely analoguous to the copy
14305   // constructor rules. Note that virtual bases are not taken into account
14306   // for determining the argument type of the operator. Note also that
14307   // operators taking an object instead of a reference are allowed.
14308   assert(ClassDecl->needsImplicitCopyAssignment());
14309 
14310   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14311   if (DSM.isAlreadyBeingDeclared())
14312     return nullptr;
14313 
14314   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14315   LangAS AS = getDefaultCXXMethodAddrSpace();
14316   if (AS != LangAS::Default)
14317     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14318   QualType RetType = Context.getLValueReferenceType(ArgType);
14319   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14320   if (Const)
14321     ArgType = ArgType.withConst();
14322 
14323   ArgType = Context.getLValueReferenceType(ArgType);
14324 
14325   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14326                                                      CXXCopyAssignment,
14327                                                      Const);
14328 
14329   //   An implicitly-declared copy assignment operator is an inline public
14330   //   member of its class.
14331   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14332   SourceLocation ClassLoc = ClassDecl->getLocation();
14333   DeclarationNameInfo NameInfo(Name, ClassLoc);
14334   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14335       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14336       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14337       getCurFPFeatures().isFPConstrained(),
14338       /*isInline=*/true,
14339       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14340       SourceLocation());
14341   CopyAssignment->setAccess(AS_public);
14342   CopyAssignment->setDefaulted();
14343   CopyAssignment->setImplicit();
14344 
14345   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14346 
14347   if (getLangOpts().CUDA)
14348     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14349                                             CopyAssignment,
14350                                             /* ConstRHS */ Const,
14351                                             /* Diagnose */ false);
14352 
14353   // Add the parameter to the operator.
14354   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14355                                                ClassLoc, ClassLoc,
14356                                                /*Id=*/nullptr, ArgType,
14357                                                /*TInfo=*/nullptr, SC_None,
14358                                                nullptr);
14359   CopyAssignment->setParams(FromParam);
14360 
14361   CopyAssignment->setTrivial(
14362     ClassDecl->needsOverloadResolutionForCopyAssignment()
14363       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14364       : ClassDecl->hasTrivialCopyAssignment());
14365 
14366   // Note that we have added this copy-assignment operator.
14367   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14368 
14369   Scope *S = getScopeForContext(ClassDecl);
14370   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14371 
14372   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14373     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14374     SetDeclDeleted(CopyAssignment, ClassLoc);
14375   }
14376 
14377   if (S)
14378     PushOnScopeChains(CopyAssignment, S, false);
14379   ClassDecl->addDecl(CopyAssignment);
14380 
14381   return CopyAssignment;
14382 }
14383 
14384 /// Diagnose an implicit copy operation for a class which is odr-used, but
14385 /// which is deprecated because the class has a user-declared copy constructor,
14386 /// copy assignment operator, or destructor.
14387 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14388   assert(CopyOp->isImplicit());
14389 
14390   CXXRecordDecl *RD = CopyOp->getParent();
14391   CXXMethodDecl *UserDeclaredOperation = nullptr;
14392 
14393   // In Microsoft mode, assignment operations don't affect constructors and
14394   // vice versa.
14395   if (RD->hasUserDeclaredDestructor()) {
14396     UserDeclaredOperation = RD->getDestructor();
14397   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14398              RD->hasUserDeclaredCopyConstructor() &&
14399              !S.getLangOpts().MSVCCompat) {
14400     // Find any user-declared copy constructor.
14401     for (auto *I : RD->ctors()) {
14402       if (I->isCopyConstructor()) {
14403         UserDeclaredOperation = I;
14404         break;
14405       }
14406     }
14407     assert(UserDeclaredOperation);
14408   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14409              RD->hasUserDeclaredCopyAssignment() &&
14410              !S.getLangOpts().MSVCCompat) {
14411     // Find any user-declared move assignment operator.
14412     for (auto *I : RD->methods()) {
14413       if (I->isCopyAssignmentOperator()) {
14414         UserDeclaredOperation = I;
14415         break;
14416       }
14417     }
14418     assert(UserDeclaredOperation);
14419   }
14420 
14421   if (UserDeclaredOperation) {
14422     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14423     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14424     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14425     unsigned DiagID =
14426         (UDOIsUserProvided && UDOIsDestructor)
14427             ? diag::warn_deprecated_copy_with_user_provided_dtor
14428         : (UDOIsUserProvided && !UDOIsDestructor)
14429             ? diag::warn_deprecated_copy_with_user_provided_copy
14430         : (!UDOIsUserProvided && UDOIsDestructor)
14431             ? diag::warn_deprecated_copy_with_dtor
14432             : diag::warn_deprecated_copy;
14433     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14434         << RD << IsCopyAssignment;
14435   }
14436 }
14437 
14438 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14439                                         CXXMethodDecl *CopyAssignOperator) {
14440   assert((CopyAssignOperator->isDefaulted() &&
14441           CopyAssignOperator->isOverloadedOperator() &&
14442           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14443           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14444           !CopyAssignOperator->isDeleted()) &&
14445          "DefineImplicitCopyAssignment called for wrong function");
14446   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14447     return;
14448 
14449   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14450   if (ClassDecl->isInvalidDecl()) {
14451     CopyAssignOperator->setInvalidDecl();
14452     return;
14453   }
14454 
14455   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14456 
14457   // The exception specification is needed because we are defining the
14458   // function.
14459   ResolveExceptionSpec(CurrentLocation,
14460                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14461 
14462   // Add a context note for diagnostics produced after this point.
14463   Scope.addContextNote(CurrentLocation);
14464 
14465   // C++11 [class.copy]p18:
14466   //   The [definition of an implicitly declared copy assignment operator] is
14467   //   deprecated if the class has a user-declared copy constructor or a
14468   //   user-declared destructor.
14469   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14470     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14471 
14472   // C++0x [class.copy]p30:
14473   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14474   //   for a non-union class X performs memberwise copy assignment of its
14475   //   subobjects. The direct base classes of X are assigned first, in the
14476   //   order of their declaration in the base-specifier-list, and then the
14477   //   immediate non-static data members of X are assigned, in the order in
14478   //   which they were declared in the class definition.
14479 
14480   // The statements that form the synthesized function body.
14481   SmallVector<Stmt*, 8> Statements;
14482 
14483   // The parameter for the "other" object, which we are copying from.
14484   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14485   Qualifiers OtherQuals = Other->getType().getQualifiers();
14486   QualType OtherRefType = Other->getType();
14487   if (const LValueReferenceType *OtherRef
14488                                 = OtherRefType->getAs<LValueReferenceType>()) {
14489     OtherRefType = OtherRef->getPointeeType();
14490     OtherQuals = OtherRefType.getQualifiers();
14491   }
14492 
14493   // Our location for everything implicitly-generated.
14494   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14495                            ? CopyAssignOperator->getEndLoc()
14496                            : CopyAssignOperator->getLocation();
14497 
14498   // Builds a DeclRefExpr for the "other" object.
14499   RefBuilder OtherRef(Other, OtherRefType);
14500 
14501   // Builds the "this" pointer.
14502   ThisBuilder This;
14503 
14504   // Assign base classes.
14505   bool Invalid = false;
14506   for (auto &Base : ClassDecl->bases()) {
14507     // Form the assignment:
14508     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14509     QualType BaseType = Base.getType().getUnqualifiedType();
14510     if (!BaseType->isRecordType()) {
14511       Invalid = true;
14512       continue;
14513     }
14514 
14515     CXXCastPath BasePath;
14516     BasePath.push_back(&Base);
14517 
14518     // Construct the "from" expression, which is an implicit cast to the
14519     // appropriately-qualified base type.
14520     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14521                      VK_LValue, BasePath);
14522 
14523     // Dereference "this".
14524     DerefBuilder DerefThis(This);
14525     CastBuilder To(DerefThis,
14526                    Context.getQualifiedType(
14527                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14528                    VK_LValue, BasePath);
14529 
14530     // Build the copy.
14531     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14532                                             To, From,
14533                                             /*CopyingBaseSubobject=*/true,
14534                                             /*Copying=*/true);
14535     if (Copy.isInvalid()) {
14536       CopyAssignOperator->setInvalidDecl();
14537       return;
14538     }
14539 
14540     // Success! Record the copy.
14541     Statements.push_back(Copy.getAs<Expr>());
14542   }
14543 
14544   // Assign non-static members.
14545   for (auto *Field : ClassDecl->fields()) {
14546     // FIXME: We should form some kind of AST representation for the implied
14547     // memcpy in a union copy operation.
14548     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14549       continue;
14550 
14551     if (Field->isInvalidDecl()) {
14552       Invalid = true;
14553       continue;
14554     }
14555 
14556     // Check for members of reference type; we can't copy those.
14557     if (Field->getType()->isReferenceType()) {
14558       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14559         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14560       Diag(Field->getLocation(), diag::note_declared_at);
14561       Invalid = true;
14562       continue;
14563     }
14564 
14565     // Check for members of const-qualified, non-class type.
14566     QualType BaseType = Context.getBaseElementType(Field->getType());
14567     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14568       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14569         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14570       Diag(Field->getLocation(), diag::note_declared_at);
14571       Invalid = true;
14572       continue;
14573     }
14574 
14575     // Suppress assigning zero-width bitfields.
14576     if (Field->isZeroLengthBitField(Context))
14577       continue;
14578 
14579     QualType FieldType = Field->getType().getNonReferenceType();
14580     if (FieldType->isIncompleteArrayType()) {
14581       assert(ClassDecl->hasFlexibleArrayMember() &&
14582              "Incomplete array type is not valid");
14583       continue;
14584     }
14585 
14586     // Build references to the field in the object we're copying from and to.
14587     CXXScopeSpec SS; // Intentionally empty
14588     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14589                               LookupMemberName);
14590     MemberLookup.addDecl(Field);
14591     MemberLookup.resolveKind();
14592 
14593     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14594 
14595     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14596 
14597     // Build the copy of this field.
14598     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14599                                             To, From,
14600                                             /*CopyingBaseSubobject=*/false,
14601                                             /*Copying=*/true);
14602     if (Copy.isInvalid()) {
14603       CopyAssignOperator->setInvalidDecl();
14604       return;
14605     }
14606 
14607     // Success! Record the copy.
14608     Statements.push_back(Copy.getAs<Stmt>());
14609   }
14610 
14611   if (!Invalid) {
14612     // Add a "return *this;"
14613     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14614 
14615     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14616     if (Return.isInvalid())
14617       Invalid = true;
14618     else
14619       Statements.push_back(Return.getAs<Stmt>());
14620   }
14621 
14622   if (Invalid) {
14623     CopyAssignOperator->setInvalidDecl();
14624     return;
14625   }
14626 
14627   StmtResult Body;
14628   {
14629     CompoundScopeRAII CompoundScope(*this);
14630     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14631                              /*isStmtExpr=*/false);
14632     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14633   }
14634   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14635   CopyAssignOperator->markUsed(Context);
14636 
14637   if (ASTMutationListener *L = getASTMutationListener()) {
14638     L->CompletedImplicitDefinition(CopyAssignOperator);
14639   }
14640 }
14641 
14642 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14643   assert(ClassDecl->needsImplicitMoveAssignment());
14644 
14645   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14646   if (DSM.isAlreadyBeingDeclared())
14647     return nullptr;
14648 
14649   // Note: The following rules are largely analoguous to the move
14650   // constructor rules.
14651 
14652   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14653   LangAS AS = getDefaultCXXMethodAddrSpace();
14654   if (AS != LangAS::Default)
14655     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14656   QualType RetType = Context.getLValueReferenceType(ArgType);
14657   ArgType = Context.getRValueReferenceType(ArgType);
14658 
14659   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14660                                                      CXXMoveAssignment,
14661                                                      false);
14662 
14663   //   An implicitly-declared move assignment operator is an inline public
14664   //   member of its class.
14665   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14666   SourceLocation ClassLoc = ClassDecl->getLocation();
14667   DeclarationNameInfo NameInfo(Name, ClassLoc);
14668   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14669       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14670       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14671       getCurFPFeatures().isFPConstrained(),
14672       /*isInline=*/true,
14673       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14674       SourceLocation());
14675   MoveAssignment->setAccess(AS_public);
14676   MoveAssignment->setDefaulted();
14677   MoveAssignment->setImplicit();
14678 
14679   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14680 
14681   if (getLangOpts().CUDA)
14682     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14683                                             MoveAssignment,
14684                                             /* ConstRHS */ false,
14685                                             /* Diagnose */ false);
14686 
14687   // Add the parameter to the operator.
14688   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14689                                                ClassLoc, ClassLoc,
14690                                                /*Id=*/nullptr, ArgType,
14691                                                /*TInfo=*/nullptr, SC_None,
14692                                                nullptr);
14693   MoveAssignment->setParams(FromParam);
14694 
14695   MoveAssignment->setTrivial(
14696     ClassDecl->needsOverloadResolutionForMoveAssignment()
14697       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14698       : ClassDecl->hasTrivialMoveAssignment());
14699 
14700   // Note that we have added this copy-assignment operator.
14701   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14702 
14703   Scope *S = getScopeForContext(ClassDecl);
14704   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14705 
14706   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14707     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14708     SetDeclDeleted(MoveAssignment, ClassLoc);
14709   }
14710 
14711   if (S)
14712     PushOnScopeChains(MoveAssignment, S, false);
14713   ClassDecl->addDecl(MoveAssignment);
14714 
14715   return MoveAssignment;
14716 }
14717 
14718 /// Check if we're implicitly defining a move assignment operator for a class
14719 /// with virtual bases. Such a move assignment might move-assign the virtual
14720 /// base multiple times.
14721 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14722                                                SourceLocation CurrentLocation) {
14723   assert(!Class->isDependentContext() && "should not define dependent move");
14724 
14725   // Only a virtual base could get implicitly move-assigned multiple times.
14726   // Only a non-trivial move assignment can observe this. We only want to
14727   // diagnose if we implicitly define an assignment operator that assigns
14728   // two base classes, both of which move-assign the same virtual base.
14729   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14730       Class->getNumBases() < 2)
14731     return;
14732 
14733   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14734   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14735   VBaseMap VBases;
14736 
14737   for (auto &BI : Class->bases()) {
14738     Worklist.push_back(&BI);
14739     while (!Worklist.empty()) {
14740       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14741       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14742 
14743       // If the base has no non-trivial move assignment operators,
14744       // we don't care about moves from it.
14745       if (!Base->hasNonTrivialMoveAssignment())
14746         continue;
14747 
14748       // If there's nothing virtual here, skip it.
14749       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14750         continue;
14751 
14752       // If we're not actually going to call a move assignment for this base,
14753       // or the selected move assignment is trivial, skip it.
14754       Sema::SpecialMemberOverloadResult SMOR =
14755         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14756                               /*ConstArg*/false, /*VolatileArg*/false,
14757                               /*RValueThis*/true, /*ConstThis*/false,
14758                               /*VolatileThis*/false);
14759       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14760           !SMOR.getMethod()->isMoveAssignmentOperator())
14761         continue;
14762 
14763       if (BaseSpec->isVirtual()) {
14764         // We're going to move-assign this virtual base, and its move
14765         // assignment operator is not trivial. If this can happen for
14766         // multiple distinct direct bases of Class, diagnose it. (If it
14767         // only happens in one base, we'll diagnose it when synthesizing
14768         // that base class's move assignment operator.)
14769         CXXBaseSpecifier *&Existing =
14770             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14771                 .first->second;
14772         if (Existing && Existing != &BI) {
14773           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14774             << Class << Base;
14775           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14776               << (Base->getCanonicalDecl() ==
14777                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14778               << Base << Existing->getType() << Existing->getSourceRange();
14779           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14780               << (Base->getCanonicalDecl() ==
14781                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14782               << Base << BI.getType() << BaseSpec->getSourceRange();
14783 
14784           // Only diagnose each vbase once.
14785           Existing = nullptr;
14786         }
14787       } else {
14788         // Only walk over bases that have defaulted move assignment operators.
14789         // We assume that any user-provided move assignment operator handles
14790         // the multiple-moves-of-vbase case itself somehow.
14791         if (!SMOR.getMethod()->isDefaulted())
14792           continue;
14793 
14794         // We're going to move the base classes of Base. Add them to the list.
14795         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14796       }
14797     }
14798   }
14799 }
14800 
14801 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14802                                         CXXMethodDecl *MoveAssignOperator) {
14803   assert((MoveAssignOperator->isDefaulted() &&
14804           MoveAssignOperator->isOverloadedOperator() &&
14805           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14806           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14807           !MoveAssignOperator->isDeleted()) &&
14808          "DefineImplicitMoveAssignment called for wrong function");
14809   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14810     return;
14811 
14812   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14813   if (ClassDecl->isInvalidDecl()) {
14814     MoveAssignOperator->setInvalidDecl();
14815     return;
14816   }
14817 
14818   // C++0x [class.copy]p28:
14819   //   The implicitly-defined or move assignment operator for a non-union class
14820   //   X performs memberwise move assignment of its subobjects. The direct base
14821   //   classes of X are assigned first, in the order of their declaration in the
14822   //   base-specifier-list, and then the immediate non-static data members of X
14823   //   are assigned, in the order in which they were declared in the class
14824   //   definition.
14825 
14826   // Issue a warning if our implicit move assignment operator will move
14827   // from a virtual base more than once.
14828   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14829 
14830   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14831 
14832   // The exception specification is needed because we are defining the
14833   // function.
14834   ResolveExceptionSpec(CurrentLocation,
14835                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14836 
14837   // Add a context note for diagnostics produced after this point.
14838   Scope.addContextNote(CurrentLocation);
14839 
14840   // The statements that form the synthesized function body.
14841   SmallVector<Stmt*, 8> Statements;
14842 
14843   // The parameter for the "other" object, which we are move from.
14844   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14845   QualType OtherRefType =
14846       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14847 
14848   // Our location for everything implicitly-generated.
14849   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14850                            ? MoveAssignOperator->getEndLoc()
14851                            : MoveAssignOperator->getLocation();
14852 
14853   // Builds a reference to the "other" object.
14854   RefBuilder OtherRef(Other, OtherRefType);
14855   // Cast to rvalue.
14856   MoveCastBuilder MoveOther(OtherRef);
14857 
14858   // Builds the "this" pointer.
14859   ThisBuilder This;
14860 
14861   // Assign base classes.
14862   bool Invalid = false;
14863   for (auto &Base : ClassDecl->bases()) {
14864     // C++11 [class.copy]p28:
14865     //   It is unspecified whether subobjects representing virtual base classes
14866     //   are assigned more than once by the implicitly-defined copy assignment
14867     //   operator.
14868     // FIXME: Do not assign to a vbase that will be assigned by some other base
14869     // class. For a move-assignment, this can result in the vbase being moved
14870     // multiple times.
14871 
14872     // Form the assignment:
14873     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14874     QualType BaseType = Base.getType().getUnqualifiedType();
14875     if (!BaseType->isRecordType()) {
14876       Invalid = true;
14877       continue;
14878     }
14879 
14880     CXXCastPath BasePath;
14881     BasePath.push_back(&Base);
14882 
14883     // Construct the "from" expression, which is an implicit cast to the
14884     // appropriately-qualified base type.
14885     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14886 
14887     // Dereference "this".
14888     DerefBuilder DerefThis(This);
14889 
14890     // Implicitly cast "this" to the appropriately-qualified base type.
14891     CastBuilder To(DerefThis,
14892                    Context.getQualifiedType(
14893                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14894                    VK_LValue, BasePath);
14895 
14896     // Build the move.
14897     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14898                                             To, From,
14899                                             /*CopyingBaseSubobject=*/true,
14900                                             /*Copying=*/false);
14901     if (Move.isInvalid()) {
14902       MoveAssignOperator->setInvalidDecl();
14903       return;
14904     }
14905 
14906     // Success! Record the move.
14907     Statements.push_back(Move.getAs<Expr>());
14908   }
14909 
14910   // Assign non-static members.
14911   for (auto *Field : ClassDecl->fields()) {
14912     // FIXME: We should form some kind of AST representation for the implied
14913     // memcpy in a union copy operation.
14914     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14915       continue;
14916 
14917     if (Field->isInvalidDecl()) {
14918       Invalid = true;
14919       continue;
14920     }
14921 
14922     // Check for members of reference type; we can't move those.
14923     if (Field->getType()->isReferenceType()) {
14924       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14925         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14926       Diag(Field->getLocation(), diag::note_declared_at);
14927       Invalid = true;
14928       continue;
14929     }
14930 
14931     // Check for members of const-qualified, non-class type.
14932     QualType BaseType = Context.getBaseElementType(Field->getType());
14933     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14934       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14935         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14936       Diag(Field->getLocation(), diag::note_declared_at);
14937       Invalid = true;
14938       continue;
14939     }
14940 
14941     // Suppress assigning zero-width bitfields.
14942     if (Field->isZeroLengthBitField(Context))
14943       continue;
14944 
14945     QualType FieldType = Field->getType().getNonReferenceType();
14946     if (FieldType->isIncompleteArrayType()) {
14947       assert(ClassDecl->hasFlexibleArrayMember() &&
14948              "Incomplete array type is not valid");
14949       continue;
14950     }
14951 
14952     // Build references to the field in the object we're copying from and to.
14953     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14954                               LookupMemberName);
14955     MemberLookup.addDecl(Field);
14956     MemberLookup.resolveKind();
14957     MemberBuilder From(MoveOther, OtherRefType,
14958                        /*IsArrow=*/false, MemberLookup);
14959     MemberBuilder To(This, getCurrentThisType(),
14960                      /*IsArrow=*/true, MemberLookup);
14961 
14962     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14963         "Member reference with rvalue base must be rvalue except for reference "
14964         "members, which aren't allowed for move assignment.");
14965 
14966     // Build the move of this field.
14967     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14968                                             To, From,
14969                                             /*CopyingBaseSubobject=*/false,
14970                                             /*Copying=*/false);
14971     if (Move.isInvalid()) {
14972       MoveAssignOperator->setInvalidDecl();
14973       return;
14974     }
14975 
14976     // Success! Record the copy.
14977     Statements.push_back(Move.getAs<Stmt>());
14978   }
14979 
14980   if (!Invalid) {
14981     // Add a "return *this;"
14982     ExprResult ThisObj =
14983         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14984 
14985     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14986     if (Return.isInvalid())
14987       Invalid = true;
14988     else
14989       Statements.push_back(Return.getAs<Stmt>());
14990   }
14991 
14992   if (Invalid) {
14993     MoveAssignOperator->setInvalidDecl();
14994     return;
14995   }
14996 
14997   StmtResult Body;
14998   {
14999     CompoundScopeRAII CompoundScope(*this);
15000     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15001                              /*isStmtExpr=*/false);
15002     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15003   }
15004   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15005   MoveAssignOperator->markUsed(Context);
15006 
15007   if (ASTMutationListener *L = getASTMutationListener()) {
15008     L->CompletedImplicitDefinition(MoveAssignOperator);
15009   }
15010 }
15011 
15012 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15013                                                     CXXRecordDecl *ClassDecl) {
15014   // C++ [class.copy]p4:
15015   //   If the class definition does not explicitly declare a copy
15016   //   constructor, one is declared implicitly.
15017   assert(ClassDecl->needsImplicitCopyConstructor());
15018 
15019   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15020   if (DSM.isAlreadyBeingDeclared())
15021     return nullptr;
15022 
15023   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15024   QualType ArgType = ClassType;
15025   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15026   if (Const)
15027     ArgType = ArgType.withConst();
15028 
15029   LangAS AS = getDefaultCXXMethodAddrSpace();
15030   if (AS != LangAS::Default)
15031     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15032 
15033   ArgType = Context.getLValueReferenceType(ArgType);
15034 
15035   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15036                                                      CXXCopyConstructor,
15037                                                      Const);
15038 
15039   DeclarationName Name
15040     = Context.DeclarationNames.getCXXConstructorName(
15041                                            Context.getCanonicalType(ClassType));
15042   SourceLocation ClassLoc = ClassDecl->getLocation();
15043   DeclarationNameInfo NameInfo(Name, ClassLoc);
15044 
15045   //   An implicitly-declared copy constructor is an inline public
15046   //   member of its class.
15047   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15048       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15049       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15050       /*isInline=*/true,
15051       /*isImplicitlyDeclared=*/true,
15052       Constexpr ? ConstexprSpecKind::Constexpr
15053                 : ConstexprSpecKind::Unspecified);
15054   CopyConstructor->setAccess(AS_public);
15055   CopyConstructor->setDefaulted();
15056 
15057   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15058 
15059   if (getLangOpts().CUDA)
15060     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15061                                             CopyConstructor,
15062                                             /* ConstRHS */ Const,
15063                                             /* Diagnose */ false);
15064 
15065   // During template instantiation of special member functions we need a
15066   // reliable TypeSourceInfo for the parameter types in order to allow functions
15067   // to be substituted.
15068   TypeSourceInfo *TSI = nullptr;
15069   if (inTemplateInstantiation() && ClassDecl->isLambda())
15070     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15071 
15072   // Add the parameter to the constructor.
15073   ParmVarDecl *FromParam =
15074       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15075                           /*IdentifierInfo=*/nullptr, ArgType,
15076                           /*TInfo=*/TSI, SC_None, nullptr);
15077   CopyConstructor->setParams(FromParam);
15078 
15079   CopyConstructor->setTrivial(
15080       ClassDecl->needsOverloadResolutionForCopyConstructor()
15081           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15082           : ClassDecl->hasTrivialCopyConstructor());
15083 
15084   CopyConstructor->setTrivialForCall(
15085       ClassDecl->hasAttr<TrivialABIAttr>() ||
15086       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15087            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15088              TAH_ConsiderTrivialABI)
15089            : ClassDecl->hasTrivialCopyConstructorForCall()));
15090 
15091   // Note that we have declared this constructor.
15092   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15093 
15094   Scope *S = getScopeForContext(ClassDecl);
15095   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15096 
15097   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15098     ClassDecl->setImplicitCopyConstructorIsDeleted();
15099     SetDeclDeleted(CopyConstructor, ClassLoc);
15100   }
15101 
15102   if (S)
15103     PushOnScopeChains(CopyConstructor, S, false);
15104   ClassDecl->addDecl(CopyConstructor);
15105 
15106   return CopyConstructor;
15107 }
15108 
15109 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15110                                          CXXConstructorDecl *CopyConstructor) {
15111   assert((CopyConstructor->isDefaulted() &&
15112           CopyConstructor->isCopyConstructor() &&
15113           !CopyConstructor->doesThisDeclarationHaveABody() &&
15114           !CopyConstructor->isDeleted()) &&
15115          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15116   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15117     return;
15118 
15119   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15120   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15121 
15122   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15123 
15124   // The exception specification is needed because we are defining the
15125   // function.
15126   ResolveExceptionSpec(CurrentLocation,
15127                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15128   MarkVTableUsed(CurrentLocation, ClassDecl);
15129 
15130   // Add a context note for diagnostics produced after this point.
15131   Scope.addContextNote(CurrentLocation);
15132 
15133   // C++11 [class.copy]p7:
15134   //   The [definition of an implicitly declared copy constructor] is
15135   //   deprecated if the class has a user-declared copy assignment operator
15136   //   or a user-declared destructor.
15137   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15138     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15139 
15140   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15141     CopyConstructor->setInvalidDecl();
15142   }  else {
15143     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15144                              ? CopyConstructor->getEndLoc()
15145                              : CopyConstructor->getLocation();
15146     Sema::CompoundScopeRAII CompoundScope(*this);
15147     CopyConstructor->setBody(
15148         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15149     CopyConstructor->markUsed(Context);
15150   }
15151 
15152   if (ASTMutationListener *L = getASTMutationListener()) {
15153     L->CompletedImplicitDefinition(CopyConstructor);
15154   }
15155 }
15156 
15157 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15158                                                     CXXRecordDecl *ClassDecl) {
15159   assert(ClassDecl->needsImplicitMoveConstructor());
15160 
15161   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15162   if (DSM.isAlreadyBeingDeclared())
15163     return nullptr;
15164 
15165   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15166 
15167   QualType ArgType = ClassType;
15168   LangAS AS = getDefaultCXXMethodAddrSpace();
15169   if (AS != LangAS::Default)
15170     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15171   ArgType = Context.getRValueReferenceType(ArgType);
15172 
15173   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15174                                                      CXXMoveConstructor,
15175                                                      false);
15176 
15177   DeclarationName Name
15178     = Context.DeclarationNames.getCXXConstructorName(
15179                                            Context.getCanonicalType(ClassType));
15180   SourceLocation ClassLoc = ClassDecl->getLocation();
15181   DeclarationNameInfo NameInfo(Name, ClassLoc);
15182 
15183   // C++11 [class.copy]p11:
15184   //   An implicitly-declared copy/move constructor is an inline public
15185   //   member of its class.
15186   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15187       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15188       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15189       /*isInline=*/true,
15190       /*isImplicitlyDeclared=*/true,
15191       Constexpr ? ConstexprSpecKind::Constexpr
15192                 : ConstexprSpecKind::Unspecified);
15193   MoveConstructor->setAccess(AS_public);
15194   MoveConstructor->setDefaulted();
15195 
15196   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15197 
15198   if (getLangOpts().CUDA)
15199     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15200                                             MoveConstructor,
15201                                             /* ConstRHS */ false,
15202                                             /* Diagnose */ false);
15203 
15204   // Add the parameter to the constructor.
15205   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15206                                                ClassLoc, ClassLoc,
15207                                                /*IdentifierInfo=*/nullptr,
15208                                                ArgType, /*TInfo=*/nullptr,
15209                                                SC_None, nullptr);
15210   MoveConstructor->setParams(FromParam);
15211 
15212   MoveConstructor->setTrivial(
15213       ClassDecl->needsOverloadResolutionForMoveConstructor()
15214           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15215           : ClassDecl->hasTrivialMoveConstructor());
15216 
15217   MoveConstructor->setTrivialForCall(
15218       ClassDecl->hasAttr<TrivialABIAttr>() ||
15219       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15220            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15221                                     TAH_ConsiderTrivialABI)
15222            : ClassDecl->hasTrivialMoveConstructorForCall()));
15223 
15224   // Note that we have declared this constructor.
15225   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15226 
15227   Scope *S = getScopeForContext(ClassDecl);
15228   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15229 
15230   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15231     ClassDecl->setImplicitMoveConstructorIsDeleted();
15232     SetDeclDeleted(MoveConstructor, ClassLoc);
15233   }
15234 
15235   if (S)
15236     PushOnScopeChains(MoveConstructor, S, false);
15237   ClassDecl->addDecl(MoveConstructor);
15238 
15239   return MoveConstructor;
15240 }
15241 
15242 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15243                                          CXXConstructorDecl *MoveConstructor) {
15244   assert((MoveConstructor->isDefaulted() &&
15245           MoveConstructor->isMoveConstructor() &&
15246           !MoveConstructor->doesThisDeclarationHaveABody() &&
15247           !MoveConstructor->isDeleted()) &&
15248          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15249   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15250     return;
15251 
15252   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15253   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15254 
15255   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15256 
15257   // The exception specification is needed because we are defining the
15258   // function.
15259   ResolveExceptionSpec(CurrentLocation,
15260                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15261   MarkVTableUsed(CurrentLocation, ClassDecl);
15262 
15263   // Add a context note for diagnostics produced after this point.
15264   Scope.addContextNote(CurrentLocation);
15265 
15266   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15267     MoveConstructor->setInvalidDecl();
15268   } else {
15269     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15270                              ? MoveConstructor->getEndLoc()
15271                              : MoveConstructor->getLocation();
15272     Sema::CompoundScopeRAII CompoundScope(*this);
15273     MoveConstructor->setBody(ActOnCompoundStmt(
15274         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15275     MoveConstructor->markUsed(Context);
15276   }
15277 
15278   if (ASTMutationListener *L = getASTMutationListener()) {
15279     L->CompletedImplicitDefinition(MoveConstructor);
15280   }
15281 }
15282 
15283 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15284   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15285 }
15286 
15287 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15288                             SourceLocation CurrentLocation,
15289                             CXXConversionDecl *Conv) {
15290   SynthesizedFunctionScope Scope(*this, Conv);
15291   assert(!Conv->getReturnType()->isUndeducedType());
15292 
15293   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15294   CallingConv CC =
15295       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15296 
15297   CXXRecordDecl *Lambda = Conv->getParent();
15298   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15299   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15300 
15301   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15302     CallOp = InstantiateFunctionDeclaration(
15303         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15304     if (!CallOp)
15305       return;
15306 
15307     Invoker = InstantiateFunctionDeclaration(
15308         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15309     if (!Invoker)
15310       return;
15311   }
15312 
15313   if (CallOp->isInvalidDecl())
15314     return;
15315 
15316   // Mark the call operator referenced (and add to pending instantiations
15317   // if necessary).
15318   // For both the conversion and static-invoker template specializations
15319   // we construct their body's in this function, so no need to add them
15320   // to the PendingInstantiations.
15321   MarkFunctionReferenced(CurrentLocation, CallOp);
15322 
15323   // Fill in the __invoke function with a dummy implementation. IR generation
15324   // will fill in the actual details. Update its type in case it contained
15325   // an 'auto'.
15326   Invoker->markUsed(Context);
15327   Invoker->setReferenced();
15328   Invoker->setType(Conv->getReturnType()->getPointeeType());
15329   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15330 
15331   // Construct the body of the conversion function { return __invoke; }.
15332   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15333                                        VK_LValue, Conv->getLocation());
15334   assert(FunctionRef && "Can't refer to __invoke function?");
15335   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15336   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15337                                      Conv->getLocation()));
15338   Conv->markUsed(Context);
15339   Conv->setReferenced();
15340 
15341   if (ASTMutationListener *L = getASTMutationListener()) {
15342     L->CompletedImplicitDefinition(Conv);
15343     L->CompletedImplicitDefinition(Invoker);
15344   }
15345 }
15346 
15347 
15348 
15349 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15350        SourceLocation CurrentLocation,
15351        CXXConversionDecl *Conv)
15352 {
15353   assert(!Conv->getParent()->isGenericLambda());
15354 
15355   SynthesizedFunctionScope Scope(*this, Conv);
15356 
15357   // Copy-initialize the lambda object as needed to capture it.
15358   Expr *This = ActOnCXXThis(CurrentLocation).get();
15359   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15360 
15361   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15362                                                         Conv->getLocation(),
15363                                                         Conv, DerefThis);
15364 
15365   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15366   // behavior.  Note that only the general conversion function does this
15367   // (since it's unusable otherwise); in the case where we inline the
15368   // block literal, it has block literal lifetime semantics.
15369   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15370     BuildBlock = ImplicitCastExpr::Create(
15371         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15372         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15373 
15374   if (BuildBlock.isInvalid()) {
15375     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15376     Conv->setInvalidDecl();
15377     return;
15378   }
15379 
15380   // Create the return statement that returns the block from the conversion
15381   // function.
15382   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15383   if (Return.isInvalid()) {
15384     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15385     Conv->setInvalidDecl();
15386     return;
15387   }
15388 
15389   // Set the body of the conversion function.
15390   Stmt *ReturnS = Return.get();
15391   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15392                                      Conv->getLocation()));
15393   Conv->markUsed(Context);
15394 
15395   // We're done; notify the mutation listener, if any.
15396   if (ASTMutationListener *L = getASTMutationListener()) {
15397     L->CompletedImplicitDefinition(Conv);
15398   }
15399 }
15400 
15401 /// Determine whether the given list arguments contains exactly one
15402 /// "real" (non-default) argument.
15403 static bool hasOneRealArgument(MultiExprArg Args) {
15404   switch (Args.size()) {
15405   case 0:
15406     return false;
15407 
15408   default:
15409     if (!Args[1]->isDefaultArgument())
15410       return false;
15411 
15412     LLVM_FALLTHROUGH;
15413   case 1:
15414     return !Args[0]->isDefaultArgument();
15415   }
15416 
15417   return false;
15418 }
15419 
15420 ExprResult
15421 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15422                             NamedDecl *FoundDecl,
15423                             CXXConstructorDecl *Constructor,
15424                             MultiExprArg ExprArgs,
15425                             bool HadMultipleCandidates,
15426                             bool IsListInitialization,
15427                             bool IsStdInitListInitialization,
15428                             bool RequiresZeroInit,
15429                             unsigned ConstructKind,
15430                             SourceRange ParenRange) {
15431   bool Elidable = false;
15432 
15433   // C++0x [class.copy]p34:
15434   //   When certain criteria are met, an implementation is allowed to
15435   //   omit the copy/move construction of a class object, even if the
15436   //   copy/move constructor and/or destructor for the object have
15437   //   side effects. [...]
15438   //     - when a temporary class object that has not been bound to a
15439   //       reference (12.2) would be copied/moved to a class object
15440   //       with the same cv-unqualified type, the copy/move operation
15441   //       can be omitted by constructing the temporary object
15442   //       directly into the target of the omitted copy/move
15443   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15444       // FIXME: Converting constructors should also be accepted.
15445       // But to fix this, the logic that digs down into a CXXConstructExpr
15446       // to find the source object needs to handle it.
15447       // Right now it assumes the source object is passed directly as the
15448       // first argument.
15449       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15450     Expr *SubExpr = ExprArgs[0];
15451     // FIXME: Per above, this is also incorrect if we want to accept
15452     //        converting constructors, as isTemporaryObject will
15453     //        reject temporaries with different type from the
15454     //        CXXRecord itself.
15455     Elidable = SubExpr->isTemporaryObject(
15456         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15457   }
15458 
15459   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15460                                FoundDecl, Constructor,
15461                                Elidable, ExprArgs, HadMultipleCandidates,
15462                                IsListInitialization,
15463                                IsStdInitListInitialization, RequiresZeroInit,
15464                                ConstructKind, ParenRange);
15465 }
15466 
15467 ExprResult
15468 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15469                             NamedDecl *FoundDecl,
15470                             CXXConstructorDecl *Constructor,
15471                             bool Elidable,
15472                             MultiExprArg ExprArgs,
15473                             bool HadMultipleCandidates,
15474                             bool IsListInitialization,
15475                             bool IsStdInitListInitialization,
15476                             bool RequiresZeroInit,
15477                             unsigned ConstructKind,
15478                             SourceRange ParenRange) {
15479   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15480     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15481     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15482       return ExprError();
15483   }
15484 
15485   return BuildCXXConstructExpr(
15486       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15487       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15488       RequiresZeroInit, ConstructKind, ParenRange);
15489 }
15490 
15491 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15492 /// including handling of its default argument expressions.
15493 ExprResult
15494 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15495                             CXXConstructorDecl *Constructor,
15496                             bool Elidable,
15497                             MultiExprArg ExprArgs,
15498                             bool HadMultipleCandidates,
15499                             bool IsListInitialization,
15500                             bool IsStdInitListInitialization,
15501                             bool RequiresZeroInit,
15502                             unsigned ConstructKind,
15503                             SourceRange ParenRange) {
15504   assert(declaresSameEntity(
15505              Constructor->getParent(),
15506              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15507          "given constructor for wrong type");
15508   MarkFunctionReferenced(ConstructLoc, Constructor);
15509   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15510     return ExprError();
15511   if (getLangOpts().SYCLIsDevice &&
15512       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15513     return ExprError();
15514 
15515   return CheckForImmediateInvocation(
15516       CXXConstructExpr::Create(
15517           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15518           HadMultipleCandidates, IsListInitialization,
15519           IsStdInitListInitialization, RequiresZeroInit,
15520           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15521           ParenRange),
15522       Constructor);
15523 }
15524 
15525 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15526   assert(Field->hasInClassInitializer());
15527 
15528   // If we already have the in-class initializer nothing needs to be done.
15529   if (Field->getInClassInitializer())
15530     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15531 
15532   // If we might have already tried and failed to instantiate, don't try again.
15533   if (Field->isInvalidDecl())
15534     return ExprError();
15535 
15536   // Maybe we haven't instantiated the in-class initializer. Go check the
15537   // pattern FieldDecl to see if it has one.
15538   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15539 
15540   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15541     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15542     DeclContext::lookup_result Lookup =
15543         ClassPattern->lookup(Field->getDeclName());
15544 
15545     FieldDecl *Pattern = nullptr;
15546     for (auto L : Lookup) {
15547       if (isa<FieldDecl>(L)) {
15548         Pattern = cast<FieldDecl>(L);
15549         break;
15550       }
15551     }
15552     assert(Pattern && "We must have set the Pattern!");
15553 
15554     if (!Pattern->hasInClassInitializer() ||
15555         InstantiateInClassInitializer(Loc, Field, Pattern,
15556                                       getTemplateInstantiationArgs(Field))) {
15557       // Don't diagnose this again.
15558       Field->setInvalidDecl();
15559       return ExprError();
15560     }
15561     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15562   }
15563 
15564   // DR1351:
15565   //   If the brace-or-equal-initializer of a non-static data member
15566   //   invokes a defaulted default constructor of its class or of an
15567   //   enclosing class in a potentially evaluated subexpression, the
15568   //   program is ill-formed.
15569   //
15570   // This resolution is unworkable: the exception specification of the
15571   // default constructor can be needed in an unevaluated context, in
15572   // particular, in the operand of a noexcept-expression, and we can be
15573   // unable to compute an exception specification for an enclosed class.
15574   //
15575   // Any attempt to resolve the exception specification of a defaulted default
15576   // constructor before the initializer is lexically complete will ultimately
15577   // come here at which point we can diagnose it.
15578   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15579   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15580       << OutermostClass << Field;
15581   Diag(Field->getEndLoc(),
15582        diag::note_default_member_initializer_not_yet_parsed);
15583   // Recover by marking the field invalid, unless we're in a SFINAE context.
15584   if (!isSFINAEContext())
15585     Field->setInvalidDecl();
15586   return ExprError();
15587 }
15588 
15589 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15590   if (VD->isInvalidDecl()) return;
15591   // If initializing the variable failed, don't also diagnose problems with
15592   // the destructor, they're likely related.
15593   if (VD->getInit() && VD->getInit()->containsErrors())
15594     return;
15595 
15596   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15597   if (ClassDecl->isInvalidDecl()) return;
15598   if (ClassDecl->hasIrrelevantDestructor()) return;
15599   if (ClassDecl->isDependentContext()) return;
15600 
15601   if (VD->isNoDestroy(getASTContext()))
15602     return;
15603 
15604   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15605 
15606   // If this is an array, we'll require the destructor during initialization, so
15607   // we can skip over this. We still want to emit exit-time destructor warnings
15608   // though.
15609   if (!VD->getType()->isArrayType()) {
15610     MarkFunctionReferenced(VD->getLocation(), Destructor);
15611     CheckDestructorAccess(VD->getLocation(), Destructor,
15612                           PDiag(diag::err_access_dtor_var)
15613                               << VD->getDeclName() << VD->getType());
15614     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15615   }
15616 
15617   if (Destructor->isTrivial()) return;
15618 
15619   // If the destructor is constexpr, check whether the variable has constant
15620   // destruction now.
15621   if (Destructor->isConstexpr()) {
15622     bool HasConstantInit = false;
15623     if (VD->getInit() && !VD->getInit()->isValueDependent())
15624       HasConstantInit = VD->evaluateValue();
15625     SmallVector<PartialDiagnosticAt, 8> Notes;
15626     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15627         HasConstantInit) {
15628       Diag(VD->getLocation(),
15629            diag::err_constexpr_var_requires_const_destruction) << VD;
15630       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15631         Diag(Notes[I].first, Notes[I].second);
15632     }
15633   }
15634 
15635   if (!VD->hasGlobalStorage()) return;
15636 
15637   // Emit warning for non-trivial dtor in global scope (a real global,
15638   // class-static, function-static).
15639   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15640 
15641   // TODO: this should be re-enabled for static locals by !CXAAtExit
15642   if (!VD->isStaticLocal())
15643     Diag(VD->getLocation(), diag::warn_global_destructor);
15644 }
15645 
15646 /// Given a constructor and the set of arguments provided for the
15647 /// constructor, convert the arguments and add any required default arguments
15648 /// to form a proper call to this constructor.
15649 ///
15650 /// \returns true if an error occurred, false otherwise.
15651 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15652                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15653                                    SourceLocation Loc,
15654                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15655                                    bool AllowExplicit,
15656                                    bool IsListInitialization) {
15657   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15658   unsigned NumArgs = ArgsPtr.size();
15659   Expr **Args = ArgsPtr.data();
15660 
15661   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15662   unsigned NumParams = Proto->getNumParams();
15663 
15664   // If too few arguments are available, we'll fill in the rest with defaults.
15665   if (NumArgs < NumParams)
15666     ConvertedArgs.reserve(NumParams);
15667   else
15668     ConvertedArgs.reserve(NumArgs);
15669 
15670   VariadicCallType CallType =
15671     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15672   SmallVector<Expr *, 8> AllArgs;
15673   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15674                                         Proto, 0,
15675                                         llvm::makeArrayRef(Args, NumArgs),
15676                                         AllArgs,
15677                                         CallType, AllowExplicit,
15678                                         IsListInitialization);
15679   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15680 
15681   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15682 
15683   CheckConstructorCall(Constructor, DeclInitType,
15684                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15685                        Proto, Loc);
15686 
15687   return Invalid;
15688 }
15689 
15690 static inline bool
15691 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15692                                        const FunctionDecl *FnDecl) {
15693   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15694   if (isa<NamespaceDecl>(DC)) {
15695     return SemaRef.Diag(FnDecl->getLocation(),
15696                         diag::err_operator_new_delete_declared_in_namespace)
15697       << FnDecl->getDeclName();
15698   }
15699 
15700   if (isa<TranslationUnitDecl>(DC) &&
15701       FnDecl->getStorageClass() == SC_Static) {
15702     return SemaRef.Diag(FnDecl->getLocation(),
15703                         diag::err_operator_new_delete_declared_static)
15704       << FnDecl->getDeclName();
15705   }
15706 
15707   return false;
15708 }
15709 
15710 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15711                                              const PointerType *PtrTy) {
15712   auto &Ctx = SemaRef.Context;
15713   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15714   PtrQuals.removeAddressSpace();
15715   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15716       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15717 }
15718 
15719 static inline bool
15720 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15721                             CanQualType ExpectedResultType,
15722                             CanQualType ExpectedFirstParamType,
15723                             unsigned DependentParamTypeDiag,
15724                             unsigned InvalidParamTypeDiag) {
15725   QualType ResultType =
15726       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15727 
15728   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15729     // The operator is valid on any address space for OpenCL.
15730     // Drop address space from actual and expected result types.
15731     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15732       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15733 
15734     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15735       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15736   }
15737 
15738   // Check that the result type is what we expect.
15739   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15740     // Reject even if the type is dependent; an operator delete function is
15741     // required to have a non-dependent result type.
15742     return SemaRef.Diag(
15743                FnDecl->getLocation(),
15744                ResultType->isDependentType()
15745                    ? diag::err_operator_new_delete_dependent_result_type
15746                    : diag::err_operator_new_delete_invalid_result_type)
15747            << FnDecl->getDeclName() << ExpectedResultType;
15748   }
15749 
15750   // A function template must have at least 2 parameters.
15751   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15752     return SemaRef.Diag(FnDecl->getLocation(),
15753                       diag::err_operator_new_delete_template_too_few_parameters)
15754         << FnDecl->getDeclName();
15755 
15756   // The function decl must have at least 1 parameter.
15757   if (FnDecl->getNumParams() == 0)
15758     return SemaRef.Diag(FnDecl->getLocation(),
15759                         diag::err_operator_new_delete_too_few_parameters)
15760       << FnDecl->getDeclName();
15761 
15762   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15763   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15764     // The operator is valid on any address space for OpenCL.
15765     // Drop address space from actual and expected first parameter types.
15766     if (const auto *PtrTy =
15767             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15768       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15769 
15770     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15771       ExpectedFirstParamType =
15772           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15773   }
15774 
15775   // Check that the first parameter type is what we expect.
15776   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15777       ExpectedFirstParamType) {
15778     // The first parameter type is not allowed to be dependent. As a tentative
15779     // DR resolution, we allow a dependent parameter type if it is the right
15780     // type anyway, to allow destroying operator delete in class templates.
15781     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15782                                                    ? DependentParamTypeDiag
15783                                                    : InvalidParamTypeDiag)
15784            << FnDecl->getDeclName() << ExpectedFirstParamType;
15785   }
15786 
15787   return false;
15788 }
15789 
15790 static bool
15791 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15792   // C++ [basic.stc.dynamic.allocation]p1:
15793   //   A program is ill-formed if an allocation function is declared in a
15794   //   namespace scope other than global scope or declared static in global
15795   //   scope.
15796   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15797     return true;
15798 
15799   CanQualType SizeTy =
15800     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15801 
15802   // C++ [basic.stc.dynamic.allocation]p1:
15803   //  The return type shall be void*. The first parameter shall have type
15804   //  std::size_t.
15805   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15806                                   SizeTy,
15807                                   diag::err_operator_new_dependent_param_type,
15808                                   diag::err_operator_new_param_type))
15809     return true;
15810 
15811   // C++ [basic.stc.dynamic.allocation]p1:
15812   //  The first parameter shall not have an associated default argument.
15813   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15814     return SemaRef.Diag(FnDecl->getLocation(),
15815                         diag::err_operator_new_default_arg)
15816       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15817 
15818   return false;
15819 }
15820 
15821 static bool
15822 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15823   // C++ [basic.stc.dynamic.deallocation]p1:
15824   //   A program is ill-formed if deallocation functions are declared in a
15825   //   namespace scope other than global scope or declared static in global
15826   //   scope.
15827   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15828     return true;
15829 
15830   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15831 
15832   // C++ P0722:
15833   //   Within a class C, the first parameter of a destroying operator delete
15834   //   shall be of type C *. The first parameter of any other deallocation
15835   //   function shall be of type void *.
15836   CanQualType ExpectedFirstParamType =
15837       MD && MD->isDestroyingOperatorDelete()
15838           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15839                 SemaRef.Context.getRecordType(MD->getParent())))
15840           : SemaRef.Context.VoidPtrTy;
15841 
15842   // C++ [basic.stc.dynamic.deallocation]p2:
15843   //   Each deallocation function shall return void
15844   if (CheckOperatorNewDeleteTypes(
15845           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15846           diag::err_operator_delete_dependent_param_type,
15847           diag::err_operator_delete_param_type))
15848     return true;
15849 
15850   // C++ P0722:
15851   //   A destroying operator delete shall be a usual deallocation function.
15852   if (MD && !MD->getParent()->isDependentContext() &&
15853       MD->isDestroyingOperatorDelete() &&
15854       !SemaRef.isUsualDeallocationFunction(MD)) {
15855     SemaRef.Diag(MD->getLocation(),
15856                  diag::err_destroying_operator_delete_not_usual);
15857     return true;
15858   }
15859 
15860   return false;
15861 }
15862 
15863 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15864 /// of this overloaded operator is well-formed. If so, returns false;
15865 /// otherwise, emits appropriate diagnostics and returns true.
15866 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15867   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15868          "Expected an overloaded operator declaration");
15869 
15870   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15871 
15872   // C++ [over.oper]p5:
15873   //   The allocation and deallocation functions, operator new,
15874   //   operator new[], operator delete and operator delete[], are
15875   //   described completely in 3.7.3. The attributes and restrictions
15876   //   found in the rest of this subclause do not apply to them unless
15877   //   explicitly stated in 3.7.3.
15878   if (Op == OO_Delete || Op == OO_Array_Delete)
15879     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15880 
15881   if (Op == OO_New || Op == OO_Array_New)
15882     return CheckOperatorNewDeclaration(*this, FnDecl);
15883 
15884   // C++ [over.oper]p6:
15885   //   An operator function shall either be a non-static member
15886   //   function or be a non-member function and have at least one
15887   //   parameter whose type is a class, a reference to a class, an
15888   //   enumeration, or a reference to an enumeration.
15889   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15890     if (MethodDecl->isStatic())
15891       return Diag(FnDecl->getLocation(),
15892                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15893   } else {
15894     bool ClassOrEnumParam = false;
15895     for (auto Param : FnDecl->parameters()) {
15896       QualType ParamType = Param->getType().getNonReferenceType();
15897       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15898           ParamType->isEnumeralType()) {
15899         ClassOrEnumParam = true;
15900         break;
15901       }
15902     }
15903 
15904     if (!ClassOrEnumParam)
15905       return Diag(FnDecl->getLocation(),
15906                   diag::err_operator_overload_needs_class_or_enum)
15907         << FnDecl->getDeclName();
15908   }
15909 
15910   // C++ [over.oper]p8:
15911   //   An operator function cannot have default arguments (8.3.6),
15912   //   except where explicitly stated below.
15913   //
15914   // Only the function-call operator (C++ [over.call]p1) and the subscript
15915   // operator (CWG2507) allow default arguments.
15916   if (Op != OO_Call) {
15917     ParmVarDecl *FirstDefaultedParam = nullptr;
15918     for (auto Param : FnDecl->parameters()) {
15919       if (Param->hasDefaultArg()) {
15920         FirstDefaultedParam = Param;
15921         break;
15922       }
15923     }
15924     if (FirstDefaultedParam) {
15925       if (Op == OO_Subscript) {
15926         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15927                                         ? diag::ext_subscript_overload
15928                                         : diag::error_subscript_overload)
15929             << FnDecl->getDeclName() << 1
15930             << FirstDefaultedParam->getDefaultArgRange();
15931       } else {
15932         return Diag(FirstDefaultedParam->getLocation(),
15933                     diag::err_operator_overload_default_arg)
15934                << FnDecl->getDeclName()
15935                << FirstDefaultedParam->getDefaultArgRange();
15936       }
15937     }
15938   }
15939 
15940   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15941     { false, false, false }
15942 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15943     , { Unary, Binary, MemberOnly }
15944 #include "clang/Basic/OperatorKinds.def"
15945   };
15946 
15947   bool CanBeUnaryOperator = OperatorUses[Op][0];
15948   bool CanBeBinaryOperator = OperatorUses[Op][1];
15949   bool MustBeMemberOperator = OperatorUses[Op][2];
15950 
15951   // C++ [over.oper]p8:
15952   //   [...] Operator functions cannot have more or fewer parameters
15953   //   than the number required for the corresponding operator, as
15954   //   described in the rest of this subclause.
15955   unsigned NumParams = FnDecl->getNumParams()
15956                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15957   if (Op != OO_Call && Op != OO_Subscript &&
15958       ((NumParams == 1 && !CanBeUnaryOperator) ||
15959        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15960        (NumParams > 2))) {
15961     // We have the wrong number of parameters.
15962     unsigned ErrorKind;
15963     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15964       ErrorKind = 2;  // 2 -> unary or binary.
15965     } else if (CanBeUnaryOperator) {
15966       ErrorKind = 0;  // 0 -> unary
15967     } else {
15968       assert(CanBeBinaryOperator &&
15969              "All non-call overloaded operators are unary or binary!");
15970       ErrorKind = 1;  // 1 -> binary
15971     }
15972     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15973       << FnDecl->getDeclName() << NumParams << ErrorKind;
15974   }
15975 
15976   if (Op == OO_Subscript && NumParams != 2) {
15977     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15978                                     ? diag::ext_subscript_overload
15979                                     : diag::error_subscript_overload)
15980         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
15981   }
15982 
15983   // Overloaded operators other than operator() and operator[] cannot be
15984   // variadic.
15985   if (Op != OO_Call &&
15986       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15987     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15988            << FnDecl->getDeclName();
15989   }
15990 
15991   // Some operators must be non-static member functions.
15992   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15993     return Diag(FnDecl->getLocation(),
15994                 diag::err_operator_overload_must_be_member)
15995       << FnDecl->getDeclName();
15996   }
15997 
15998   // C++ [over.inc]p1:
15999   //   The user-defined function called operator++ implements the
16000   //   prefix and postfix ++ operator. If this function is a member
16001   //   function with no parameters, or a non-member function with one
16002   //   parameter of class or enumeration type, it defines the prefix
16003   //   increment operator ++ for objects of that type. If the function
16004   //   is a member function with one parameter (which shall be of type
16005   //   int) or a non-member function with two parameters (the second
16006   //   of which shall be of type int), it defines the postfix
16007   //   increment operator ++ for objects of that type.
16008   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16009     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16010     QualType ParamType = LastParam->getType();
16011 
16012     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16013         !ParamType->isDependentType())
16014       return Diag(LastParam->getLocation(),
16015                   diag::err_operator_overload_post_incdec_must_be_int)
16016         << LastParam->getType() << (Op == OO_MinusMinus);
16017   }
16018 
16019   return false;
16020 }
16021 
16022 static bool
16023 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16024                                           FunctionTemplateDecl *TpDecl) {
16025   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16026 
16027   // Must have one or two template parameters.
16028   if (TemplateParams->size() == 1) {
16029     NonTypeTemplateParmDecl *PmDecl =
16030         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16031 
16032     // The template parameter must be a char parameter pack.
16033     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16034         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16035       return false;
16036 
16037     // C++20 [over.literal]p5:
16038     //   A string literal operator template is a literal operator template
16039     //   whose template-parameter-list comprises a single non-type
16040     //   template-parameter of class type.
16041     //
16042     // As a DR resolution, we also allow placeholders for deduced class
16043     // template specializations.
16044     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16045         !PmDecl->isTemplateParameterPack() &&
16046         (PmDecl->getType()->isRecordType() ||
16047          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16048       return false;
16049   } else if (TemplateParams->size() == 2) {
16050     TemplateTypeParmDecl *PmType =
16051         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16052     NonTypeTemplateParmDecl *PmArgs =
16053         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16054 
16055     // The second template parameter must be a parameter pack with the
16056     // first template parameter as its type.
16057     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16058         PmArgs->isTemplateParameterPack()) {
16059       const TemplateTypeParmType *TArgs =
16060           PmArgs->getType()->getAs<TemplateTypeParmType>();
16061       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16062           TArgs->getIndex() == PmType->getIndex()) {
16063         if (!SemaRef.inTemplateInstantiation())
16064           SemaRef.Diag(TpDecl->getLocation(),
16065                        diag::ext_string_literal_operator_template);
16066         return false;
16067       }
16068     }
16069   }
16070 
16071   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16072                diag::err_literal_operator_template)
16073       << TpDecl->getTemplateParameters()->getSourceRange();
16074   return true;
16075 }
16076 
16077 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16078 /// of this literal operator function is well-formed. If so, returns
16079 /// false; otherwise, emits appropriate diagnostics and returns true.
16080 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16081   if (isa<CXXMethodDecl>(FnDecl)) {
16082     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16083       << FnDecl->getDeclName();
16084     return true;
16085   }
16086 
16087   if (FnDecl->isExternC()) {
16088     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16089     if (const LinkageSpecDecl *LSD =
16090             FnDecl->getDeclContext()->getExternCContext())
16091       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16092     return true;
16093   }
16094 
16095   // This might be the definition of a literal operator template.
16096   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16097 
16098   // This might be a specialization of a literal operator template.
16099   if (!TpDecl)
16100     TpDecl = FnDecl->getPrimaryTemplate();
16101 
16102   // template <char...> type operator "" name() and
16103   // template <class T, T...> type operator "" name() are the only valid
16104   // template signatures, and the only valid signatures with no parameters.
16105   //
16106   // C++20 also allows template <SomeClass T> type operator "" name().
16107   if (TpDecl) {
16108     if (FnDecl->param_size() != 0) {
16109       Diag(FnDecl->getLocation(),
16110            diag::err_literal_operator_template_with_params);
16111       return true;
16112     }
16113 
16114     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16115       return true;
16116 
16117   } else if (FnDecl->param_size() == 1) {
16118     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16119 
16120     QualType ParamType = Param->getType().getUnqualifiedType();
16121 
16122     // Only unsigned long long int, long double, any character type, and const
16123     // char * are allowed as the only parameters.
16124     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16125         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16126         Context.hasSameType(ParamType, Context.CharTy) ||
16127         Context.hasSameType(ParamType, Context.WideCharTy) ||
16128         Context.hasSameType(ParamType, Context.Char8Ty) ||
16129         Context.hasSameType(ParamType, Context.Char16Ty) ||
16130         Context.hasSameType(ParamType, Context.Char32Ty)) {
16131     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16132       QualType InnerType = Ptr->getPointeeType();
16133 
16134       // Pointer parameter must be a const char *.
16135       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16136                                 Context.CharTy) &&
16137             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16138         Diag(Param->getSourceRange().getBegin(),
16139              diag::err_literal_operator_param)
16140             << ParamType << "'const char *'" << Param->getSourceRange();
16141         return true;
16142       }
16143 
16144     } else if (ParamType->isRealFloatingType()) {
16145       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16146           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16147       return true;
16148 
16149     } else if (ParamType->isIntegerType()) {
16150       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16151           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16152       return true;
16153 
16154     } else {
16155       Diag(Param->getSourceRange().getBegin(),
16156            diag::err_literal_operator_invalid_param)
16157           << ParamType << Param->getSourceRange();
16158       return true;
16159     }
16160 
16161   } else if (FnDecl->param_size() == 2) {
16162     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16163 
16164     // First, verify that the first parameter is correct.
16165 
16166     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16167 
16168     // Two parameter function must have a pointer to const as a
16169     // first parameter; let's strip those qualifiers.
16170     const PointerType *PT = FirstParamType->getAs<PointerType>();
16171 
16172     if (!PT) {
16173       Diag((*Param)->getSourceRange().getBegin(),
16174            diag::err_literal_operator_param)
16175           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16176       return true;
16177     }
16178 
16179     QualType PointeeType = PT->getPointeeType();
16180     // First parameter must be const
16181     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16182       Diag((*Param)->getSourceRange().getBegin(),
16183            diag::err_literal_operator_param)
16184           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16185       return true;
16186     }
16187 
16188     QualType InnerType = PointeeType.getUnqualifiedType();
16189     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16190     // const char32_t* are allowed as the first parameter to a two-parameter
16191     // function
16192     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16193           Context.hasSameType(InnerType, Context.WideCharTy) ||
16194           Context.hasSameType(InnerType, Context.Char8Ty) ||
16195           Context.hasSameType(InnerType, Context.Char16Ty) ||
16196           Context.hasSameType(InnerType, Context.Char32Ty))) {
16197       Diag((*Param)->getSourceRange().getBegin(),
16198            diag::err_literal_operator_param)
16199           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16200       return true;
16201     }
16202 
16203     // Move on to the second and final parameter.
16204     ++Param;
16205 
16206     // The second parameter must be a std::size_t.
16207     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16208     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16209       Diag((*Param)->getSourceRange().getBegin(),
16210            diag::err_literal_operator_param)
16211           << SecondParamType << Context.getSizeType()
16212           << (*Param)->getSourceRange();
16213       return true;
16214     }
16215   } else {
16216     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16217     return true;
16218   }
16219 
16220   // Parameters are good.
16221 
16222   // A parameter-declaration-clause containing a default argument is not
16223   // equivalent to any of the permitted forms.
16224   for (auto Param : FnDecl->parameters()) {
16225     if (Param->hasDefaultArg()) {
16226       Diag(Param->getDefaultArgRange().getBegin(),
16227            diag::err_literal_operator_default_argument)
16228         << Param->getDefaultArgRange();
16229       break;
16230     }
16231   }
16232 
16233   StringRef LiteralName
16234     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16235   if (LiteralName[0] != '_' &&
16236       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16237     // C++11 [usrlit.suffix]p1:
16238     //   Literal suffix identifiers that do not start with an underscore
16239     //   are reserved for future standardization.
16240     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16241       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16242   }
16243 
16244   return false;
16245 }
16246 
16247 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16248 /// linkage specification, including the language and (if present)
16249 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16250 /// language string literal. LBraceLoc, if valid, provides the location of
16251 /// the '{' brace. Otherwise, this linkage specification does not
16252 /// have any braces.
16253 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16254                                            Expr *LangStr,
16255                                            SourceLocation LBraceLoc) {
16256   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16257   if (!Lit->isAscii()) {
16258     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16259       << LangStr->getSourceRange();
16260     return nullptr;
16261   }
16262 
16263   StringRef Lang = Lit->getString();
16264   LinkageSpecDecl::LanguageIDs Language;
16265   if (Lang == "C")
16266     Language = LinkageSpecDecl::lang_c;
16267   else if (Lang == "C++")
16268     Language = LinkageSpecDecl::lang_cxx;
16269   else {
16270     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16271       << LangStr->getSourceRange();
16272     return nullptr;
16273   }
16274 
16275   // FIXME: Add all the various semantics of linkage specifications
16276 
16277   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16278                                                LangStr->getExprLoc(), Language,
16279                                                LBraceLoc.isValid());
16280 
16281   /// C++ [module.unit]p7.2.3
16282   /// - Otherwise, if the declaration
16283   ///   - ...
16284   ///   - ...
16285   ///   - appears within a linkage-specification,
16286   ///   it is attached to the global module.
16287   ///
16288   /// If the declaration is already in global module fragment, we don't
16289   /// need to attach it again.
16290   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16291     Module *GlobalModule =
16292         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16293     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16294     D->setLocalOwningModule(GlobalModule);
16295   }
16296 
16297   CurContext->addDecl(D);
16298   PushDeclContext(S, D);
16299   return D;
16300 }
16301 
16302 /// ActOnFinishLinkageSpecification - Complete the definition of
16303 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16304 /// valid, it's the position of the closing '}' brace in a linkage
16305 /// specification that uses braces.
16306 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16307                                             Decl *LinkageSpec,
16308                                             SourceLocation RBraceLoc) {
16309   if (RBraceLoc.isValid()) {
16310     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16311     LSDecl->setRBraceLoc(RBraceLoc);
16312   }
16313 
16314   // If the current module doesn't has Parent, it implies that the
16315   // LinkageSpec isn't in the module created by itself. So we don't
16316   // need to pop it.
16317   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16318       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16319     PopGlobalModuleFragment();
16320 
16321   PopDeclContext();
16322   return LinkageSpec;
16323 }
16324 
16325 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16326                                   const ParsedAttributesView &AttrList,
16327                                   SourceLocation SemiLoc) {
16328   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16329   // Attribute declarations appertain to empty declaration so we handle
16330   // them here.
16331   ProcessDeclAttributeList(S, ED, AttrList);
16332 
16333   CurContext->addDecl(ED);
16334   return ED;
16335 }
16336 
16337 /// Perform semantic analysis for the variable declaration that
16338 /// occurs within a C++ catch clause, returning the newly-created
16339 /// variable.
16340 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16341                                          TypeSourceInfo *TInfo,
16342                                          SourceLocation StartLoc,
16343                                          SourceLocation Loc,
16344                                          IdentifierInfo *Name) {
16345   bool Invalid = false;
16346   QualType ExDeclType = TInfo->getType();
16347 
16348   // Arrays and functions decay.
16349   if (ExDeclType->isArrayType())
16350     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16351   else if (ExDeclType->isFunctionType())
16352     ExDeclType = Context.getPointerType(ExDeclType);
16353 
16354   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16355   // The exception-declaration shall not denote a pointer or reference to an
16356   // incomplete type, other than [cv] void*.
16357   // N2844 forbids rvalue references.
16358   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16359     Diag(Loc, diag::err_catch_rvalue_ref);
16360     Invalid = true;
16361   }
16362 
16363   if (ExDeclType->isVariablyModifiedType()) {
16364     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16365     Invalid = true;
16366   }
16367 
16368   QualType BaseType = ExDeclType;
16369   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16370   unsigned DK = diag::err_catch_incomplete;
16371   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16372     BaseType = Ptr->getPointeeType();
16373     Mode = 1;
16374     DK = diag::err_catch_incomplete_ptr;
16375   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16376     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16377     BaseType = Ref->getPointeeType();
16378     Mode = 2;
16379     DK = diag::err_catch_incomplete_ref;
16380   }
16381   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16382       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16383     Invalid = true;
16384 
16385   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16386     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16387     Invalid = true;
16388   }
16389 
16390   if (!Invalid && !ExDeclType->isDependentType() &&
16391       RequireNonAbstractType(Loc, ExDeclType,
16392                              diag::err_abstract_type_in_decl,
16393                              AbstractVariableType))
16394     Invalid = true;
16395 
16396   // Only the non-fragile NeXT runtime currently supports C++ catches
16397   // of ObjC types, and no runtime supports catching ObjC types by value.
16398   if (!Invalid && getLangOpts().ObjC) {
16399     QualType T = ExDeclType;
16400     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16401       T = RT->getPointeeType();
16402 
16403     if (T->isObjCObjectType()) {
16404       Diag(Loc, diag::err_objc_object_catch);
16405       Invalid = true;
16406     } else if (T->isObjCObjectPointerType()) {
16407       // FIXME: should this be a test for macosx-fragile specifically?
16408       if (getLangOpts().ObjCRuntime.isFragile())
16409         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16410     }
16411   }
16412 
16413   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16414                                     ExDeclType, TInfo, SC_None);
16415   ExDecl->setExceptionVariable(true);
16416 
16417   // In ARC, infer 'retaining' for variables of retainable type.
16418   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16419     Invalid = true;
16420 
16421   if (!Invalid && !ExDeclType->isDependentType()) {
16422     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16423       // Insulate this from anything else we might currently be parsing.
16424       EnterExpressionEvaluationContext scope(
16425           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16426 
16427       // C++ [except.handle]p16:
16428       //   The object declared in an exception-declaration or, if the
16429       //   exception-declaration does not specify a name, a temporary (12.2) is
16430       //   copy-initialized (8.5) from the exception object. [...]
16431       //   The object is destroyed when the handler exits, after the destruction
16432       //   of any automatic objects initialized within the handler.
16433       //
16434       // We just pretend to initialize the object with itself, then make sure
16435       // it can be destroyed later.
16436       QualType initType = Context.getExceptionObjectType(ExDeclType);
16437 
16438       InitializedEntity entity =
16439         InitializedEntity::InitializeVariable(ExDecl);
16440       InitializationKind initKind =
16441         InitializationKind::CreateCopy(Loc, SourceLocation());
16442 
16443       Expr *opaqueValue =
16444         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16445       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16446       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16447       if (result.isInvalid())
16448         Invalid = true;
16449       else {
16450         // If the constructor used was non-trivial, set this as the
16451         // "initializer".
16452         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16453         if (!construct->getConstructor()->isTrivial()) {
16454           Expr *init = MaybeCreateExprWithCleanups(construct);
16455           ExDecl->setInit(init);
16456         }
16457 
16458         // And make sure it's destructable.
16459         FinalizeVarWithDestructor(ExDecl, recordType);
16460       }
16461     }
16462   }
16463 
16464   if (Invalid)
16465     ExDecl->setInvalidDecl();
16466 
16467   return ExDecl;
16468 }
16469 
16470 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16471 /// handler.
16472 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16473   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16474   bool Invalid = D.isInvalidType();
16475 
16476   // Check for unexpanded parameter packs.
16477   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16478                                       UPPC_ExceptionType)) {
16479     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16480                                              D.getIdentifierLoc());
16481     Invalid = true;
16482   }
16483 
16484   IdentifierInfo *II = D.getIdentifier();
16485   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16486                                              LookupOrdinaryName,
16487                                              ForVisibleRedeclaration)) {
16488     // The scope should be freshly made just for us. There is just no way
16489     // it contains any previous declaration, except for function parameters in
16490     // a function-try-block's catch statement.
16491     assert(!S->isDeclScope(PrevDecl));
16492     if (isDeclInScope(PrevDecl, CurContext, S)) {
16493       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16494         << D.getIdentifier();
16495       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16496       Invalid = true;
16497     } else if (PrevDecl->isTemplateParameter())
16498       // Maybe we will complain about the shadowed template parameter.
16499       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16500   }
16501 
16502   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16503     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16504       << D.getCXXScopeSpec().getRange();
16505     Invalid = true;
16506   }
16507 
16508   VarDecl *ExDecl = BuildExceptionDeclaration(
16509       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16510   if (Invalid)
16511     ExDecl->setInvalidDecl();
16512 
16513   // Add the exception declaration into this scope.
16514   if (II)
16515     PushOnScopeChains(ExDecl, S);
16516   else
16517     CurContext->addDecl(ExDecl);
16518 
16519   ProcessDeclAttributes(S, ExDecl, D);
16520   return ExDecl;
16521 }
16522 
16523 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16524                                          Expr *AssertExpr,
16525                                          Expr *AssertMessageExpr,
16526                                          SourceLocation RParenLoc) {
16527   StringLiteral *AssertMessage =
16528       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16529 
16530   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16531     return nullptr;
16532 
16533   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16534                                       AssertMessage, RParenLoc, false);
16535 }
16536 
16537 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16538                                          Expr *AssertExpr,
16539                                          StringLiteral *AssertMessage,
16540                                          SourceLocation RParenLoc,
16541                                          bool Failed) {
16542   assert(AssertExpr != nullptr && "Expected non-null condition");
16543   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16544       !Failed) {
16545     // In a static_assert-declaration, the constant-expression shall be a
16546     // constant expression that can be contextually converted to bool.
16547     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16548     if (Converted.isInvalid())
16549       Failed = true;
16550 
16551     ExprResult FullAssertExpr =
16552         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16553                             /*DiscardedValue*/ false,
16554                             /*IsConstexpr*/ true);
16555     if (FullAssertExpr.isInvalid())
16556       Failed = true;
16557     else
16558       AssertExpr = FullAssertExpr.get();
16559 
16560     llvm::APSInt Cond;
16561     if (!Failed && VerifyIntegerConstantExpression(
16562                        AssertExpr, &Cond,
16563                        diag::err_static_assert_expression_is_not_constant)
16564                        .isInvalid())
16565       Failed = true;
16566 
16567     if (!Failed && !Cond) {
16568       SmallString<256> MsgBuffer;
16569       llvm::raw_svector_ostream Msg(MsgBuffer);
16570       if (AssertMessage)
16571         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16572 
16573       Expr *InnerCond = nullptr;
16574       std::string InnerCondDescription;
16575       std::tie(InnerCond, InnerCondDescription) =
16576         findFailedBooleanCondition(Converted.get());
16577       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16578         // Drill down into concept specialization expressions to see why they
16579         // weren't satisfied.
16580         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16581           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16582         ConstraintSatisfaction Satisfaction;
16583         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16584           DiagnoseUnsatisfiedConstraint(Satisfaction);
16585       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16586                            && !isa<IntegerLiteral>(InnerCond)) {
16587         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16588           << InnerCondDescription << !AssertMessage
16589           << Msg.str() << InnerCond->getSourceRange();
16590       } else {
16591         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16592           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16593       }
16594       Failed = true;
16595     }
16596   } else {
16597     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16598                                                     /*DiscardedValue*/false,
16599                                                     /*IsConstexpr*/true);
16600     if (FullAssertExpr.isInvalid())
16601       Failed = true;
16602     else
16603       AssertExpr = FullAssertExpr.get();
16604   }
16605 
16606   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16607                                         AssertExpr, AssertMessage, RParenLoc,
16608                                         Failed);
16609 
16610   CurContext->addDecl(Decl);
16611   return Decl;
16612 }
16613 
16614 /// Perform semantic analysis of the given friend type declaration.
16615 ///
16616 /// \returns A friend declaration that.
16617 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16618                                       SourceLocation FriendLoc,
16619                                       TypeSourceInfo *TSInfo) {
16620   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16621 
16622   QualType T = TSInfo->getType();
16623   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16624 
16625   // C++03 [class.friend]p2:
16626   //   An elaborated-type-specifier shall be used in a friend declaration
16627   //   for a class.*
16628   //
16629   //   * The class-key of the elaborated-type-specifier is required.
16630   if (!CodeSynthesisContexts.empty()) {
16631     // Do not complain about the form of friend template types during any kind
16632     // of code synthesis. For template instantiation, we will have complained
16633     // when the template was defined.
16634   } else {
16635     if (!T->isElaboratedTypeSpecifier()) {
16636       // If we evaluated the type to a record type, suggest putting
16637       // a tag in front.
16638       if (const RecordType *RT = T->getAs<RecordType>()) {
16639         RecordDecl *RD = RT->getDecl();
16640 
16641         SmallString<16> InsertionText(" ");
16642         InsertionText += RD->getKindName();
16643 
16644         Diag(TypeRange.getBegin(),
16645              getLangOpts().CPlusPlus11 ?
16646                diag::warn_cxx98_compat_unelaborated_friend_type :
16647                diag::ext_unelaborated_friend_type)
16648           << (unsigned) RD->getTagKind()
16649           << T
16650           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16651                                         InsertionText);
16652       } else {
16653         Diag(FriendLoc,
16654              getLangOpts().CPlusPlus11 ?
16655                diag::warn_cxx98_compat_nonclass_type_friend :
16656                diag::ext_nonclass_type_friend)
16657           << T
16658           << TypeRange;
16659       }
16660     } else if (T->getAs<EnumType>()) {
16661       Diag(FriendLoc,
16662            getLangOpts().CPlusPlus11 ?
16663              diag::warn_cxx98_compat_enum_friend :
16664              diag::ext_enum_friend)
16665         << T
16666         << TypeRange;
16667     }
16668 
16669     // C++11 [class.friend]p3:
16670     //   A friend declaration that does not declare a function shall have one
16671     //   of the following forms:
16672     //     friend elaborated-type-specifier ;
16673     //     friend simple-type-specifier ;
16674     //     friend typename-specifier ;
16675     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16676       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16677   }
16678 
16679   //   If the type specifier in a friend declaration designates a (possibly
16680   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16681   //   the friend declaration is ignored.
16682   return FriendDecl::Create(Context, CurContext,
16683                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16684                             FriendLoc);
16685 }
16686 
16687 /// Handle a friend tag declaration where the scope specifier was
16688 /// templated.
16689 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16690                                     unsigned TagSpec, SourceLocation TagLoc,
16691                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16692                                     SourceLocation NameLoc,
16693                                     const ParsedAttributesView &Attr,
16694                                     MultiTemplateParamsArg TempParamLists) {
16695   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16696 
16697   bool IsMemberSpecialization = false;
16698   bool Invalid = false;
16699 
16700   if (TemplateParameterList *TemplateParams =
16701           MatchTemplateParametersToScopeSpecifier(
16702               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16703               IsMemberSpecialization, Invalid)) {
16704     if (TemplateParams->size() > 0) {
16705       // This is a declaration of a class template.
16706       if (Invalid)
16707         return nullptr;
16708 
16709       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16710                                 NameLoc, Attr, TemplateParams, AS_public,
16711                                 /*ModulePrivateLoc=*/SourceLocation(),
16712                                 FriendLoc, TempParamLists.size() - 1,
16713                                 TempParamLists.data()).get();
16714     } else {
16715       // The "template<>" header is extraneous.
16716       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16717         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16718       IsMemberSpecialization = true;
16719     }
16720   }
16721 
16722   if (Invalid) return nullptr;
16723 
16724   bool isAllExplicitSpecializations = true;
16725   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16726     if (TempParamLists[I]->size()) {
16727       isAllExplicitSpecializations = false;
16728       break;
16729     }
16730   }
16731 
16732   // FIXME: don't ignore attributes.
16733 
16734   // If it's explicit specializations all the way down, just forget
16735   // about the template header and build an appropriate non-templated
16736   // friend.  TODO: for source fidelity, remember the headers.
16737   if (isAllExplicitSpecializations) {
16738     if (SS.isEmpty()) {
16739       bool Owned = false;
16740       bool IsDependent = false;
16741       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16742                       Attr, AS_public,
16743                       /*ModulePrivateLoc=*/SourceLocation(),
16744                       MultiTemplateParamsArg(), Owned, IsDependent,
16745                       /*ScopedEnumKWLoc=*/SourceLocation(),
16746                       /*ScopedEnumUsesClassTag=*/false,
16747                       /*UnderlyingType=*/TypeResult(),
16748                       /*IsTypeSpecifier=*/false,
16749                       /*IsTemplateParamOrArg=*/false);
16750     }
16751 
16752     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16753     ElaboratedTypeKeyword Keyword
16754       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16755     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16756                                    *Name, NameLoc);
16757     if (T.isNull())
16758       return nullptr;
16759 
16760     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16761     if (isa<DependentNameType>(T)) {
16762       DependentNameTypeLoc TL =
16763           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16764       TL.setElaboratedKeywordLoc(TagLoc);
16765       TL.setQualifierLoc(QualifierLoc);
16766       TL.setNameLoc(NameLoc);
16767     } else {
16768       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16769       TL.setElaboratedKeywordLoc(TagLoc);
16770       TL.setQualifierLoc(QualifierLoc);
16771       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16772     }
16773 
16774     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16775                                             TSI, FriendLoc, TempParamLists);
16776     Friend->setAccess(AS_public);
16777     CurContext->addDecl(Friend);
16778     return Friend;
16779   }
16780 
16781   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16782 
16783 
16784 
16785   // Handle the case of a templated-scope friend class.  e.g.
16786   //   template <class T> class A<T>::B;
16787   // FIXME: we don't support these right now.
16788   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16789     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16790   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16791   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16792   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16793   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16794   TL.setElaboratedKeywordLoc(TagLoc);
16795   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16796   TL.setNameLoc(NameLoc);
16797 
16798   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16799                                           TSI, FriendLoc, TempParamLists);
16800   Friend->setAccess(AS_public);
16801   Friend->setUnsupportedFriend(true);
16802   CurContext->addDecl(Friend);
16803   return Friend;
16804 }
16805 
16806 /// Handle a friend type declaration.  This works in tandem with
16807 /// ActOnTag.
16808 ///
16809 /// Notes on friend class templates:
16810 ///
16811 /// We generally treat friend class declarations as if they were
16812 /// declaring a class.  So, for example, the elaborated type specifier
16813 /// in a friend declaration is required to obey the restrictions of a
16814 /// class-head (i.e. no typedefs in the scope chain), template
16815 /// parameters are required to match up with simple template-ids, &c.
16816 /// However, unlike when declaring a template specialization, it's
16817 /// okay to refer to a template specialization without an empty
16818 /// template parameter declaration, e.g.
16819 ///   friend class A<T>::B<unsigned>;
16820 /// We permit this as a special case; if there are any template
16821 /// parameters present at all, require proper matching, i.e.
16822 ///   template <> template \<class T> friend class A<int>::B;
16823 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16824                                 MultiTemplateParamsArg TempParams) {
16825   SourceLocation Loc = DS.getBeginLoc();
16826 
16827   assert(DS.isFriendSpecified());
16828   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16829 
16830   // C++ [class.friend]p3:
16831   // A friend declaration that does not declare a function shall have one of
16832   // the following forms:
16833   //     friend elaborated-type-specifier ;
16834   //     friend simple-type-specifier ;
16835   //     friend typename-specifier ;
16836   //
16837   // Any declaration with a type qualifier does not have that form. (It's
16838   // legal to specify a qualified type as a friend, you just can't write the
16839   // keywords.)
16840   if (DS.getTypeQualifiers()) {
16841     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16842       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16843     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16844       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16845     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16846       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16847     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16848       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16849     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16850       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16851   }
16852 
16853   // Try to convert the decl specifier to a type.  This works for
16854   // friend templates because ActOnTag never produces a ClassTemplateDecl
16855   // for a TUK_Friend.
16856   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16857   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16858   QualType T = TSI->getType();
16859   if (TheDeclarator.isInvalidType())
16860     return nullptr;
16861 
16862   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16863     return nullptr;
16864 
16865   // This is definitely an error in C++98.  It's probably meant to
16866   // be forbidden in C++0x, too, but the specification is just
16867   // poorly written.
16868   //
16869   // The problem is with declarations like the following:
16870   //   template <T> friend A<T>::foo;
16871   // where deciding whether a class C is a friend or not now hinges
16872   // on whether there exists an instantiation of A that causes
16873   // 'foo' to equal C.  There are restrictions on class-heads
16874   // (which we declare (by fiat) elaborated friend declarations to
16875   // be) that makes this tractable.
16876   //
16877   // FIXME: handle "template <> friend class A<T>;", which
16878   // is possibly well-formed?  Who even knows?
16879   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16880     Diag(Loc, diag::err_tagless_friend_type_template)
16881       << DS.getSourceRange();
16882     return nullptr;
16883   }
16884 
16885   // C++98 [class.friend]p1: A friend of a class is a function
16886   //   or class that is not a member of the class . . .
16887   // This is fixed in DR77, which just barely didn't make the C++03
16888   // deadline.  It's also a very silly restriction that seriously
16889   // affects inner classes and which nobody else seems to implement;
16890   // thus we never diagnose it, not even in -pedantic.
16891   //
16892   // But note that we could warn about it: it's always useless to
16893   // friend one of your own members (it's not, however, worthless to
16894   // friend a member of an arbitrary specialization of your template).
16895 
16896   Decl *D;
16897   if (!TempParams.empty())
16898     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16899                                    TempParams,
16900                                    TSI,
16901                                    DS.getFriendSpecLoc());
16902   else
16903     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16904 
16905   if (!D)
16906     return nullptr;
16907 
16908   D->setAccess(AS_public);
16909   CurContext->addDecl(D);
16910 
16911   return D;
16912 }
16913 
16914 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16915                                         MultiTemplateParamsArg TemplateParams) {
16916   const DeclSpec &DS = D.getDeclSpec();
16917 
16918   assert(DS.isFriendSpecified());
16919   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16920 
16921   SourceLocation Loc = D.getIdentifierLoc();
16922   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16923 
16924   // C++ [class.friend]p1
16925   //   A friend of a class is a function or class....
16926   // Note that this sees through typedefs, which is intended.
16927   // It *doesn't* see through dependent types, which is correct
16928   // according to [temp.arg.type]p3:
16929   //   If a declaration acquires a function type through a
16930   //   type dependent on a template-parameter and this causes
16931   //   a declaration that does not use the syntactic form of a
16932   //   function declarator to have a function type, the program
16933   //   is ill-formed.
16934   if (!TInfo->getType()->isFunctionType()) {
16935     Diag(Loc, diag::err_unexpected_friend);
16936 
16937     // It might be worthwhile to try to recover by creating an
16938     // appropriate declaration.
16939     return nullptr;
16940   }
16941 
16942   // C++ [namespace.memdef]p3
16943   //  - If a friend declaration in a non-local class first declares a
16944   //    class or function, the friend class or function is a member
16945   //    of the innermost enclosing namespace.
16946   //  - The name of the friend is not found by simple name lookup
16947   //    until a matching declaration is provided in that namespace
16948   //    scope (either before or after the class declaration granting
16949   //    friendship).
16950   //  - If a friend function is called, its name may be found by the
16951   //    name lookup that considers functions from namespaces and
16952   //    classes associated with the types of the function arguments.
16953   //  - When looking for a prior declaration of a class or a function
16954   //    declared as a friend, scopes outside the innermost enclosing
16955   //    namespace scope are not considered.
16956 
16957   CXXScopeSpec &SS = D.getCXXScopeSpec();
16958   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16959   assert(NameInfo.getName());
16960 
16961   // Check for unexpanded parameter packs.
16962   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16963       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16964       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16965     return nullptr;
16966 
16967   // The context we found the declaration in, or in which we should
16968   // create the declaration.
16969   DeclContext *DC;
16970   Scope *DCScope = S;
16971   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16972                         ForExternalRedeclaration);
16973 
16974   // There are five cases here.
16975   //   - There's no scope specifier and we're in a local class. Only look
16976   //     for functions declared in the immediately-enclosing block scope.
16977   // We recover from invalid scope qualifiers as if they just weren't there.
16978   FunctionDecl *FunctionContainingLocalClass = nullptr;
16979   if ((SS.isInvalid() || !SS.isSet()) &&
16980       (FunctionContainingLocalClass =
16981            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16982     // C++11 [class.friend]p11:
16983     //   If a friend declaration appears in a local class and the name
16984     //   specified is an unqualified name, a prior declaration is
16985     //   looked up without considering scopes that are outside the
16986     //   innermost enclosing non-class scope. For a friend function
16987     //   declaration, if there is no prior declaration, the program is
16988     //   ill-formed.
16989 
16990     // Find the innermost enclosing non-class scope. This is the block
16991     // scope containing the local class definition (or for a nested class,
16992     // the outer local class).
16993     DCScope = S->getFnParent();
16994 
16995     // Look up the function name in the scope.
16996     Previous.clear(LookupLocalFriendName);
16997     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16998 
16999     if (!Previous.empty()) {
17000       // All possible previous declarations must have the same context:
17001       // either they were declared at block scope or they are members of
17002       // one of the enclosing local classes.
17003       DC = Previous.getRepresentativeDecl()->getDeclContext();
17004     } else {
17005       // This is ill-formed, but provide the context that we would have
17006       // declared the function in, if we were permitted to, for error recovery.
17007       DC = FunctionContainingLocalClass;
17008     }
17009     adjustContextForLocalExternDecl(DC);
17010 
17011     // C++ [class.friend]p6:
17012     //   A function can be defined in a friend declaration of a class if and
17013     //   only if the class is a non-local class (9.8), the function name is
17014     //   unqualified, and the function has namespace scope.
17015     if (D.isFunctionDefinition()) {
17016       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17017     }
17018 
17019   //   - There's no scope specifier, in which case we just go to the
17020   //     appropriate scope and look for a function or function template
17021   //     there as appropriate.
17022   } else if (SS.isInvalid() || !SS.isSet()) {
17023     // C++11 [namespace.memdef]p3:
17024     //   If the name in a friend declaration is neither qualified nor
17025     //   a template-id and the declaration is a function or an
17026     //   elaborated-type-specifier, the lookup to determine whether
17027     //   the entity has been previously declared shall not consider
17028     //   any scopes outside the innermost enclosing namespace.
17029     bool isTemplateId =
17030         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17031 
17032     // Find the appropriate context according to the above.
17033     DC = CurContext;
17034 
17035     // Skip class contexts.  If someone can cite chapter and verse
17036     // for this behavior, that would be nice --- it's what GCC and
17037     // EDG do, and it seems like a reasonable intent, but the spec
17038     // really only says that checks for unqualified existing
17039     // declarations should stop at the nearest enclosing namespace,
17040     // not that they should only consider the nearest enclosing
17041     // namespace.
17042     while (DC->isRecord())
17043       DC = DC->getParent();
17044 
17045     DeclContext *LookupDC = DC->getNonTransparentContext();
17046     while (true) {
17047       LookupQualifiedName(Previous, LookupDC);
17048 
17049       if (!Previous.empty()) {
17050         DC = LookupDC;
17051         break;
17052       }
17053 
17054       if (isTemplateId) {
17055         if (isa<TranslationUnitDecl>(LookupDC)) break;
17056       } else {
17057         if (LookupDC->isFileContext()) break;
17058       }
17059       LookupDC = LookupDC->getParent();
17060     }
17061 
17062     DCScope = getScopeForDeclContext(S, DC);
17063 
17064   //   - There's a non-dependent scope specifier, in which case we
17065   //     compute it and do a previous lookup there for a function
17066   //     or function template.
17067   } else if (!SS.getScopeRep()->isDependent()) {
17068     DC = computeDeclContext(SS);
17069     if (!DC) return nullptr;
17070 
17071     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17072 
17073     LookupQualifiedName(Previous, DC);
17074 
17075     // C++ [class.friend]p1: A friend of a class is a function or
17076     //   class that is not a member of the class . . .
17077     if (DC->Equals(CurContext))
17078       Diag(DS.getFriendSpecLoc(),
17079            getLangOpts().CPlusPlus11 ?
17080              diag::warn_cxx98_compat_friend_is_member :
17081              diag::err_friend_is_member);
17082 
17083     if (D.isFunctionDefinition()) {
17084       // C++ [class.friend]p6:
17085       //   A function can be defined in a friend declaration of a class if and
17086       //   only if the class is a non-local class (9.8), the function name is
17087       //   unqualified, and the function has namespace scope.
17088       //
17089       // FIXME: We should only do this if the scope specifier names the
17090       // innermost enclosing namespace; otherwise the fixit changes the
17091       // meaning of the code.
17092       SemaDiagnosticBuilder DB
17093         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17094 
17095       DB << SS.getScopeRep();
17096       if (DC->isFileContext())
17097         DB << FixItHint::CreateRemoval(SS.getRange());
17098       SS.clear();
17099     }
17100 
17101   //   - There's a scope specifier that does not match any template
17102   //     parameter lists, in which case we use some arbitrary context,
17103   //     create a method or method template, and wait for instantiation.
17104   //   - There's a scope specifier that does match some template
17105   //     parameter lists, which we don't handle right now.
17106   } else {
17107     if (D.isFunctionDefinition()) {
17108       // C++ [class.friend]p6:
17109       //   A function can be defined in a friend declaration of a class if and
17110       //   only if the class is a non-local class (9.8), the function name is
17111       //   unqualified, and the function has namespace scope.
17112       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17113         << SS.getScopeRep();
17114     }
17115 
17116     DC = CurContext;
17117     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17118   }
17119 
17120   if (!DC->isRecord()) {
17121     int DiagArg = -1;
17122     switch (D.getName().getKind()) {
17123     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17124     case UnqualifiedIdKind::IK_ConstructorName:
17125       DiagArg = 0;
17126       break;
17127     case UnqualifiedIdKind::IK_DestructorName:
17128       DiagArg = 1;
17129       break;
17130     case UnqualifiedIdKind::IK_ConversionFunctionId:
17131       DiagArg = 2;
17132       break;
17133     case UnqualifiedIdKind::IK_DeductionGuideName:
17134       DiagArg = 3;
17135       break;
17136     case UnqualifiedIdKind::IK_Identifier:
17137     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17138     case UnqualifiedIdKind::IK_LiteralOperatorId:
17139     case UnqualifiedIdKind::IK_OperatorFunctionId:
17140     case UnqualifiedIdKind::IK_TemplateId:
17141       break;
17142     }
17143     // This implies that it has to be an operator or function.
17144     if (DiagArg >= 0) {
17145       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17146       return nullptr;
17147     }
17148   }
17149 
17150   // FIXME: This is an egregious hack to cope with cases where the scope stack
17151   // does not contain the declaration context, i.e., in an out-of-line
17152   // definition of a class.
17153   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17154   if (!DCScope) {
17155     FakeDCScope.setEntity(DC);
17156     DCScope = &FakeDCScope;
17157   }
17158 
17159   bool AddToScope = true;
17160   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17161                                           TemplateParams, AddToScope);
17162   if (!ND) return nullptr;
17163 
17164   assert(ND->getLexicalDeclContext() == CurContext);
17165 
17166   // If we performed typo correction, we might have added a scope specifier
17167   // and changed the decl context.
17168   DC = ND->getDeclContext();
17169 
17170   // Add the function declaration to the appropriate lookup tables,
17171   // adjusting the redeclarations list as necessary.  We don't
17172   // want to do this yet if the friending class is dependent.
17173   //
17174   // Also update the scope-based lookup if the target context's
17175   // lookup context is in lexical scope.
17176   if (!CurContext->isDependentContext()) {
17177     DC = DC->getRedeclContext();
17178     DC->makeDeclVisibleInContext(ND);
17179     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17180       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17181   }
17182 
17183   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17184                                        D.getIdentifierLoc(), ND,
17185                                        DS.getFriendSpecLoc());
17186   FrD->setAccess(AS_public);
17187   CurContext->addDecl(FrD);
17188 
17189   if (ND->isInvalidDecl()) {
17190     FrD->setInvalidDecl();
17191   } else {
17192     if (DC->isRecord()) CheckFriendAccess(ND);
17193 
17194     FunctionDecl *FD;
17195     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17196       FD = FTD->getTemplatedDecl();
17197     else
17198       FD = cast<FunctionDecl>(ND);
17199 
17200     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17201     // default argument expression, that declaration shall be a definition
17202     // and shall be the only declaration of the function or function
17203     // template in the translation unit.
17204     if (functionDeclHasDefaultArgument(FD)) {
17205       // We can't look at FD->getPreviousDecl() because it may not have been set
17206       // if we're in a dependent context. If the function is known to be a
17207       // redeclaration, we will have narrowed Previous down to the right decl.
17208       if (D.isRedeclaration()) {
17209         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17210         Diag(Previous.getRepresentativeDecl()->getLocation(),
17211              diag::note_previous_declaration);
17212       } else if (!D.isFunctionDefinition())
17213         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17214     }
17215 
17216     // Mark templated-scope function declarations as unsupported.
17217     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17218       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17219         << SS.getScopeRep() << SS.getRange()
17220         << cast<CXXRecordDecl>(CurContext);
17221       FrD->setUnsupportedFriend(true);
17222     }
17223   }
17224 
17225   warnOnReservedIdentifier(ND);
17226 
17227   return ND;
17228 }
17229 
17230 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17231   AdjustDeclIfTemplate(Dcl);
17232 
17233   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17234   if (!Fn) {
17235     Diag(DelLoc, diag::err_deleted_non_function);
17236     return;
17237   }
17238 
17239   // Deleted function does not have a body.
17240   Fn->setWillHaveBody(false);
17241 
17242   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17243     // Don't consider the implicit declaration we generate for explicit
17244     // specializations. FIXME: Do not generate these implicit declarations.
17245     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17246          Prev->getPreviousDecl()) &&
17247         !Prev->isDefined()) {
17248       Diag(DelLoc, diag::err_deleted_decl_not_first);
17249       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17250            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17251                               : diag::note_previous_declaration);
17252       // We can't recover from this; the declaration might have already
17253       // been used.
17254       Fn->setInvalidDecl();
17255       return;
17256     }
17257 
17258     // To maintain the invariant that functions are only deleted on their first
17259     // declaration, mark the implicitly-instantiated declaration of the
17260     // explicitly-specialized function as deleted instead of marking the
17261     // instantiated redeclaration.
17262     Fn = Fn->getCanonicalDecl();
17263   }
17264 
17265   // dllimport/dllexport cannot be deleted.
17266   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17267     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17268     Fn->setInvalidDecl();
17269   }
17270 
17271   // C++11 [basic.start.main]p3:
17272   //   A program that defines main as deleted [...] is ill-formed.
17273   if (Fn->isMain())
17274     Diag(DelLoc, diag::err_deleted_main);
17275 
17276   // C++11 [dcl.fct.def.delete]p4:
17277   //  A deleted function is implicitly inline.
17278   Fn->setImplicitlyInline();
17279   Fn->setDeletedAsWritten();
17280 }
17281 
17282 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17283   if (!Dcl || Dcl->isInvalidDecl())
17284     return;
17285 
17286   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17287   if (!FD) {
17288     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17289       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17290         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17291         return;
17292       }
17293     }
17294 
17295     Diag(DefaultLoc, diag::err_default_special_members)
17296         << getLangOpts().CPlusPlus20;
17297     return;
17298   }
17299 
17300   // Reject if this can't possibly be a defaultable function.
17301   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17302   if (!DefKind &&
17303       // A dependent function that doesn't locally look defaultable can
17304       // still instantiate to a defaultable function if it's a constructor
17305       // or assignment operator.
17306       (!FD->isDependentContext() ||
17307        (!isa<CXXConstructorDecl>(FD) &&
17308         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17309     Diag(DefaultLoc, diag::err_default_special_members)
17310         << getLangOpts().CPlusPlus20;
17311     return;
17312   }
17313 
17314   // Issue compatibility warning. We already warned if the operator is
17315   // 'operator<=>' when parsing the '<=>' token.
17316   if (DefKind.isComparison() &&
17317       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17318     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17319                          ? diag::warn_cxx17_compat_defaulted_comparison
17320                          : diag::ext_defaulted_comparison);
17321   }
17322 
17323   FD->setDefaulted();
17324   FD->setExplicitlyDefaulted();
17325 
17326   // Defer checking functions that are defaulted in a dependent context.
17327   if (FD->isDependentContext())
17328     return;
17329 
17330   // Unset that we will have a body for this function. We might not,
17331   // if it turns out to be trivial, and we don't need this marking now
17332   // that we've marked it as defaulted.
17333   FD->setWillHaveBody(false);
17334 
17335   if (DefKind.isComparison()) {
17336     // If this comparison's defaulting occurs within the definition of its
17337     // lexical class context, we have to do the checking when complete.
17338     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17339       if (!RD->isCompleteDefinition())
17340         return;
17341   }
17342 
17343   // If this member fn was defaulted on its first declaration, we will have
17344   // already performed the checking in CheckCompletedCXXClass. Such a
17345   // declaration doesn't trigger an implicit definition.
17346   if (isa<CXXMethodDecl>(FD)) {
17347     const FunctionDecl *Primary = FD;
17348     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17349       // Ask the template instantiation pattern that actually had the
17350       // '= default' on it.
17351       Primary = Pattern;
17352     if (Primary->getCanonicalDecl()->isDefaulted())
17353       return;
17354   }
17355 
17356   if (DefKind.isComparison()) {
17357     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17358       FD->setInvalidDecl();
17359     else
17360       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17361   } else {
17362     auto *MD = cast<CXXMethodDecl>(FD);
17363 
17364     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17365       MD->setInvalidDecl();
17366     else
17367       DefineDefaultedFunction(*this, MD, DefaultLoc);
17368   }
17369 }
17370 
17371 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17372   for (Stmt *SubStmt : S->children()) {
17373     if (!SubStmt)
17374       continue;
17375     if (isa<ReturnStmt>(SubStmt))
17376       Self.Diag(SubStmt->getBeginLoc(),
17377                 diag::err_return_in_constructor_handler);
17378     if (!isa<Expr>(SubStmt))
17379       SearchForReturnInStmt(Self, SubStmt);
17380   }
17381 }
17382 
17383 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17384   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17385     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17386     SearchForReturnInStmt(*this, Handler);
17387   }
17388 }
17389 
17390 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17391                                FnBodyKind BodyKind) {
17392   switch (BodyKind) {
17393   case FnBodyKind::Delete:
17394     SetDeclDeleted(D, Loc);
17395     break;
17396   case FnBodyKind::Default:
17397     SetDeclDefaulted(D, Loc);
17398     break;
17399   case FnBodyKind::Other:
17400     llvm_unreachable(
17401         "Parsed function body should be '= delete;' or '= default;'");
17402   }
17403 }
17404 
17405 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17406                                              const CXXMethodDecl *Old) {
17407   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17408   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17409 
17410   if (OldFT->hasExtParameterInfos()) {
17411     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17412       // A parameter of the overriding method should be annotated with noescape
17413       // if the corresponding parameter of the overridden method is annotated.
17414       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17415           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17416         Diag(New->getParamDecl(I)->getLocation(),
17417              diag::warn_overriding_method_missing_noescape);
17418         Diag(Old->getParamDecl(I)->getLocation(),
17419              diag::note_overridden_marked_noescape);
17420       }
17421   }
17422 
17423   // Virtual overrides must have the same code_seg.
17424   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17425   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17426   if ((NewCSA || OldCSA) &&
17427       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17428     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17429     Diag(Old->getLocation(), diag::note_previous_declaration);
17430     return true;
17431   }
17432 
17433   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17434 
17435   // If the calling conventions match, everything is fine
17436   if (NewCC == OldCC)
17437     return false;
17438 
17439   // If the calling conventions mismatch because the new function is static,
17440   // suppress the calling convention mismatch error; the error about static
17441   // function override (err_static_overrides_virtual from
17442   // Sema::CheckFunctionDeclaration) is more clear.
17443   if (New->getStorageClass() == SC_Static)
17444     return false;
17445 
17446   Diag(New->getLocation(),
17447        diag::err_conflicting_overriding_cc_attributes)
17448     << New->getDeclName() << New->getType() << Old->getType();
17449   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17450   return true;
17451 }
17452 
17453 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17454                                              const CXXMethodDecl *Old) {
17455   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17456   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17457 
17458   if (Context.hasSameType(NewTy, OldTy) ||
17459       NewTy->isDependentType() || OldTy->isDependentType())
17460     return false;
17461 
17462   // Check if the return types are covariant
17463   QualType NewClassTy, OldClassTy;
17464 
17465   /// Both types must be pointers or references to classes.
17466   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17467     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17468       NewClassTy = NewPT->getPointeeType();
17469       OldClassTy = OldPT->getPointeeType();
17470     }
17471   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17472     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17473       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17474         NewClassTy = NewRT->getPointeeType();
17475         OldClassTy = OldRT->getPointeeType();
17476       }
17477     }
17478   }
17479 
17480   // The return types aren't either both pointers or references to a class type.
17481   if (NewClassTy.isNull()) {
17482     Diag(New->getLocation(),
17483          diag::err_different_return_type_for_overriding_virtual_function)
17484         << New->getDeclName() << NewTy << OldTy
17485         << New->getReturnTypeSourceRange();
17486     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17487         << Old->getReturnTypeSourceRange();
17488 
17489     return true;
17490   }
17491 
17492   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17493     // C++14 [class.virtual]p8:
17494     //   If the class type in the covariant return type of D::f differs from
17495     //   that of B::f, the class type in the return type of D::f shall be
17496     //   complete at the point of declaration of D::f or shall be the class
17497     //   type D.
17498     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17499       if (!RT->isBeingDefined() &&
17500           RequireCompleteType(New->getLocation(), NewClassTy,
17501                               diag::err_covariant_return_incomplete,
17502                               New->getDeclName()))
17503         return true;
17504     }
17505 
17506     // Check if the new class derives from the old class.
17507     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17508       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17509           << New->getDeclName() << NewTy << OldTy
17510           << New->getReturnTypeSourceRange();
17511       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17512           << Old->getReturnTypeSourceRange();
17513       return true;
17514     }
17515 
17516     // Check if we the conversion from derived to base is valid.
17517     if (CheckDerivedToBaseConversion(
17518             NewClassTy, OldClassTy,
17519             diag::err_covariant_return_inaccessible_base,
17520             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17521             New->getLocation(), New->getReturnTypeSourceRange(),
17522             New->getDeclName(), nullptr)) {
17523       // FIXME: this note won't trigger for delayed access control
17524       // diagnostics, and it's impossible to get an undelayed error
17525       // here from access control during the original parse because
17526       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17527       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17528           << Old->getReturnTypeSourceRange();
17529       return true;
17530     }
17531   }
17532 
17533   // The qualifiers of the return types must be the same.
17534   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17535     Diag(New->getLocation(),
17536          diag::err_covariant_return_type_different_qualifications)
17537         << New->getDeclName() << NewTy << OldTy
17538         << New->getReturnTypeSourceRange();
17539     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17540         << Old->getReturnTypeSourceRange();
17541     return true;
17542   }
17543 
17544 
17545   // The new class type must have the same or less qualifiers as the old type.
17546   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17547     Diag(New->getLocation(),
17548          diag::err_covariant_return_type_class_type_more_qualified)
17549         << New->getDeclName() << NewTy << OldTy
17550         << New->getReturnTypeSourceRange();
17551     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17552         << Old->getReturnTypeSourceRange();
17553     return true;
17554   }
17555 
17556   return false;
17557 }
17558 
17559 /// Mark the given method pure.
17560 ///
17561 /// \param Method the method to be marked pure.
17562 ///
17563 /// \param InitRange the source range that covers the "0" initializer.
17564 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17565   SourceLocation EndLoc = InitRange.getEnd();
17566   if (EndLoc.isValid())
17567     Method->setRangeEnd(EndLoc);
17568 
17569   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17570     Method->setPure();
17571     return false;
17572   }
17573 
17574   if (!Method->isInvalidDecl())
17575     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17576       << Method->getDeclName() << InitRange;
17577   return true;
17578 }
17579 
17580 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17581   if (D->getFriendObjectKind())
17582     Diag(D->getLocation(), diag::err_pure_friend);
17583   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17584     CheckPureMethod(M, ZeroLoc);
17585   else
17586     Diag(D->getLocation(), diag::err_illegal_initializer);
17587 }
17588 
17589 /// Determine whether the given declaration is a global variable or
17590 /// static data member.
17591 static bool isNonlocalVariable(const Decl *D) {
17592   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17593     return Var->hasGlobalStorage();
17594 
17595   return false;
17596 }
17597 
17598 /// Invoked when we are about to parse an initializer for the declaration
17599 /// 'Dcl'.
17600 ///
17601 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17602 /// static data member of class X, names should be looked up in the scope of
17603 /// class X. If the declaration had a scope specifier, a scope will have
17604 /// been created and passed in for this purpose. Otherwise, S will be null.
17605 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17606   // If there is no declaration, there was an error parsing it.
17607   if (!D || D->isInvalidDecl())
17608     return;
17609 
17610   // We will always have a nested name specifier here, but this declaration
17611   // might not be out of line if the specifier names the current namespace:
17612   //   extern int n;
17613   //   int ::n = 0;
17614   if (S && D->isOutOfLine())
17615     EnterDeclaratorContext(S, D->getDeclContext());
17616 
17617   // If we are parsing the initializer for a static data member, push a
17618   // new expression evaluation context that is associated with this static
17619   // data member.
17620   if (isNonlocalVariable(D))
17621     PushExpressionEvaluationContext(
17622         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17623 }
17624 
17625 /// Invoked after we are finished parsing an initializer for the declaration D.
17626 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17627   // If there is no declaration, there was an error parsing it.
17628   if (!D || D->isInvalidDecl())
17629     return;
17630 
17631   if (isNonlocalVariable(D))
17632     PopExpressionEvaluationContext();
17633 
17634   if (S && D->isOutOfLine())
17635     ExitDeclaratorContext(S);
17636 }
17637 
17638 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17639 /// C++ if/switch/while/for statement.
17640 /// e.g: "if (int x = f()) {...}"
17641 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17642   // C++ 6.4p2:
17643   // The declarator shall not specify a function or an array.
17644   // The type-specifier-seq shall not contain typedef and shall not declare a
17645   // new class or enumeration.
17646   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17647          "Parser allowed 'typedef' as storage class of condition decl.");
17648 
17649   Decl *Dcl = ActOnDeclarator(S, D);
17650   if (!Dcl)
17651     return true;
17652 
17653   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17654     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17655       << D.getSourceRange();
17656     return true;
17657   }
17658 
17659   return Dcl;
17660 }
17661 
17662 void Sema::LoadExternalVTableUses() {
17663   if (!ExternalSource)
17664     return;
17665 
17666   SmallVector<ExternalVTableUse, 4> VTables;
17667   ExternalSource->ReadUsedVTables(VTables);
17668   SmallVector<VTableUse, 4> NewUses;
17669   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17670     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17671       = VTablesUsed.find(VTables[I].Record);
17672     // Even if a definition wasn't required before, it may be required now.
17673     if (Pos != VTablesUsed.end()) {
17674       if (!Pos->second && VTables[I].DefinitionRequired)
17675         Pos->second = true;
17676       continue;
17677     }
17678 
17679     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17680     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17681   }
17682 
17683   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17684 }
17685 
17686 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17687                           bool DefinitionRequired) {
17688   // Ignore any vtable uses in unevaluated operands or for classes that do
17689   // not have a vtable.
17690   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17691       CurContext->isDependentContext() || isUnevaluatedContext())
17692     return;
17693   // Do not mark as used if compiling for the device outside of the target
17694   // region.
17695   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17696       !isInOpenMPDeclareTargetContext() &&
17697       !isInOpenMPTargetExecutionDirective()) {
17698     if (!DefinitionRequired)
17699       MarkVirtualMembersReferenced(Loc, Class);
17700     return;
17701   }
17702 
17703   // Try to insert this class into the map.
17704   LoadExternalVTableUses();
17705   Class = Class->getCanonicalDecl();
17706   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17707     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17708   if (!Pos.second) {
17709     // If we already had an entry, check to see if we are promoting this vtable
17710     // to require a definition. If so, we need to reappend to the VTableUses
17711     // list, since we may have already processed the first entry.
17712     if (DefinitionRequired && !Pos.first->second) {
17713       Pos.first->second = true;
17714     } else {
17715       // Otherwise, we can early exit.
17716       return;
17717     }
17718   } else {
17719     // The Microsoft ABI requires that we perform the destructor body
17720     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17721     // the deleting destructor is emitted with the vtable, not with the
17722     // destructor definition as in the Itanium ABI.
17723     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17724       CXXDestructorDecl *DD = Class->getDestructor();
17725       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17726         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17727           // If this is an out-of-line declaration, marking it referenced will
17728           // not do anything. Manually call CheckDestructor to look up operator
17729           // delete().
17730           ContextRAII SavedContext(*this, DD);
17731           CheckDestructor(DD);
17732         } else {
17733           MarkFunctionReferenced(Loc, Class->getDestructor());
17734         }
17735       }
17736     }
17737   }
17738 
17739   // Local classes need to have their virtual members marked
17740   // immediately. For all other classes, we mark their virtual members
17741   // at the end of the translation unit.
17742   if (Class->isLocalClass())
17743     MarkVirtualMembersReferenced(Loc, Class);
17744   else
17745     VTableUses.push_back(std::make_pair(Class, Loc));
17746 }
17747 
17748 bool Sema::DefineUsedVTables() {
17749   LoadExternalVTableUses();
17750   if (VTableUses.empty())
17751     return false;
17752 
17753   // Note: The VTableUses vector could grow as a result of marking
17754   // the members of a class as "used", so we check the size each
17755   // time through the loop and prefer indices (which are stable) to
17756   // iterators (which are not).
17757   bool DefinedAnything = false;
17758   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17759     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17760     if (!Class)
17761       continue;
17762     TemplateSpecializationKind ClassTSK =
17763         Class->getTemplateSpecializationKind();
17764 
17765     SourceLocation Loc = VTableUses[I].second;
17766 
17767     bool DefineVTable = true;
17768 
17769     // If this class has a key function, but that key function is
17770     // defined in another translation unit, we don't need to emit the
17771     // vtable even though we're using it.
17772     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17773     if (KeyFunction && !KeyFunction->hasBody()) {
17774       // The key function is in another translation unit.
17775       DefineVTable = false;
17776       TemplateSpecializationKind TSK =
17777           KeyFunction->getTemplateSpecializationKind();
17778       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17779              TSK != TSK_ImplicitInstantiation &&
17780              "Instantiations don't have key functions");
17781       (void)TSK;
17782     } else if (!KeyFunction) {
17783       // If we have a class with no key function that is the subject
17784       // of an explicit instantiation declaration, suppress the
17785       // vtable; it will live with the explicit instantiation
17786       // definition.
17787       bool IsExplicitInstantiationDeclaration =
17788           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17789       for (auto R : Class->redecls()) {
17790         TemplateSpecializationKind TSK
17791           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17792         if (TSK == TSK_ExplicitInstantiationDeclaration)
17793           IsExplicitInstantiationDeclaration = true;
17794         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17795           IsExplicitInstantiationDeclaration = false;
17796           break;
17797         }
17798       }
17799 
17800       if (IsExplicitInstantiationDeclaration)
17801         DefineVTable = false;
17802     }
17803 
17804     // The exception specifications for all virtual members may be needed even
17805     // if we are not providing an authoritative form of the vtable in this TU.
17806     // We may choose to emit it available_externally anyway.
17807     if (!DefineVTable) {
17808       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17809       continue;
17810     }
17811 
17812     // Mark all of the virtual members of this class as referenced, so
17813     // that we can build a vtable. Then, tell the AST consumer that a
17814     // vtable for this class is required.
17815     DefinedAnything = true;
17816     MarkVirtualMembersReferenced(Loc, Class);
17817     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17818     if (VTablesUsed[Canonical])
17819       Consumer.HandleVTable(Class);
17820 
17821     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17822     // no key function or the key function is inlined. Don't warn in C++ ABIs
17823     // that lack key functions, since the user won't be able to make one.
17824     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17825         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17826         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17827       const FunctionDecl *KeyFunctionDef = nullptr;
17828       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17829                            KeyFunctionDef->isInlined()))
17830         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17831     }
17832   }
17833   VTableUses.clear();
17834 
17835   return DefinedAnything;
17836 }
17837 
17838 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17839                                                  const CXXRecordDecl *RD) {
17840   for (const auto *I : RD->methods())
17841     if (I->isVirtual() && !I->isPure())
17842       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17843 }
17844 
17845 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17846                                         const CXXRecordDecl *RD,
17847                                         bool ConstexprOnly) {
17848   // Mark all functions which will appear in RD's vtable as used.
17849   CXXFinalOverriderMap FinalOverriders;
17850   RD->getFinalOverriders(FinalOverriders);
17851   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17852                                             E = FinalOverriders.end();
17853        I != E; ++I) {
17854     for (OverridingMethods::const_iterator OI = I->second.begin(),
17855                                            OE = I->second.end();
17856          OI != OE; ++OI) {
17857       assert(OI->second.size() > 0 && "no final overrider");
17858       CXXMethodDecl *Overrider = OI->second.front().Method;
17859 
17860       // C++ [basic.def.odr]p2:
17861       //   [...] A virtual member function is used if it is not pure. [...]
17862       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17863         MarkFunctionReferenced(Loc, Overrider);
17864     }
17865   }
17866 
17867   // Only classes that have virtual bases need a VTT.
17868   if (RD->getNumVBases() == 0)
17869     return;
17870 
17871   for (const auto &I : RD->bases()) {
17872     const auto *Base =
17873         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17874     if (Base->getNumVBases() == 0)
17875       continue;
17876     MarkVirtualMembersReferenced(Loc, Base);
17877   }
17878 }
17879 
17880 /// SetIvarInitializers - This routine builds initialization ASTs for the
17881 /// Objective-C implementation whose ivars need be initialized.
17882 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17883   if (!getLangOpts().CPlusPlus)
17884     return;
17885   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17886     SmallVector<ObjCIvarDecl*, 8> ivars;
17887     CollectIvarsToConstructOrDestruct(OID, ivars);
17888     if (ivars.empty())
17889       return;
17890     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17891     for (unsigned i = 0; i < ivars.size(); i++) {
17892       FieldDecl *Field = ivars[i];
17893       if (Field->isInvalidDecl())
17894         continue;
17895 
17896       CXXCtorInitializer *Member;
17897       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17898       InitializationKind InitKind =
17899         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17900 
17901       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17902       ExprResult MemberInit =
17903         InitSeq.Perform(*this, InitEntity, InitKind, None);
17904       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17905       // Note, MemberInit could actually come back empty if no initialization
17906       // is required (e.g., because it would call a trivial default constructor)
17907       if (!MemberInit.get() || MemberInit.isInvalid())
17908         continue;
17909 
17910       Member =
17911         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17912                                          SourceLocation(),
17913                                          MemberInit.getAs<Expr>(),
17914                                          SourceLocation());
17915       AllToInit.push_back(Member);
17916 
17917       // Be sure that the destructor is accessible and is marked as referenced.
17918       if (const RecordType *RecordTy =
17919               Context.getBaseElementType(Field->getType())
17920                   ->getAs<RecordType>()) {
17921         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17922         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17923           MarkFunctionReferenced(Field->getLocation(), Destructor);
17924           CheckDestructorAccess(Field->getLocation(), Destructor,
17925                             PDiag(diag::err_access_dtor_ivar)
17926                               << Context.getBaseElementType(Field->getType()));
17927         }
17928       }
17929     }
17930     ObjCImplementation->setIvarInitializers(Context,
17931                                             AllToInit.data(), AllToInit.size());
17932   }
17933 }
17934 
17935 static
17936 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17937                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17938                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17939                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17940                            Sema &S) {
17941   if (Ctor->isInvalidDecl())
17942     return;
17943 
17944   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17945 
17946   // Target may not be determinable yet, for instance if this is a dependent
17947   // call in an uninstantiated template.
17948   if (Target) {
17949     const FunctionDecl *FNTarget = nullptr;
17950     (void)Target->hasBody(FNTarget);
17951     Target = const_cast<CXXConstructorDecl*>(
17952       cast_or_null<CXXConstructorDecl>(FNTarget));
17953   }
17954 
17955   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17956                      // Avoid dereferencing a null pointer here.
17957                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17958 
17959   if (!Current.insert(Canonical).second)
17960     return;
17961 
17962   // We know that beyond here, we aren't chaining into a cycle.
17963   if (!Target || !Target->isDelegatingConstructor() ||
17964       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17965     Valid.insert(Current.begin(), Current.end());
17966     Current.clear();
17967   // We've hit a cycle.
17968   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17969              Current.count(TCanonical)) {
17970     // If we haven't diagnosed this cycle yet, do so now.
17971     if (!Invalid.count(TCanonical)) {
17972       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17973              diag::warn_delegating_ctor_cycle)
17974         << Ctor;
17975 
17976       // Don't add a note for a function delegating directly to itself.
17977       if (TCanonical != Canonical)
17978         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17979 
17980       CXXConstructorDecl *C = Target;
17981       while (C->getCanonicalDecl() != Canonical) {
17982         const FunctionDecl *FNTarget = nullptr;
17983         (void)C->getTargetConstructor()->hasBody(FNTarget);
17984         assert(FNTarget && "Ctor cycle through bodiless function");
17985 
17986         C = const_cast<CXXConstructorDecl*>(
17987           cast<CXXConstructorDecl>(FNTarget));
17988         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17989       }
17990     }
17991 
17992     Invalid.insert(Current.begin(), Current.end());
17993     Current.clear();
17994   } else {
17995     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17996   }
17997 }
17998 
17999 
18000 void Sema::CheckDelegatingCtorCycles() {
18001   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18002 
18003   for (DelegatingCtorDeclsType::iterator
18004          I = DelegatingCtorDecls.begin(ExternalSource),
18005          E = DelegatingCtorDecls.end();
18006        I != E; ++I)
18007     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18008 
18009   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18010     (*CI)->setInvalidDecl();
18011 }
18012 
18013 namespace {
18014   /// AST visitor that finds references to the 'this' expression.
18015   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18016     Sema &S;
18017 
18018   public:
18019     explicit FindCXXThisExpr(Sema &S) : S(S) { }
18020 
18021     bool VisitCXXThisExpr(CXXThisExpr *E) {
18022       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18023         << E->isImplicit();
18024       return false;
18025     }
18026   };
18027 }
18028 
18029 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18030   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18031   if (!TSInfo)
18032     return false;
18033 
18034   TypeLoc TL = TSInfo->getTypeLoc();
18035   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18036   if (!ProtoTL)
18037     return false;
18038 
18039   // C++11 [expr.prim.general]p3:
18040   //   [The expression this] shall not appear before the optional
18041   //   cv-qualifier-seq and it shall not appear within the declaration of a
18042   //   static member function (although its type and value category are defined
18043   //   within a static member function as they are within a non-static member
18044   //   function). [ Note: this is because declaration matching does not occur
18045   //  until the complete declarator is known. - end note ]
18046   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18047   FindCXXThisExpr Finder(*this);
18048 
18049   // If the return type came after the cv-qualifier-seq, check it now.
18050   if (Proto->hasTrailingReturn() &&
18051       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18052     return true;
18053 
18054   // Check the exception specification.
18055   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18056     return true;
18057 
18058   // Check the trailing requires clause
18059   if (Expr *E = Method->getTrailingRequiresClause())
18060     if (!Finder.TraverseStmt(E))
18061       return true;
18062 
18063   return checkThisInStaticMemberFunctionAttributes(Method);
18064 }
18065 
18066 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18067   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18068   if (!TSInfo)
18069     return false;
18070 
18071   TypeLoc TL = TSInfo->getTypeLoc();
18072   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18073   if (!ProtoTL)
18074     return false;
18075 
18076   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18077   FindCXXThisExpr Finder(*this);
18078 
18079   switch (Proto->getExceptionSpecType()) {
18080   case EST_Unparsed:
18081   case EST_Uninstantiated:
18082   case EST_Unevaluated:
18083   case EST_BasicNoexcept:
18084   case EST_NoThrow:
18085   case EST_DynamicNone:
18086   case EST_MSAny:
18087   case EST_None:
18088     break;
18089 
18090   case EST_DependentNoexcept:
18091   case EST_NoexceptFalse:
18092   case EST_NoexceptTrue:
18093     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18094       return true;
18095     LLVM_FALLTHROUGH;
18096 
18097   case EST_Dynamic:
18098     for (const auto &E : Proto->exceptions()) {
18099       if (!Finder.TraverseType(E))
18100         return true;
18101     }
18102     break;
18103   }
18104 
18105   return false;
18106 }
18107 
18108 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18109   FindCXXThisExpr Finder(*this);
18110 
18111   // Check attributes.
18112   for (const auto *A : Method->attrs()) {
18113     // FIXME: This should be emitted by tblgen.
18114     Expr *Arg = nullptr;
18115     ArrayRef<Expr *> Args;
18116     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18117       Arg = G->getArg();
18118     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18119       Arg = G->getArg();
18120     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18121       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18122     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18123       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18124     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18125       Arg = ETLF->getSuccessValue();
18126       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18127     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18128       Arg = STLF->getSuccessValue();
18129       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18130     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18131       Arg = LR->getArg();
18132     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18133       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18134     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18135       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18136     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18137       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18138     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18139       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18140     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18141       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18142 
18143     if (Arg && !Finder.TraverseStmt(Arg))
18144       return true;
18145 
18146     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18147       if (!Finder.TraverseStmt(Args[I]))
18148         return true;
18149     }
18150   }
18151 
18152   return false;
18153 }
18154 
18155 void Sema::checkExceptionSpecification(
18156     bool IsTopLevel, ExceptionSpecificationType EST,
18157     ArrayRef<ParsedType> DynamicExceptions,
18158     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18159     SmallVectorImpl<QualType> &Exceptions,
18160     FunctionProtoType::ExceptionSpecInfo &ESI) {
18161   Exceptions.clear();
18162   ESI.Type = EST;
18163   if (EST == EST_Dynamic) {
18164     Exceptions.reserve(DynamicExceptions.size());
18165     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18166       // FIXME: Preserve type source info.
18167       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18168 
18169       if (IsTopLevel) {
18170         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18171         collectUnexpandedParameterPacks(ET, Unexpanded);
18172         if (!Unexpanded.empty()) {
18173           DiagnoseUnexpandedParameterPacks(
18174               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18175               Unexpanded);
18176           continue;
18177         }
18178       }
18179 
18180       // Check that the type is valid for an exception spec, and
18181       // drop it if not.
18182       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18183         Exceptions.push_back(ET);
18184     }
18185     ESI.Exceptions = Exceptions;
18186     return;
18187   }
18188 
18189   if (isComputedNoexcept(EST)) {
18190     assert((NoexceptExpr->isTypeDependent() ||
18191             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18192             Context.BoolTy) &&
18193            "Parser should have made sure that the expression is boolean");
18194     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18195       ESI.Type = EST_BasicNoexcept;
18196       return;
18197     }
18198 
18199     ESI.NoexceptExpr = NoexceptExpr;
18200     return;
18201   }
18202 }
18203 
18204 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18205              ExceptionSpecificationType EST,
18206              SourceRange SpecificationRange,
18207              ArrayRef<ParsedType> DynamicExceptions,
18208              ArrayRef<SourceRange> DynamicExceptionRanges,
18209              Expr *NoexceptExpr) {
18210   if (!MethodD)
18211     return;
18212 
18213   // Dig out the method we're referring to.
18214   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18215     MethodD = FunTmpl->getTemplatedDecl();
18216 
18217   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18218   if (!Method)
18219     return;
18220 
18221   // Check the exception specification.
18222   llvm::SmallVector<QualType, 4> Exceptions;
18223   FunctionProtoType::ExceptionSpecInfo ESI;
18224   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18225                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18226                               ESI);
18227 
18228   // Update the exception specification on the function type.
18229   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18230 
18231   if (Method->isStatic())
18232     checkThisInStaticMemberFunctionExceptionSpec(Method);
18233 
18234   if (Method->isVirtual()) {
18235     // Check overrides, which we previously had to delay.
18236     for (const CXXMethodDecl *O : Method->overridden_methods())
18237       CheckOverridingFunctionExceptionSpec(Method, O);
18238   }
18239 }
18240 
18241 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18242 ///
18243 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18244                                        SourceLocation DeclStart, Declarator &D,
18245                                        Expr *BitWidth,
18246                                        InClassInitStyle InitStyle,
18247                                        AccessSpecifier AS,
18248                                        const ParsedAttr &MSPropertyAttr) {
18249   IdentifierInfo *II = D.getIdentifier();
18250   if (!II) {
18251     Diag(DeclStart, diag::err_anonymous_property);
18252     return nullptr;
18253   }
18254   SourceLocation Loc = D.getIdentifierLoc();
18255 
18256   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18257   QualType T = TInfo->getType();
18258   if (getLangOpts().CPlusPlus) {
18259     CheckExtraCXXDefaultArguments(D);
18260 
18261     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18262                                         UPPC_DataMemberType)) {
18263       D.setInvalidType();
18264       T = Context.IntTy;
18265       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18266     }
18267   }
18268 
18269   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18270 
18271   if (D.getDeclSpec().isInlineSpecified())
18272     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18273         << getLangOpts().CPlusPlus17;
18274   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18275     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18276          diag::err_invalid_thread)
18277       << DeclSpec::getSpecifierName(TSCS);
18278 
18279   // Check to see if this name was declared as a member previously
18280   NamedDecl *PrevDecl = nullptr;
18281   LookupResult Previous(*this, II, Loc, LookupMemberName,
18282                         ForVisibleRedeclaration);
18283   LookupName(Previous, S);
18284   switch (Previous.getResultKind()) {
18285   case LookupResult::Found:
18286   case LookupResult::FoundUnresolvedValue:
18287     PrevDecl = Previous.getAsSingle<NamedDecl>();
18288     break;
18289 
18290   case LookupResult::FoundOverloaded:
18291     PrevDecl = Previous.getRepresentativeDecl();
18292     break;
18293 
18294   case LookupResult::NotFound:
18295   case LookupResult::NotFoundInCurrentInstantiation:
18296   case LookupResult::Ambiguous:
18297     break;
18298   }
18299 
18300   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18301     // Maybe we will complain about the shadowed template parameter.
18302     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18303     // Just pretend that we didn't see the previous declaration.
18304     PrevDecl = nullptr;
18305   }
18306 
18307   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18308     PrevDecl = nullptr;
18309 
18310   SourceLocation TSSL = D.getBeginLoc();
18311   MSPropertyDecl *NewPD =
18312       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18313                              MSPropertyAttr.getPropertyDataGetter(),
18314                              MSPropertyAttr.getPropertyDataSetter());
18315   ProcessDeclAttributes(TUScope, NewPD, D);
18316   NewPD->setAccess(AS);
18317 
18318   if (NewPD->isInvalidDecl())
18319     Record->setInvalidDecl();
18320 
18321   if (D.getDeclSpec().isModulePrivateSpecified())
18322     NewPD->setModulePrivate();
18323 
18324   if (NewPD->isInvalidDecl() && PrevDecl) {
18325     // Don't introduce NewFD into scope; there's already something
18326     // with the same name in the same scope.
18327   } else if (II) {
18328     PushOnScopeChains(NewPD, S);
18329   } else
18330     Record->addDecl(NewPD);
18331 
18332   return NewPD;
18333 }
18334 
18335 void Sema::ActOnStartFunctionDeclarationDeclarator(
18336     Declarator &Declarator, unsigned TemplateParameterDepth) {
18337   auto &Info = InventedParameterInfos.emplace_back();
18338   TemplateParameterList *ExplicitParams = nullptr;
18339   ArrayRef<TemplateParameterList *> ExplicitLists =
18340       Declarator.getTemplateParameterLists();
18341   if (!ExplicitLists.empty()) {
18342     bool IsMemberSpecialization, IsInvalid;
18343     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18344         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18345         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18346         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18347         /*SuppressDiagnostic=*/true);
18348   }
18349   if (ExplicitParams) {
18350     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18351     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18352     Info.NumExplicitTemplateParams = ExplicitParams->size();
18353   } else {
18354     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18355     Info.NumExplicitTemplateParams = 0;
18356   }
18357 }
18358 
18359 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18360   auto &FSI = InventedParameterInfos.back();
18361   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18362     if (FSI.NumExplicitTemplateParams != 0) {
18363       TemplateParameterList *ExplicitParams =
18364           Declarator.getTemplateParameterLists().back();
18365       Declarator.setInventedTemplateParameterList(
18366           TemplateParameterList::Create(
18367               Context, ExplicitParams->getTemplateLoc(),
18368               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18369               ExplicitParams->getRAngleLoc(),
18370               ExplicitParams->getRequiresClause()));
18371     } else {
18372       Declarator.setInventedTemplateParameterList(
18373           TemplateParameterList::Create(
18374               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18375               SourceLocation(), /*RequiresClause=*/nullptr));
18376     }
18377   }
18378   InventedParameterInfos.pop_back();
18379 }
18380