1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include <map>
46 #include <set>
47 
48 using namespace clang;
49 
50 //===----------------------------------------------------------------------===//
51 // CheckDefaultArgumentVisitor
52 //===----------------------------------------------------------------------===//
53 
54 namespace {
55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56 /// the default argument of a parameter to determine whether it
57 /// contains any ill-formed subexpressions. For example, this will
58 /// diagnose the use of local variables or parameters within the
59 /// default argument expression.
60 class CheckDefaultArgumentVisitor
61     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62   Sema &S;
63   const Expr *DefaultArg;
64 
65 public:
66   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67       : S(S), DefaultArg(DefaultArg) {}
68 
69   bool VisitExpr(const Expr *Node);
70   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72   bool VisitLambdaExpr(const LambdaExpr *Lambda);
73   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74 };
75 
76 /// VisitExpr - Visit all of the children of this expression.
77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78   bool IsInvalid = false;
79   for (const Stmt *SubStmt : Node->children())
80     IsInvalid |= Visit(SubStmt);
81   return IsInvalid;
82 }
83 
84 /// VisitDeclRefExpr - Visit a reference to a declaration, to
85 /// determine whether this declaration can be used in the default
86 /// argument expression.
87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88   const NamedDecl *Decl = DRE->getDecl();
89   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90     // C++ [dcl.fct.default]p9:
91     //   [...] parameters of a function shall not be used in default
92     //   argument expressions, even if they are not evaluated. [...]
93     //
94     // C++17 [dcl.fct.default]p9 (by CWG 2082):
95     //   [...] A parameter shall not appear as a potentially-evaluated
96     //   expression in a default argument. [...]
97     //
98     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99       return S.Diag(DRE->getBeginLoc(),
100                     diag::err_param_default_argument_references_param)
101              << Param->getDeclName() << DefaultArg->getSourceRange();
102   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103     // C++ [dcl.fct.default]p7:
104     //   Local variables shall not be used in default argument
105     //   expressions.
106     //
107     // C++17 [dcl.fct.default]p7 (by CWG 2082):
108     //   A local variable shall not appear as a potentially-evaluated
109     //   expression in a default argument.
110     //
111     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113     //
114     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115       return S.Diag(DRE->getBeginLoc(),
116                     diag::err_param_default_argument_references_local)
117              << VDecl->getDeclName() << DefaultArg->getSourceRange();
118   }
119 
120   return false;
121 }
122 
123 /// VisitCXXThisExpr - Visit a C++ "this" expression.
124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125   // C++ [dcl.fct.default]p8:
126   //   The keyword this shall not be used in a default argument of a
127   //   member function.
128   return S.Diag(ThisE->getBeginLoc(),
129                 diag::err_param_default_argument_references_this)
130          << ThisE->getSourceRange();
131 }
132 
133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134     const PseudoObjectExpr *POE) {
135   bool Invalid = false;
136   for (const Expr *E : POE->semantics()) {
137     // Look through bindings.
138     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139       E = OVE->getSourceExpr();
140       assert(E && "pseudo-object binding without source expression?");
141     }
142 
143     Invalid |= Visit(E);
144   }
145   return Invalid;
146 }
147 
148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149   // C++11 [expr.lambda.prim]p13:
150   //   A lambda-expression appearing in a default argument shall not
151   //   implicitly or explicitly capture any entity.
152   if (Lambda->capture_begin() == Lambda->capture_end())
153     return false;
154 
155   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156 }
157 } // namespace
158 
159 void
160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161                                                  const CXXMethodDecl *Method) {
162   // If we have an MSAny spec already, don't bother.
163   if (!Method || ComputedEST == EST_MSAny)
164     return;
165 
166   const FunctionProtoType *Proto
167     = Method->getType()->getAs<FunctionProtoType>();
168   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169   if (!Proto)
170     return;
171 
172   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173 
174   // If we have a throw-all spec at this point, ignore the function.
175   if (ComputedEST == EST_None)
176     return;
177 
178   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179     EST = EST_BasicNoexcept;
180 
181   switch (EST) {
182   case EST_Unparsed:
183   case EST_Uninstantiated:
184   case EST_Unevaluated:
185     llvm_unreachable("should not see unresolved exception specs here");
186 
187   // If this function can throw any exceptions, make a note of that.
188   case EST_MSAny:
189   case EST_None:
190     // FIXME: Whichever we see last of MSAny and None determines our result.
191     // We should make a consistent, order-independent choice here.
192     ClearExceptions();
193     ComputedEST = EST;
194     return;
195   case EST_NoexceptFalse:
196     ClearExceptions();
197     ComputedEST = EST_None;
198     return;
199   // FIXME: If the call to this decl is using any of its default arguments, we
200   // need to search them for potentially-throwing calls.
201   // If this function has a basic noexcept, it doesn't affect the outcome.
202   case EST_BasicNoexcept:
203   case EST_NoexceptTrue:
204   case EST_NoThrow:
205     return;
206   // If we're still at noexcept(true) and there's a throw() callee,
207   // change to that specification.
208   case EST_DynamicNone:
209     if (ComputedEST == EST_BasicNoexcept)
210       ComputedEST = EST_DynamicNone;
211     return;
212   case EST_DependentNoexcept:
213     llvm_unreachable(
214         "should not generate implicit declarations for dependent cases");
215   case EST_Dynamic:
216     break;
217   }
218   assert(EST == EST_Dynamic && "EST case not considered earlier.");
219   assert(ComputedEST != EST_None &&
220          "Shouldn't collect exceptions when throw-all is guaranteed.");
221   ComputedEST = EST_Dynamic;
222   // Record the exceptions in this function's exception specification.
223   for (const auto &E : Proto->exceptions())
224     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225       Exceptions.push_back(E);
226 }
227 
228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229   if (!S || ComputedEST == EST_MSAny)
230     return;
231 
232   // FIXME:
233   //
234   // C++0x [except.spec]p14:
235   //   [An] implicit exception-specification specifies the type-id T if and
236   // only if T is allowed by the exception-specification of a function directly
237   // invoked by f's implicit definition; f shall allow all exceptions if any
238   // function it directly invokes allows all exceptions, and f shall allow no
239   // exceptions if every function it directly invokes allows no exceptions.
240   //
241   // Note in particular that if an implicit exception-specification is generated
242   // for a function containing a throw-expression, that specification can still
243   // be noexcept(true).
244   //
245   // Note also that 'directly invoked' is not defined in the standard, and there
246   // is no indication that we should only consider potentially-evaluated calls.
247   //
248   // Ultimately we should implement the intent of the standard: the exception
249   // specification should be the set of exceptions which can be thrown by the
250   // implicit definition. For now, we assume that any non-nothrow expression can
251   // throw any exception.
252 
253   if (Self->canThrow(S))
254     ComputedEST = EST_None;
255 }
256 
257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258                                              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_RValue));
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)
385                        OpaqueValueExpr(EqualLoc,
386                                        Param->getType().getNonReferenceType(),
387                                        VK_RValue));
388 }
389 
390 /// CheckExtraCXXDefaultArguments - Check for any extra default
391 /// arguments in the declarator, which is not a function declaration
392 /// or definition and therefore is not permitted to have default
393 /// arguments. This routine should be invoked for every declarator
394 /// that is not a function declaration or definition.
395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396   // C++ [dcl.fct.default]p3
397   //   A default argument expression shall be specified only in the
398   //   parameter-declaration-clause of a function declaration or in a
399   //   template-parameter (14.1). It shall not be specified for a
400   //   parameter pack. If it is specified in a
401   //   parameter-declaration-clause, it shall not occur within a
402   //   declarator or abstract-declarator of a parameter-declaration.
403   bool MightBeFunction = D.isFunctionDeclarationContext();
404   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405     DeclaratorChunk &chunk = D.getTypeObject(i);
406     if (chunk.Kind == DeclaratorChunk::Function) {
407       if (MightBeFunction) {
408         // This is a function declaration. It can have default arguments, but
409         // keep looking in case its return type is a function type with default
410         // arguments.
411         MightBeFunction = false;
412         continue;
413       }
414       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415            ++argIdx) {
416         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417         if (Param->hasUnparsedDefaultArg()) {
418           std::unique_ptr<CachedTokens> Toks =
419               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420           SourceRange SR;
421           if (Toks->size() > 1)
422             SR = SourceRange((*Toks)[1].getLocation(),
423                              Toks->back().getLocation());
424           else
425             SR = UnparsedDefaultArgLocs[Param];
426           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427             << SR;
428         } else if (Param->getDefaultArg()) {
429           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430             << Param->getDefaultArg()->getSourceRange();
431           Param->setDefaultArg(nullptr);
432         }
433       }
434     } else if (chunk.Kind != DeclaratorChunk::Paren) {
435       MightBeFunction = false;
436     }
437   }
438 }
439 
440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441   return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443   });
444 }
445 
446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
447 /// function, once we already know that they have the same
448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449 /// error, false otherwise.
450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451                                 Scope *S) {
452   bool Invalid = false;
453 
454   // The declaration context corresponding to the scope is the semantic
455   // parent, unless this is a local function declaration, in which case
456   // it is that surrounding function.
457   DeclContext *ScopeDC = New->isLocalExternDecl()
458                              ? New->getLexicalDeclContext()
459                              : New->getDeclContext();
460 
461   // Find the previous declaration for the purpose of default arguments.
462   FunctionDecl *PrevForDefaultArgs = Old;
463   for (/**/; PrevForDefaultArgs;
464        // Don't bother looking back past the latest decl if this is a local
465        // extern declaration; nothing else could work.
466        PrevForDefaultArgs = New->isLocalExternDecl()
467                                 ? nullptr
468                                 : PrevForDefaultArgs->getPreviousDecl()) {
469     // Ignore hidden declarations.
470     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471       continue;
472 
473     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474         !New->isCXXClassMember()) {
475       // Ignore default arguments of old decl if they are not in
476       // the same scope and this is not an out-of-line definition of
477       // a member function.
478       continue;
479     }
480 
481     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482       // If only one of these is a local function declaration, then they are
483       // declared in different scopes, even though isDeclInScope may think
484       // they're in the same scope. (If both are local, the scope check is
485       // sufficient, and if neither is local, then they are in the same scope.)
486       continue;
487     }
488 
489     // We found the right previous declaration.
490     break;
491   }
492 
493   // C++ [dcl.fct.default]p4:
494   //   For non-template functions, default arguments can be added in
495   //   later declarations of a function in the same
496   //   scope. Declarations in different scopes have completely
497   //   distinct sets of default arguments. That is, declarations in
498   //   inner scopes do not acquire default arguments from
499   //   declarations in outer scopes, and vice versa. In a given
500   //   function declaration, all parameters subsequent to a
501   //   parameter with a default argument shall have default
502   //   arguments supplied in this or previous declarations. A
503   //   default argument shall not be redefined by a later
504   //   declaration (not even to the same value).
505   //
506   // C++ [dcl.fct.default]p6:
507   //   Except for member functions of class templates, the default arguments
508   //   in a member function definition that appears outside of the class
509   //   definition are added to the set of default arguments provided by the
510   //   member function declaration in the class definition.
511   for (unsigned p = 0, NumParams = PrevForDefaultArgs
512                                        ? PrevForDefaultArgs->getNumParams()
513                                        : 0;
514        p < NumParams; ++p) {
515     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516     ParmVarDecl *NewParam = New->getParamDecl(p);
517 
518     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519     bool NewParamHasDfl = NewParam->hasDefaultArg();
520 
521     if (OldParamHasDfl && NewParamHasDfl) {
522       unsigned DiagDefaultParamID =
523         diag::err_param_default_argument_redefinition;
524 
525       // MSVC accepts that default parameters be redefined for member functions
526       // of template class. The new default parameter's value is ignored.
527       Invalid = true;
528       if (getLangOpts().MicrosoftExt) {
529         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530         if (MD && MD->getParent()->getDescribedClassTemplate()) {
531           // Merge the old default argument into the new parameter.
532           NewParam->setHasInheritedDefaultArg();
533           if (OldParam->hasUninstantiatedDefaultArg())
534             NewParam->setUninstantiatedDefaultArg(
535                                       OldParam->getUninstantiatedDefaultArg());
536           else
537             NewParam->setDefaultArg(OldParam->getInit());
538           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539           Invalid = false;
540         }
541       }
542 
543       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544       // hint here. Alternatively, we could walk the type-source information
545       // for NewParam to find the last source location in the type... but it
546       // isn't worth the effort right now. This is the kind of test case that
547       // is hard to get right:
548       //   int f(int);
549       //   void g(int (*fp)(int) = f);
550       //   void g(int (*fp)(int) = &f);
551       Diag(NewParam->getLocation(), DiagDefaultParamID)
552         << NewParam->getDefaultArgRange();
553 
554       // Look for the function declaration where the default argument was
555       // actually written, which may be a declaration prior to Old.
556       for (auto Older = PrevForDefaultArgs;
557            OldParam->hasInheritedDefaultArg(); /**/) {
558         Older = Older->getPreviousDecl();
559         OldParam = Older->getParamDecl(p);
560       }
561 
562       Diag(OldParam->getLocation(), diag::note_previous_definition)
563         << OldParam->getDefaultArgRange();
564     } else if (OldParamHasDfl) {
565       // Merge the old default argument into the new parameter unless the new
566       // function is a friend declaration in a template class. In the latter
567       // case the default arguments will be inherited when the friend
568       // declaration will be instantiated.
569       if (New->getFriendObjectKind() == Decl::FOK_None ||
570           !New->getLexicalDeclContext()->isDependentContext()) {
571         // It's important to use getInit() here;  getDefaultArg()
572         // strips off any top-level ExprWithCleanups.
573         NewParam->setHasInheritedDefaultArg();
574         if (OldParam->hasUnparsedDefaultArg())
575           NewParam->setUnparsedDefaultArg();
576         else if (OldParam->hasUninstantiatedDefaultArg())
577           NewParam->setUninstantiatedDefaultArg(
578                                        OldParam->getUninstantiatedDefaultArg());
579         else
580           NewParam->setDefaultArg(OldParam->getInit());
581       }
582     } else if (NewParamHasDfl) {
583       if (New->getDescribedFunctionTemplate()) {
584         // Paragraph 4, quoted above, only applies to non-template functions.
585         Diag(NewParam->getLocation(),
586              diag::err_param_default_argument_template_redecl)
587           << NewParam->getDefaultArgRange();
588         Diag(PrevForDefaultArgs->getLocation(),
589              diag::note_template_prev_declaration)
590             << false;
591       } else if (New->getTemplateSpecializationKind()
592                    != TSK_ImplicitInstantiation &&
593                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
594         // C++ [temp.expr.spec]p21:
595         //   Default function arguments shall not be specified in a declaration
596         //   or a definition for one of the following explicit specializations:
597         //     - the explicit specialization of a function template;
598         //     - the explicit specialization of a member function template;
599         //     - the explicit specialization of a member function of a class
600         //       template where the class template specialization to which the
601         //       member function specialization belongs is implicitly
602         //       instantiated.
603         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605           << New->getDeclName()
606           << NewParam->getDefaultArgRange();
607       } else if (New->getDeclContext()->isDependentContext()) {
608         // C++ [dcl.fct.default]p6 (DR217):
609         //   Default arguments for a member function of a class template shall
610         //   be specified on the initial declaration of the member function
611         //   within the class template.
612         //
613         // Reading the tea leaves a bit in DR217 and its reference to DR205
614         // leads me to the conclusion that one cannot add default function
615         // arguments for an out-of-line definition of a member function of a
616         // dependent type.
617         int WhichKind = 2;
618         if (CXXRecordDecl *Record
619               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620           if (Record->getDescribedClassTemplate())
621             WhichKind = 0;
622           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623             WhichKind = 1;
624           else
625             WhichKind = 2;
626         }
627 
628         Diag(NewParam->getLocation(),
629              diag::err_param_default_argument_member_template_redecl)
630           << WhichKind
631           << NewParam->getDefaultArgRange();
632       }
633     }
634   }
635 
636   // DR1344: If a default argument is added outside a class definition and that
637   // default argument makes the function a special member function, the program
638   // is ill-formed. This can only happen for constructors.
639   if (isa<CXXConstructorDecl>(New) &&
640       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643     if (NewSM != OldSM) {
644       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645       assert(NewParam->hasDefaultArg());
646       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647         << NewParam->getDefaultArgRange() << NewSM;
648       Diag(Old->getLocation(), diag::note_previous_declaration);
649     }
650   }
651 
652   const FunctionDecl *Def;
653   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654   // template has a constexpr specifier then all its declarations shall
655   // contain the constexpr specifier.
656   if (New->getConstexprKind() != Old->getConstexprKind()) {
657     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658         << New << New->getConstexprKind() << Old->getConstexprKind();
659     Diag(Old->getLocation(), diag::note_previous_declaration);
660     Invalid = true;
661   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
662              Old->isDefined(Def) &&
663              // If a friend function is inlined but does not have 'inline'
664              // specifier, it is a definition. Do not report attribute conflict
665              // in this case, redefinition will be diagnosed later.
666              (New->isInlineSpecified() ||
667               New->getFriendObjectKind() == Decl::FOK_None)) {
668     // C++11 [dcl.fcn.spec]p4:
669     //   If the definition of a function appears in a translation unit before its
670     //   first declaration as inline, the program is ill-formed.
671     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672     Diag(Def->getLocation(), diag::note_previous_definition);
673     Invalid = true;
674   }
675 
676   // C++17 [temp.deduct.guide]p3:
677   //   Two deduction guide declarations in the same translation unit
678   //   for the same class template shall not have equivalent
679   //   parameter-declaration-clauses.
680   if (isa<CXXDeductionGuideDecl>(New) &&
681       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
682     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683     Diag(Old->getLocation(), diag::note_previous_declaration);
684   }
685 
686   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687   // argument expression, that declaration shall be a definition and shall be
688   // the only declaration of the function or function template in the
689   // translation unit.
690   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691       functionDeclHasDefaultArgument(Old)) {
692     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693     Diag(Old->getLocation(), diag::note_previous_declaration);
694     Invalid = true;
695   }
696 
697   // C++11 [temp.friend]p4 (DR329):
698   //   When a function is defined in a friend function declaration in a class
699   //   template, the function is instantiated when the function is odr-used.
700   //   The same restrictions on multiple declarations and definitions that
701   //   apply to non-template function declarations and definitions also apply
702   //   to these implicit definitions.
703   const FunctionDecl *OldDefinition = nullptr;
704   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
705       Old->isDefined(OldDefinition, true))
706     CheckForFunctionRedefinition(New, OldDefinition);
707 
708   return Invalid;
709 }
710 
711 NamedDecl *
712 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
713                                    MultiTemplateParamsArg TemplateParamLists) {
714   assert(D.isDecompositionDeclarator());
715   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
716 
717   // The syntax only allows a decomposition declarator as a simple-declaration,
718   // a for-range-declaration, or a condition in Clang, but we parse it in more
719   // cases than that.
720   if (!D.mayHaveDecompositionDeclarator()) {
721     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
722       << Decomp.getSourceRange();
723     return nullptr;
724   }
725 
726   if (!TemplateParamLists.empty()) {
727     // FIXME: There's no rule against this, but there are also no rules that
728     // would actually make it usable, so we reject it for now.
729     Diag(TemplateParamLists.front()->getTemplateLoc(),
730          diag::err_decomp_decl_template);
731     return nullptr;
732   }
733 
734   Diag(Decomp.getLSquareLoc(),
735        !getLangOpts().CPlusPlus17
736            ? diag::ext_decomp_decl
737            : D.getContext() == DeclaratorContext::Condition
738                  ? diag::ext_decomp_decl_cond
739                  : diag::warn_cxx14_compat_decomp_decl)
740       << Decomp.getSourceRange();
741 
742   // The semantic context is always just the current context.
743   DeclContext *const DC = CurContext;
744 
745   // C++17 [dcl.dcl]/8:
746   //   The decl-specifier-seq shall contain only the type-specifier auto
747   //   and cv-qualifiers.
748   // C++2a [dcl.dcl]/8:
749   //   If decl-specifier-seq contains any decl-specifier other than static,
750   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
751   auto &DS = D.getDeclSpec();
752   {
753     SmallVector<StringRef, 8> BadSpecifiers;
754     SmallVector<SourceLocation, 8> BadSpecifierLocs;
755     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
756     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
757     if (auto SCS = DS.getStorageClassSpec()) {
758       if (SCS == DeclSpec::SCS_static) {
759         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
760         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
761       } else {
762         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
763         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
764       }
765     }
766     if (auto TSCS = DS.getThreadStorageClassSpec()) {
767       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
768       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
769     }
770     if (DS.hasConstexprSpecifier()) {
771       BadSpecifiers.push_back(
772           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
773       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
774     }
775     if (DS.isInlineSpecified()) {
776       BadSpecifiers.push_back("inline");
777       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
778     }
779     if (!BadSpecifiers.empty()) {
780       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
781       Err << (int)BadSpecifiers.size()
782           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
783       // Don't add FixItHints to remove the specifiers; we do still respect
784       // them when building the underlying variable.
785       for (auto Loc : BadSpecifierLocs)
786         Err << SourceRange(Loc, Loc);
787     } else if (!CPlusPlus20Specifiers.empty()) {
788       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
789                          getLangOpts().CPlusPlus20
790                              ? diag::warn_cxx17_compat_decomp_decl_spec
791                              : diag::ext_decomp_decl_spec);
792       Warn << (int)CPlusPlus20Specifiers.size()
793            << llvm::join(CPlusPlus20Specifiers.begin(),
794                          CPlusPlus20Specifiers.end(), " ");
795       for (auto Loc : CPlusPlus20SpecifierLocs)
796         Warn << SourceRange(Loc, Loc);
797     }
798     // We can't recover from it being declared as a typedef.
799     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
800       return nullptr;
801   }
802 
803   // C++2a [dcl.struct.bind]p1:
804   //   A cv that includes volatile is deprecated
805   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
806       getLangOpts().CPlusPlus20)
807     Diag(DS.getVolatileSpecLoc(),
808          diag::warn_deprecated_volatile_structured_binding);
809 
810   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
811   QualType R = TInfo->getType();
812 
813   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
814                                       UPPC_DeclarationType))
815     D.setInvalidType();
816 
817   // The syntax only allows a single ref-qualifier prior to the decomposition
818   // declarator. No other declarator chunks are permitted. Also check the type
819   // specifier here.
820   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
821       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
822       (D.getNumTypeObjects() == 1 &&
823        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
824     Diag(Decomp.getLSquareLoc(),
825          (D.hasGroupingParens() ||
826           (D.getNumTypeObjects() &&
827            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
828              ? diag::err_decomp_decl_parens
829              : diag::err_decomp_decl_type)
830         << R;
831 
832     // In most cases, there's no actual problem with an explicitly-specified
833     // type, but a function type won't work here, and ActOnVariableDeclarator
834     // shouldn't be called for such a type.
835     if (R->isFunctionType())
836       D.setInvalidType();
837   }
838 
839   // Build the BindingDecls.
840   SmallVector<BindingDecl*, 8> Bindings;
841 
842   // Build the BindingDecls.
843   for (auto &B : D.getDecompositionDeclarator().bindings()) {
844     // Check for name conflicts.
845     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
846     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847                           ForVisibleRedeclaration);
848     LookupName(Previous, S,
849                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
850 
851     // It's not permitted to shadow a template parameter name.
852     if (Previous.isSingleResult() &&
853         Previous.getFoundDecl()->isTemplateParameter()) {
854       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
855                                       Previous.getFoundDecl());
856       Previous.clear();
857     }
858 
859     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
860                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
861     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
862                          /*AllowInlineNamespace*/false);
863     if (!Previous.empty()) {
864       auto *Old = Previous.getRepresentativeDecl();
865       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
866       Diag(Old->getLocation(), diag::note_previous_definition);
867     }
868 
869     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
870     PushOnScopeChains(BD, S, true);
871     Bindings.push_back(BD);
872     ParsingInitForAutoVars.insert(BD);
873   }
874 
875   // There are no prior lookup results for the variable itself, because it
876   // is unnamed.
877   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
878                                Decomp.getLSquareLoc());
879   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
880                         ForVisibleRedeclaration);
881 
882   // Build the variable that holds the non-decomposed object.
883   bool AddToScope = true;
884   NamedDecl *New =
885       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
886                               MultiTemplateParamsArg(), AddToScope, Bindings);
887   if (AddToScope) {
888     S->AddDecl(New);
889     CurContext->addHiddenDecl(New);
890   }
891 
892   if (isInOpenMPDeclareTargetContext())
893     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
894 
895   return New;
896 }
897 
898 static bool checkSimpleDecomposition(
899     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
900     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
901     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
902   if ((int64_t)Bindings.size() != NumElems) {
903     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
904         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
905         << (NumElems < Bindings.size());
906     return true;
907   }
908 
909   unsigned I = 0;
910   for (auto *B : Bindings) {
911     SourceLocation Loc = B->getLocation();
912     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
913     if (E.isInvalid())
914       return true;
915     E = GetInit(Loc, E.get(), I++);
916     if (E.isInvalid())
917       return true;
918     B->setBinding(ElemType, E.get());
919   }
920 
921   return false;
922 }
923 
924 static bool checkArrayLikeDecomposition(Sema &S,
925                                         ArrayRef<BindingDecl *> Bindings,
926                                         ValueDecl *Src, QualType DecompType,
927                                         const llvm::APSInt &NumElems,
928                                         QualType ElemType) {
929   return checkSimpleDecomposition(
930       S, Bindings, Src, DecompType, NumElems, ElemType,
931       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
932         ExprResult E = S.ActOnIntegerConstant(Loc, I);
933         if (E.isInvalid())
934           return ExprError();
935         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
936       });
937 }
938 
939 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
940                                     ValueDecl *Src, QualType DecompType,
941                                     const ConstantArrayType *CAT) {
942   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
943                                      llvm::APSInt(CAT->getSize()),
944                                      CAT->getElementType());
945 }
946 
947 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
948                                      ValueDecl *Src, QualType DecompType,
949                                      const VectorType *VT) {
950   return checkArrayLikeDecomposition(
951       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
952       S.Context.getQualifiedType(VT->getElementType(),
953                                  DecompType.getQualifiers()));
954 }
955 
956 static bool checkComplexDecomposition(Sema &S,
957                                       ArrayRef<BindingDecl *> Bindings,
958                                       ValueDecl *Src, QualType DecompType,
959                                       const ComplexType *CT) {
960   return checkSimpleDecomposition(
961       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
962       S.Context.getQualifiedType(CT->getElementType(),
963                                  DecompType.getQualifiers()),
964       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
965         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
966       });
967 }
968 
969 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
970                                      TemplateArgumentListInfo &Args) {
971   SmallString<128> SS;
972   llvm::raw_svector_ostream OS(SS);
973   bool First = true;
974   for (auto &Arg : Args.arguments()) {
975     if (!First)
976       OS << ", ";
977     Arg.getArgument().print(PrintingPolicy, OS);
978     First = false;
979   }
980   return std::string(OS.str());
981 }
982 
983 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
984                                      SourceLocation Loc, StringRef Trait,
985                                      TemplateArgumentListInfo &Args,
986                                      unsigned DiagID) {
987   auto DiagnoseMissing = [&] {
988     if (DiagID)
989       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
990                                                Args);
991     return true;
992   };
993 
994   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
995   NamespaceDecl *Std = S.getStdNamespace();
996   if (!Std)
997     return DiagnoseMissing();
998 
999   // Look up the trait itself, within namespace std. We can diagnose various
1000   // problems with this lookup even if we've been asked to not diagnose a
1001   // missing specialization, because this can only fail if the user has been
1002   // declaring their own names in namespace std or we don't support the
1003   // standard library implementation in use.
1004   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1005                       Loc, Sema::LookupOrdinaryName);
1006   if (!S.LookupQualifiedName(Result, Std))
1007     return DiagnoseMissing();
1008   if (Result.isAmbiguous())
1009     return true;
1010 
1011   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1012   if (!TraitTD) {
1013     Result.suppressDiagnostics();
1014     NamedDecl *Found = *Result.begin();
1015     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1016     S.Diag(Found->getLocation(), diag::note_declared_at);
1017     return true;
1018   }
1019 
1020   // Build the template-id.
1021   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1022   if (TraitTy.isNull())
1023     return true;
1024   if (!S.isCompleteType(Loc, TraitTy)) {
1025     if (DiagID)
1026       S.RequireCompleteType(
1027           Loc, TraitTy, DiagID,
1028           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1029     return true;
1030   }
1031 
1032   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1033   assert(RD && "specialization of class template is not a class?");
1034 
1035   // Look up the member of the trait type.
1036   S.LookupQualifiedName(TraitMemberLookup, RD);
1037   return TraitMemberLookup.isAmbiguous();
1038 }
1039 
1040 static TemplateArgumentLoc
1041 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1042                                    uint64_t I) {
1043   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1044   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1045 }
1046 
1047 static TemplateArgumentLoc
1048 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1049   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1050 }
1051 
1052 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1053 
1054 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1055                                llvm::APSInt &Size) {
1056   EnterExpressionEvaluationContext ContextRAII(
1057       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1058 
1059   DeclarationName Value = S.PP.getIdentifierInfo("value");
1060   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1061 
1062   // Form template argument list for tuple_size<T>.
1063   TemplateArgumentListInfo Args(Loc, Loc);
1064   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1065 
1066   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1067   // it's not tuple-like.
1068   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1069       R.empty())
1070     return IsTupleLike::NotTupleLike;
1071 
1072   // If we get this far, we've committed to the tuple interpretation, but
1073   // we can still fail if there actually isn't a usable ::value.
1074 
1075   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1076     LookupResult &R;
1077     TemplateArgumentListInfo &Args;
1078     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1079         : R(R), Args(Args) {}
1080     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1081                                                SourceLocation Loc) override {
1082       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1083           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1084     }
1085   } Diagnoser(R, Args);
1086 
1087   ExprResult E =
1088       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1089   if (E.isInvalid())
1090     return IsTupleLike::Error;
1091 
1092   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1093   if (E.isInvalid())
1094     return IsTupleLike::Error;
1095 
1096   return IsTupleLike::TupleLike;
1097 }
1098 
1099 /// \return std::tuple_element<I, T>::type.
1100 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1101                                         unsigned I, QualType T) {
1102   // Form template argument list for tuple_element<I, T>.
1103   TemplateArgumentListInfo Args(Loc, Loc);
1104   Args.addArgument(
1105       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1106   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1107 
1108   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1109   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1110   if (lookupStdTypeTraitMember(
1111           S, R, Loc, "tuple_element", Args,
1112           diag::err_decomp_decl_std_tuple_element_not_specialized))
1113     return QualType();
1114 
1115   auto *TD = R.getAsSingle<TypeDecl>();
1116   if (!TD) {
1117     R.suppressDiagnostics();
1118     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1119       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1120     if (!R.empty())
1121       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1122     return QualType();
1123   }
1124 
1125   return S.Context.getTypeDeclType(TD);
1126 }
1127 
1128 namespace {
1129 struct InitializingBinding {
1130   Sema &S;
1131   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1132     Sema::CodeSynthesisContext Ctx;
1133     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1134     Ctx.PointOfInstantiation = BD->getLocation();
1135     Ctx.Entity = BD;
1136     S.pushCodeSynthesisContext(Ctx);
1137   }
1138   ~InitializingBinding() {
1139     S.popCodeSynthesisContext();
1140   }
1141 };
1142 }
1143 
1144 static bool checkTupleLikeDecomposition(Sema &S,
1145                                         ArrayRef<BindingDecl *> Bindings,
1146                                         VarDecl *Src, QualType DecompType,
1147                                         const llvm::APSInt &TupleSize) {
1148   if ((int64_t)Bindings.size() != TupleSize) {
1149     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1150         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1151         << (TupleSize < Bindings.size());
1152     return true;
1153   }
1154 
1155   if (Bindings.empty())
1156     return false;
1157 
1158   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1159 
1160   // [dcl.decomp]p3:
1161   //   The unqualified-id get is looked up in the scope of E by class member
1162   //   access lookup ...
1163   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1164   bool UseMemberGet = false;
1165   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1166     if (auto *RD = DecompType->getAsCXXRecordDecl())
1167       S.LookupQualifiedName(MemberGet, RD);
1168     if (MemberGet.isAmbiguous())
1169       return true;
1170     //   ... and if that finds at least one declaration that is a function
1171     //   template whose first template parameter is a non-type parameter ...
1172     for (NamedDecl *D : MemberGet) {
1173       if (FunctionTemplateDecl *FTD =
1174               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1175         TemplateParameterList *TPL = FTD->getTemplateParameters();
1176         if (TPL->size() != 0 &&
1177             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1178           //   ... the initializer is e.get<i>().
1179           UseMemberGet = true;
1180           break;
1181         }
1182       }
1183     }
1184   }
1185 
1186   unsigned I = 0;
1187   for (auto *B : Bindings) {
1188     InitializingBinding InitContext(S, B);
1189     SourceLocation Loc = B->getLocation();
1190 
1191     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1192     if (E.isInvalid())
1193       return true;
1194 
1195     //   e is an lvalue if the type of the entity is an lvalue reference and
1196     //   an xvalue otherwise
1197     if (!Src->getType()->isLValueReferenceType())
1198       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1199                                    E.get(), nullptr, VK_XValue,
1200                                    FPOptionsOverride());
1201 
1202     TemplateArgumentListInfo Args(Loc, Loc);
1203     Args.addArgument(
1204         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1205 
1206     if (UseMemberGet) {
1207       //   if [lookup of member get] finds at least one declaration, the
1208       //   initializer is e.get<i-1>().
1209       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1210                                      CXXScopeSpec(), SourceLocation(), nullptr,
1211                                      MemberGet, &Args, nullptr);
1212       if (E.isInvalid())
1213         return true;
1214 
1215       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1216     } else {
1217       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1218       //   in the associated namespaces.
1219       Expr *Get = UnresolvedLookupExpr::Create(
1220           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1221           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1222           UnresolvedSetIterator(), UnresolvedSetIterator());
1223 
1224       Expr *Arg = E.get();
1225       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1226     }
1227     if (E.isInvalid())
1228       return true;
1229     Expr *Init = E.get();
1230 
1231     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1232     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1233     if (T.isNull())
1234       return true;
1235 
1236     //   each vi is a variable of type "reference to T" initialized with the
1237     //   initializer, where the reference is an lvalue reference if the
1238     //   initializer is an lvalue and an rvalue reference otherwise
1239     QualType RefType =
1240         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1241     if (RefType.isNull())
1242       return true;
1243     auto *RefVD = VarDecl::Create(
1244         S.Context, Src->getDeclContext(), Loc, Loc,
1245         B->getDeclName().getAsIdentifierInfo(), RefType,
1246         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1247     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1248     RefVD->setTSCSpec(Src->getTSCSpec());
1249     RefVD->setImplicit();
1250     if (Src->isInlineSpecified())
1251       RefVD->setInlineSpecified();
1252     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1253 
1254     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1255     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1256     InitializationSequence Seq(S, Entity, Kind, Init);
1257     E = Seq.Perform(S, Entity, Kind, Init);
1258     if (E.isInvalid())
1259       return true;
1260     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1261     if (E.isInvalid())
1262       return true;
1263     RefVD->setInit(E.get());
1264     S.CheckCompleteVariableDeclaration(RefVD);
1265 
1266     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1267                                    DeclarationNameInfo(B->getDeclName(), Loc),
1268                                    RefVD);
1269     if (E.isInvalid())
1270       return true;
1271 
1272     B->setBinding(T, E.get());
1273     I++;
1274   }
1275 
1276   return false;
1277 }
1278 
1279 /// Find the base class to decompose in a built-in decomposition of a class type.
1280 /// This base class search is, unfortunately, not quite like any other that we
1281 /// perform anywhere else in C++.
1282 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1283                                                 const CXXRecordDecl *RD,
1284                                                 CXXCastPath &BasePath) {
1285   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1286                           CXXBasePath &Path) {
1287     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1288   };
1289 
1290   const CXXRecordDecl *ClassWithFields = nullptr;
1291   AccessSpecifier AS = AS_public;
1292   if (RD->hasDirectFields())
1293     // [dcl.decomp]p4:
1294     //   Otherwise, all of E's non-static data members shall be public direct
1295     //   members of E ...
1296     ClassWithFields = RD;
1297   else {
1298     //   ... or of ...
1299     CXXBasePaths Paths;
1300     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1301     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1302       // If no classes have fields, just decompose RD itself. (This will work
1303       // if and only if zero bindings were provided.)
1304       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1305     }
1306 
1307     CXXBasePath *BestPath = nullptr;
1308     for (auto &P : Paths) {
1309       if (!BestPath)
1310         BestPath = &P;
1311       else if (!S.Context.hasSameType(P.back().Base->getType(),
1312                                       BestPath->back().Base->getType())) {
1313         //   ... the same ...
1314         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1315           << false << RD << BestPath->back().Base->getType()
1316           << P.back().Base->getType();
1317         return DeclAccessPair();
1318       } else if (P.Access < BestPath->Access) {
1319         BestPath = &P;
1320       }
1321     }
1322 
1323     //   ... unambiguous ...
1324     QualType BaseType = BestPath->back().Base->getType();
1325     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1326       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1327         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1328       return DeclAccessPair();
1329     }
1330 
1331     //   ... [accessible, implied by other rules] base class of E.
1332     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1333                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1334     AS = BestPath->Access;
1335 
1336     ClassWithFields = BaseType->getAsCXXRecordDecl();
1337     S.BuildBasePathArray(Paths, BasePath);
1338   }
1339 
1340   // The above search did not check whether the selected class itself has base
1341   // classes with fields, so check that now.
1342   CXXBasePaths Paths;
1343   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1344     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1345       << (ClassWithFields == RD) << RD << ClassWithFields
1346       << Paths.front().back().Base->getType();
1347     return DeclAccessPair();
1348   }
1349 
1350   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1351 }
1352 
1353 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1354                                      ValueDecl *Src, QualType DecompType,
1355                                      const CXXRecordDecl *OrigRD) {
1356   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1357                             diag::err_incomplete_type))
1358     return true;
1359 
1360   CXXCastPath BasePath;
1361   DeclAccessPair BasePair =
1362       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1363   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1364   if (!RD)
1365     return true;
1366   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1367                                                  DecompType.getQualifiers());
1368 
1369   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1370     unsigned NumFields =
1371         std::count_if(RD->field_begin(), RD->field_end(),
1372                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1373     assert(Bindings.size() != NumFields);
1374     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1375         << DecompType << (unsigned)Bindings.size() << NumFields
1376         << (NumFields < Bindings.size());
1377     return true;
1378   };
1379 
1380   //   all of E's non-static data members shall be [...] well-formed
1381   //   when named as e.name in the context of the structured binding,
1382   //   E shall not have an anonymous union member, ...
1383   unsigned I = 0;
1384   for (auto *FD : RD->fields()) {
1385     if (FD->isUnnamedBitfield())
1386       continue;
1387 
1388     // All the non-static data members are required to be nameable, so they
1389     // must all have names.
1390     if (!FD->getDeclName()) {
1391       if (RD->isLambda()) {
1392         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1393         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1394         return true;
1395       }
1396 
1397       if (FD->isAnonymousStructOrUnion()) {
1398         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1399           << DecompType << FD->getType()->isUnionType();
1400         S.Diag(FD->getLocation(), diag::note_declared_at);
1401         return true;
1402       }
1403 
1404       // FIXME: Are there any other ways we could have an anonymous member?
1405     }
1406 
1407     // We have a real field to bind.
1408     if (I >= Bindings.size())
1409       return DiagnoseBadNumberOfBindings();
1410     auto *B = Bindings[I++];
1411     SourceLocation Loc = B->getLocation();
1412 
1413     // The field must be accessible in the context of the structured binding.
1414     // We already checked that the base class is accessible.
1415     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1416     // const_cast here.
1417     S.CheckStructuredBindingMemberAccess(
1418         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1419         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1420                                      BasePair.getAccess(), FD->getAccess())));
1421 
1422     // Initialize the binding to Src.FD.
1423     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1424     if (E.isInvalid())
1425       return true;
1426     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1427                             VK_LValue, &BasePath);
1428     if (E.isInvalid())
1429       return true;
1430     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1431                                   CXXScopeSpec(), FD,
1432                                   DeclAccessPair::make(FD, FD->getAccess()),
1433                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1434     if (E.isInvalid())
1435       return true;
1436 
1437     // If the type of the member is T, the referenced type is cv T, where cv is
1438     // the cv-qualification of the decomposition expression.
1439     //
1440     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1441     // 'const' to the type of the field.
1442     Qualifiers Q = DecompType.getQualifiers();
1443     if (FD->isMutable())
1444       Q.removeConst();
1445     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1446   }
1447 
1448   if (I != Bindings.size())
1449     return DiagnoseBadNumberOfBindings();
1450 
1451   return false;
1452 }
1453 
1454 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1455   QualType DecompType = DD->getType();
1456 
1457   // If the type of the decomposition is dependent, then so is the type of
1458   // each binding.
1459   if (DecompType->isDependentType()) {
1460     for (auto *B : DD->bindings())
1461       B->setType(Context.DependentTy);
1462     return;
1463   }
1464 
1465   DecompType = DecompType.getNonReferenceType();
1466   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1467 
1468   // C++1z [dcl.decomp]/2:
1469   //   If E is an array type [...]
1470   // As an extension, we also support decomposition of built-in complex and
1471   // vector types.
1472   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1473     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1474       DD->setInvalidDecl();
1475     return;
1476   }
1477   if (auto *VT = DecompType->getAs<VectorType>()) {
1478     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1479       DD->setInvalidDecl();
1480     return;
1481   }
1482   if (auto *CT = DecompType->getAs<ComplexType>()) {
1483     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1484       DD->setInvalidDecl();
1485     return;
1486   }
1487 
1488   // C++1z [dcl.decomp]/3:
1489   //   if the expression std::tuple_size<E>::value is a well-formed integral
1490   //   constant expression, [...]
1491   llvm::APSInt TupleSize(32);
1492   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1493   case IsTupleLike::Error:
1494     DD->setInvalidDecl();
1495     return;
1496 
1497   case IsTupleLike::TupleLike:
1498     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1499       DD->setInvalidDecl();
1500     return;
1501 
1502   case IsTupleLike::NotTupleLike:
1503     break;
1504   }
1505 
1506   // C++1z [dcl.dcl]/8:
1507   //   [E shall be of array or non-union class type]
1508   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1509   if (!RD || RD->isUnion()) {
1510     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1511         << DD << !RD << DecompType;
1512     DD->setInvalidDecl();
1513     return;
1514   }
1515 
1516   // C++1z [dcl.decomp]/4:
1517   //   all of E's non-static data members shall be [...] direct members of
1518   //   E or of the same unambiguous public base class of E, ...
1519   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1520     DD->setInvalidDecl();
1521 }
1522 
1523 /// Merge the exception specifications of two variable declarations.
1524 ///
1525 /// This is called when there's a redeclaration of a VarDecl. The function
1526 /// checks if the redeclaration might have an exception specification and
1527 /// validates compatibility and merges the specs if necessary.
1528 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1529   // Shortcut if exceptions are disabled.
1530   if (!getLangOpts().CXXExceptions)
1531     return;
1532 
1533   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1534          "Should only be called if types are otherwise the same.");
1535 
1536   QualType NewType = New->getType();
1537   QualType OldType = Old->getType();
1538 
1539   // We're only interested in pointers and references to functions, as well
1540   // as pointers to member functions.
1541   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1542     NewType = R->getPointeeType();
1543     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1544   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1545     NewType = P->getPointeeType();
1546     OldType = OldType->castAs<PointerType>()->getPointeeType();
1547   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1548     NewType = M->getPointeeType();
1549     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1550   }
1551 
1552   if (!NewType->isFunctionProtoType())
1553     return;
1554 
1555   // There's lots of special cases for functions. For function pointers, system
1556   // libraries are hopefully not as broken so that we don't need these
1557   // workarounds.
1558   if (CheckEquivalentExceptionSpec(
1559         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1560         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1561     New->setInvalidDecl();
1562   }
1563 }
1564 
1565 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1566 /// function declaration are well-formed according to C++
1567 /// [dcl.fct.default].
1568 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1569   unsigned NumParams = FD->getNumParams();
1570   unsigned ParamIdx = 0;
1571 
1572   // This checking doesn't make sense for explicit specializations; their
1573   // default arguments are determined by the declaration we're specializing,
1574   // not by FD.
1575   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1576     return;
1577   if (auto *FTD = FD->getDescribedFunctionTemplate())
1578     if (FTD->isMemberSpecialization())
1579       return;
1580 
1581   // Find first parameter with a default argument
1582   for (; ParamIdx < NumParams; ++ParamIdx) {
1583     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1584     if (Param->hasDefaultArg())
1585       break;
1586   }
1587 
1588   // C++20 [dcl.fct.default]p4:
1589   //   In a given function declaration, each parameter subsequent to a parameter
1590   //   with a default argument shall have a default argument supplied in this or
1591   //   a previous declaration, unless the parameter was expanded from a
1592   //   parameter pack, or shall be a function parameter pack.
1593   for (; ParamIdx < NumParams; ++ParamIdx) {
1594     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1595     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1596         !(CurrentInstantiationScope &&
1597           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1598       if (Param->isInvalidDecl())
1599         /* We already complained about this parameter. */;
1600       else if (Param->getIdentifier())
1601         Diag(Param->getLocation(),
1602              diag::err_param_default_argument_missing_name)
1603           << Param->getIdentifier();
1604       else
1605         Diag(Param->getLocation(),
1606              diag::err_param_default_argument_missing);
1607     }
1608   }
1609 }
1610 
1611 /// Check that the given type is a literal type. Issue a diagnostic if not,
1612 /// if Kind is Diagnose.
1613 /// \return \c true if a problem has been found (and optionally diagnosed).
1614 template <typename... Ts>
1615 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1616                              SourceLocation Loc, QualType T, unsigned DiagID,
1617                              Ts &&...DiagArgs) {
1618   if (T->isDependentType())
1619     return false;
1620 
1621   switch (Kind) {
1622   case Sema::CheckConstexprKind::Diagnose:
1623     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1624                                       std::forward<Ts>(DiagArgs)...);
1625 
1626   case Sema::CheckConstexprKind::CheckValid:
1627     return !T->isLiteralType(SemaRef.Context);
1628   }
1629 
1630   llvm_unreachable("unknown CheckConstexprKind");
1631 }
1632 
1633 /// Determine whether a destructor cannot be constexpr due to
1634 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1635                                                const CXXDestructorDecl *DD,
1636                                                Sema::CheckConstexprKind Kind) {
1637   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1638     const CXXRecordDecl *RD =
1639         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1640     if (!RD || RD->hasConstexprDestructor())
1641       return true;
1642 
1643     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1644       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1645           << DD->getConstexprKind() << !FD
1646           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1647       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1648           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1649     }
1650     return false;
1651   };
1652 
1653   const CXXRecordDecl *RD = DD->getParent();
1654   for (const CXXBaseSpecifier &B : RD->bases())
1655     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1656       return false;
1657   for (const FieldDecl *FD : RD->fields())
1658     if (!Check(FD->getLocation(), FD->getType(), FD))
1659       return false;
1660   return true;
1661 }
1662 
1663 /// Check whether a function's parameter types are all literal types. If so,
1664 /// return true. If not, produce a suitable diagnostic and return false.
1665 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1666                                          const FunctionDecl *FD,
1667                                          Sema::CheckConstexprKind Kind) {
1668   unsigned ArgIndex = 0;
1669   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1670   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1671                                               e = FT->param_type_end();
1672        i != e; ++i, ++ArgIndex) {
1673     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1674     SourceLocation ParamLoc = PD->getLocation();
1675     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1676                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1677                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1678                          FD->isConsteval()))
1679       return false;
1680   }
1681   return true;
1682 }
1683 
1684 /// Check whether a function's return type is a literal type. If so, return
1685 /// true. If not, produce a suitable diagnostic and return false.
1686 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1687                                      Sema::CheckConstexprKind Kind) {
1688   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1689                        diag::err_constexpr_non_literal_return,
1690                        FD->isConsteval()))
1691     return false;
1692   return true;
1693 }
1694 
1695 /// Get diagnostic %select index for tag kind for
1696 /// record diagnostic message.
1697 /// WARNING: Indexes apply to particular diagnostics only!
1698 ///
1699 /// \returns diagnostic %select index.
1700 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1701   switch (Tag) {
1702   case TTK_Struct: return 0;
1703   case TTK_Interface: return 1;
1704   case TTK_Class:  return 2;
1705   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1706   }
1707 }
1708 
1709 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1710                                        Stmt *Body,
1711                                        Sema::CheckConstexprKind Kind);
1712 
1713 // Check whether a function declaration satisfies the requirements of a
1714 // constexpr function definition or a constexpr constructor definition. If so,
1715 // return true. If not, produce appropriate diagnostics (unless asked not to by
1716 // Kind) and return false.
1717 //
1718 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1719 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1720                                             CheckConstexprKind Kind) {
1721   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1722   if (MD && MD->isInstance()) {
1723     // C++11 [dcl.constexpr]p4:
1724     //  The definition of a constexpr constructor shall satisfy the following
1725     //  constraints:
1726     //  - the class shall not have any virtual base classes;
1727     //
1728     // FIXME: This only applies to constructors and destructors, not arbitrary
1729     // member functions.
1730     const CXXRecordDecl *RD = MD->getParent();
1731     if (RD->getNumVBases()) {
1732       if (Kind == CheckConstexprKind::CheckValid)
1733         return false;
1734 
1735       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1736         << isa<CXXConstructorDecl>(NewFD)
1737         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1738       for (const auto &I : RD->vbases())
1739         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1740             << I.getSourceRange();
1741       return false;
1742     }
1743   }
1744 
1745   if (!isa<CXXConstructorDecl>(NewFD)) {
1746     // C++11 [dcl.constexpr]p3:
1747     //  The definition of a constexpr function shall satisfy the following
1748     //  constraints:
1749     // - it shall not be virtual; (removed in C++20)
1750     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1751     if (Method && Method->isVirtual()) {
1752       if (getLangOpts().CPlusPlus20) {
1753         if (Kind == CheckConstexprKind::Diagnose)
1754           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1755       } else {
1756         if (Kind == CheckConstexprKind::CheckValid)
1757           return false;
1758 
1759         Method = Method->getCanonicalDecl();
1760         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1761 
1762         // If it's not obvious why this function is virtual, find an overridden
1763         // function which uses the 'virtual' keyword.
1764         const CXXMethodDecl *WrittenVirtual = Method;
1765         while (!WrittenVirtual->isVirtualAsWritten())
1766           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1767         if (WrittenVirtual != Method)
1768           Diag(WrittenVirtual->getLocation(),
1769                diag::note_overridden_virtual_function);
1770         return false;
1771       }
1772     }
1773 
1774     // - its return type shall be a literal type;
1775     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1776       return false;
1777   }
1778 
1779   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1780     // A destructor can be constexpr only if the defaulted destructor could be;
1781     // we don't need to check the members and bases if we already know they all
1782     // have constexpr destructors.
1783     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1784       if (Kind == CheckConstexprKind::CheckValid)
1785         return false;
1786       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1787         return false;
1788     }
1789   }
1790 
1791   // - each of its parameter types shall be a literal type;
1792   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1793     return false;
1794 
1795   Stmt *Body = NewFD->getBody();
1796   assert(Body &&
1797          "CheckConstexprFunctionDefinition called on function with no body");
1798   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1799 }
1800 
1801 /// Check the given declaration statement is legal within a constexpr function
1802 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1803 ///
1804 /// \return true if the body is OK (maybe only as an extension), false if we
1805 ///         have diagnosed a problem.
1806 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1807                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1808                                    Sema::CheckConstexprKind Kind) {
1809   // C++11 [dcl.constexpr]p3 and p4:
1810   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1811   //  contain only
1812   for (const auto *DclIt : DS->decls()) {
1813     switch (DclIt->getKind()) {
1814     case Decl::StaticAssert:
1815     case Decl::Using:
1816     case Decl::UsingShadow:
1817     case Decl::UsingDirective:
1818     case Decl::UnresolvedUsingTypename:
1819     case Decl::UnresolvedUsingValue:
1820       //   - static_assert-declarations
1821       //   - using-declarations,
1822       //   - using-directives,
1823       continue;
1824 
1825     case Decl::Typedef:
1826     case Decl::TypeAlias: {
1827       //   - typedef declarations and alias-declarations that do not define
1828       //     classes or enumerations,
1829       const auto *TN = cast<TypedefNameDecl>(DclIt);
1830       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1831         // Don't allow variably-modified types in constexpr functions.
1832         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1833           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1834           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1835             << TL.getSourceRange() << TL.getType()
1836             << isa<CXXConstructorDecl>(Dcl);
1837         }
1838         return false;
1839       }
1840       continue;
1841     }
1842 
1843     case Decl::Enum:
1844     case Decl::CXXRecord:
1845       // C++1y allows types to be defined, not just declared.
1846       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1847         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1848           SemaRef.Diag(DS->getBeginLoc(),
1849                        SemaRef.getLangOpts().CPlusPlus14
1850                            ? diag::warn_cxx11_compat_constexpr_type_definition
1851                            : diag::ext_constexpr_type_definition)
1852               << isa<CXXConstructorDecl>(Dcl);
1853         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1854           return false;
1855         }
1856       }
1857       continue;
1858 
1859     case Decl::EnumConstant:
1860     case Decl::IndirectField:
1861     case Decl::ParmVar:
1862       // These can only appear with other declarations which are banned in
1863       // C++11 and permitted in C++1y, so ignore them.
1864       continue;
1865 
1866     case Decl::Var:
1867     case Decl::Decomposition: {
1868       // C++1y [dcl.constexpr]p3 allows anything except:
1869       //   a definition of a variable of non-literal type or of static or
1870       //   thread storage duration or [before C++2a] for which no
1871       //   initialization is performed.
1872       const auto *VD = cast<VarDecl>(DclIt);
1873       if (VD->isThisDeclarationADefinition()) {
1874         if (VD->isStaticLocal()) {
1875           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1876             SemaRef.Diag(VD->getLocation(),
1877                          diag::err_constexpr_local_var_static)
1878               << isa<CXXConstructorDecl>(Dcl)
1879               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1880           }
1881           return false;
1882         }
1883         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1884                              diag::err_constexpr_local_var_non_literal_type,
1885                              isa<CXXConstructorDecl>(Dcl)))
1886           return false;
1887         if (!VD->getType()->isDependentType() &&
1888             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1889           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1890             SemaRef.Diag(
1891                 VD->getLocation(),
1892                 SemaRef.getLangOpts().CPlusPlus20
1893                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1894                     : diag::ext_constexpr_local_var_no_init)
1895                 << isa<CXXConstructorDecl>(Dcl);
1896           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1897             return false;
1898           }
1899           continue;
1900         }
1901       }
1902       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1903         SemaRef.Diag(VD->getLocation(),
1904                      SemaRef.getLangOpts().CPlusPlus14
1905                       ? diag::warn_cxx11_compat_constexpr_local_var
1906                       : diag::ext_constexpr_local_var)
1907           << isa<CXXConstructorDecl>(Dcl);
1908       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1909         return false;
1910       }
1911       continue;
1912     }
1913 
1914     case Decl::NamespaceAlias:
1915     case Decl::Function:
1916       // These are disallowed in C++11 and permitted in C++1y. Allow them
1917       // everywhere as an extension.
1918       if (!Cxx1yLoc.isValid())
1919         Cxx1yLoc = DS->getBeginLoc();
1920       continue;
1921 
1922     default:
1923       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1924         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1925             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1926       }
1927       return false;
1928     }
1929   }
1930 
1931   return true;
1932 }
1933 
1934 /// Check that the given field is initialized within a constexpr constructor.
1935 ///
1936 /// \param Dcl The constexpr constructor being checked.
1937 /// \param Field The field being checked. This may be a member of an anonymous
1938 ///        struct or union nested within the class being checked.
1939 /// \param Inits All declarations, including anonymous struct/union members and
1940 ///        indirect members, for which any initialization was provided.
1941 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1942 ///        multiple notes for different members to the same error.
1943 /// \param Kind Whether we're diagnosing a constructor as written or determining
1944 ///        whether the formal requirements are satisfied.
1945 /// \return \c false if we're checking for validity and the constructor does
1946 ///         not satisfy the requirements on a constexpr constructor.
1947 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1948                                           const FunctionDecl *Dcl,
1949                                           FieldDecl *Field,
1950                                           llvm::SmallSet<Decl*, 16> &Inits,
1951                                           bool &Diagnosed,
1952                                           Sema::CheckConstexprKind Kind) {
1953   // In C++20 onwards, there's nothing to check for validity.
1954   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1955       SemaRef.getLangOpts().CPlusPlus20)
1956     return true;
1957 
1958   if (Field->isInvalidDecl())
1959     return true;
1960 
1961   if (Field->isUnnamedBitfield())
1962     return true;
1963 
1964   // Anonymous unions with no variant members and empty anonymous structs do not
1965   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1966   // indirect fields don't need initializing.
1967   if (Field->isAnonymousStructOrUnion() &&
1968       (Field->getType()->isUnionType()
1969            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1970            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1971     return true;
1972 
1973   if (!Inits.count(Field)) {
1974     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1975       if (!Diagnosed) {
1976         SemaRef.Diag(Dcl->getLocation(),
1977                      SemaRef.getLangOpts().CPlusPlus20
1978                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1979                          : diag::ext_constexpr_ctor_missing_init);
1980         Diagnosed = true;
1981       }
1982       SemaRef.Diag(Field->getLocation(),
1983                    diag::note_constexpr_ctor_missing_init);
1984     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1985       return false;
1986     }
1987   } else if (Field->isAnonymousStructOrUnion()) {
1988     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1989     for (auto *I : RD->fields())
1990       // If an anonymous union contains an anonymous struct of which any member
1991       // is initialized, all members must be initialized.
1992       if (!RD->isUnion() || Inits.count(I))
1993         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1994                                            Kind))
1995           return false;
1996   }
1997   return true;
1998 }
1999 
2000 /// Check the provided statement is allowed in a constexpr function
2001 /// definition.
2002 static bool
2003 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2004                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2005                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2006                            Sema::CheckConstexprKind Kind) {
2007   // - its function-body shall be [...] a compound-statement that contains only
2008   switch (S->getStmtClass()) {
2009   case Stmt::NullStmtClass:
2010     //   - null statements,
2011     return true;
2012 
2013   case Stmt::DeclStmtClass:
2014     //   - static_assert-declarations
2015     //   - using-declarations,
2016     //   - using-directives,
2017     //   - typedef declarations and alias-declarations that do not define
2018     //     classes or enumerations,
2019     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2020       return false;
2021     return true;
2022 
2023   case Stmt::ReturnStmtClass:
2024     //   - and exactly one return statement;
2025     if (isa<CXXConstructorDecl>(Dcl)) {
2026       // C++1y allows return statements in constexpr constructors.
2027       if (!Cxx1yLoc.isValid())
2028         Cxx1yLoc = S->getBeginLoc();
2029       return true;
2030     }
2031 
2032     ReturnStmts.push_back(S->getBeginLoc());
2033     return true;
2034 
2035   case Stmt::CompoundStmtClass: {
2036     // C++1y allows compound-statements.
2037     if (!Cxx1yLoc.isValid())
2038       Cxx1yLoc = S->getBeginLoc();
2039 
2040     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2041     for (auto *BodyIt : CompStmt->body()) {
2042       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2043                                       Cxx1yLoc, Cxx2aLoc, Kind))
2044         return false;
2045     }
2046     return true;
2047   }
2048 
2049   case Stmt::AttributedStmtClass:
2050     if (!Cxx1yLoc.isValid())
2051       Cxx1yLoc = S->getBeginLoc();
2052     return true;
2053 
2054   case Stmt::IfStmtClass: {
2055     // C++1y allows if-statements.
2056     if (!Cxx1yLoc.isValid())
2057       Cxx1yLoc = S->getBeginLoc();
2058 
2059     IfStmt *If = cast<IfStmt>(S);
2060     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2061                                     Cxx1yLoc, Cxx2aLoc, Kind))
2062       return false;
2063     if (If->getElse() &&
2064         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2065                                     Cxx1yLoc, Cxx2aLoc, Kind))
2066       return false;
2067     return true;
2068   }
2069 
2070   case Stmt::WhileStmtClass:
2071   case Stmt::DoStmtClass:
2072   case Stmt::ForStmtClass:
2073   case Stmt::CXXForRangeStmtClass:
2074   case Stmt::ContinueStmtClass:
2075     // C++1y allows all of these. We don't allow them as extensions in C++11,
2076     // because they don't make sense without variable mutation.
2077     if (!SemaRef.getLangOpts().CPlusPlus14)
2078       break;
2079     if (!Cxx1yLoc.isValid())
2080       Cxx1yLoc = S->getBeginLoc();
2081     for (Stmt *SubStmt : S->children())
2082       if (SubStmt &&
2083           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2084                                       Cxx1yLoc, Cxx2aLoc, Kind))
2085         return false;
2086     return true;
2087 
2088   case Stmt::SwitchStmtClass:
2089   case Stmt::CaseStmtClass:
2090   case Stmt::DefaultStmtClass:
2091   case Stmt::BreakStmtClass:
2092     // C++1y allows switch-statements, and since they don't need variable
2093     // mutation, we can reasonably allow them in C++11 as an extension.
2094     if (!Cxx1yLoc.isValid())
2095       Cxx1yLoc = S->getBeginLoc();
2096     for (Stmt *SubStmt : S->children())
2097       if (SubStmt &&
2098           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2099                                       Cxx1yLoc, Cxx2aLoc, Kind))
2100         return false;
2101     return true;
2102 
2103   case Stmt::GCCAsmStmtClass:
2104   case Stmt::MSAsmStmtClass:
2105     // C++2a allows inline assembly statements.
2106   case Stmt::CXXTryStmtClass:
2107     if (Cxx2aLoc.isInvalid())
2108       Cxx2aLoc = S->getBeginLoc();
2109     for (Stmt *SubStmt : S->children()) {
2110       if (SubStmt &&
2111           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2112                                       Cxx1yLoc, Cxx2aLoc, Kind))
2113         return false;
2114     }
2115     return true;
2116 
2117   case Stmt::CXXCatchStmtClass:
2118     // Do not bother checking the language mode (already covered by the
2119     // try block check).
2120     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2121                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2122                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2123       return false;
2124     return true;
2125 
2126   default:
2127     if (!isa<Expr>(S))
2128       break;
2129 
2130     // C++1y allows expression-statements.
2131     if (!Cxx1yLoc.isValid())
2132       Cxx1yLoc = S->getBeginLoc();
2133     return true;
2134   }
2135 
2136   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2137     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2138         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2139   }
2140   return false;
2141 }
2142 
2143 /// Check the body for the given constexpr function declaration only contains
2144 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2145 ///
2146 /// \return true if the body is OK, false if we have found or diagnosed a
2147 /// problem.
2148 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2149                                        Stmt *Body,
2150                                        Sema::CheckConstexprKind Kind) {
2151   SmallVector<SourceLocation, 4> ReturnStmts;
2152 
2153   if (isa<CXXTryStmt>(Body)) {
2154     // C++11 [dcl.constexpr]p3:
2155     //  The definition of a constexpr function shall satisfy the following
2156     //  constraints: [...]
2157     // - its function-body shall be = delete, = default, or a
2158     //   compound-statement
2159     //
2160     // C++11 [dcl.constexpr]p4:
2161     //  In the definition of a constexpr constructor, [...]
2162     // - its function-body shall not be a function-try-block;
2163     //
2164     // This restriction is lifted in C++2a, as long as inner statements also
2165     // apply the general constexpr rules.
2166     switch (Kind) {
2167     case Sema::CheckConstexprKind::CheckValid:
2168       if (!SemaRef.getLangOpts().CPlusPlus20)
2169         return false;
2170       break;
2171 
2172     case Sema::CheckConstexprKind::Diagnose:
2173       SemaRef.Diag(Body->getBeginLoc(),
2174            !SemaRef.getLangOpts().CPlusPlus20
2175                ? diag::ext_constexpr_function_try_block_cxx20
2176                : diag::warn_cxx17_compat_constexpr_function_try_block)
2177           << isa<CXXConstructorDecl>(Dcl);
2178       break;
2179     }
2180   }
2181 
2182   // - its function-body shall be [...] a compound-statement that contains only
2183   //   [... list of cases ...]
2184   //
2185   // Note that walking the children here is enough to properly check for
2186   // CompoundStmt and CXXTryStmt body.
2187   SourceLocation Cxx1yLoc, Cxx2aLoc;
2188   for (Stmt *SubStmt : Body->children()) {
2189     if (SubStmt &&
2190         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2191                                     Cxx1yLoc, Cxx2aLoc, Kind))
2192       return false;
2193   }
2194 
2195   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2196     // If this is only valid as an extension, report that we don't satisfy the
2197     // constraints of the current language.
2198     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2199         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2200       return false;
2201   } else if (Cxx2aLoc.isValid()) {
2202     SemaRef.Diag(Cxx2aLoc,
2203          SemaRef.getLangOpts().CPlusPlus20
2204            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2205            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2206       << isa<CXXConstructorDecl>(Dcl);
2207   } else if (Cxx1yLoc.isValid()) {
2208     SemaRef.Diag(Cxx1yLoc,
2209          SemaRef.getLangOpts().CPlusPlus14
2210            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2211            : diag::ext_constexpr_body_invalid_stmt)
2212       << isa<CXXConstructorDecl>(Dcl);
2213   }
2214 
2215   if (const CXXConstructorDecl *Constructor
2216         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2217     const CXXRecordDecl *RD = Constructor->getParent();
2218     // DR1359:
2219     // - every non-variant non-static data member and base class sub-object
2220     //   shall be initialized;
2221     // DR1460:
2222     // - if the class is a union having variant members, exactly one of them
2223     //   shall be initialized;
2224     if (RD->isUnion()) {
2225       if (Constructor->getNumCtorInitializers() == 0 &&
2226           RD->hasVariantMembers()) {
2227         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2228           SemaRef.Diag(
2229               Dcl->getLocation(),
2230               SemaRef.getLangOpts().CPlusPlus20
2231                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2232                   : diag::ext_constexpr_union_ctor_no_init);
2233         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2234           return false;
2235         }
2236       }
2237     } else if (!Constructor->isDependentContext() &&
2238                !Constructor->isDelegatingConstructor()) {
2239       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2240 
2241       // Skip detailed checking if we have enough initializers, and we would
2242       // allow at most one initializer per member.
2243       bool AnyAnonStructUnionMembers = false;
2244       unsigned Fields = 0;
2245       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2246            E = RD->field_end(); I != E; ++I, ++Fields) {
2247         if (I->isAnonymousStructOrUnion()) {
2248           AnyAnonStructUnionMembers = true;
2249           break;
2250         }
2251       }
2252       // DR1460:
2253       // - if the class is a union-like class, but is not a union, for each of
2254       //   its anonymous union members having variant members, exactly one of
2255       //   them shall be initialized;
2256       if (AnyAnonStructUnionMembers ||
2257           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2258         // Check initialization of non-static data members. Base classes are
2259         // always initialized so do not need to be checked. Dependent bases
2260         // might not have initializers in the member initializer list.
2261         llvm::SmallSet<Decl*, 16> Inits;
2262         for (const auto *I: Constructor->inits()) {
2263           if (FieldDecl *FD = I->getMember())
2264             Inits.insert(FD);
2265           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2266             Inits.insert(ID->chain_begin(), ID->chain_end());
2267         }
2268 
2269         bool Diagnosed = false;
2270         for (auto *I : RD->fields())
2271           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2272                                              Kind))
2273             return false;
2274       }
2275     }
2276   } else {
2277     if (ReturnStmts.empty()) {
2278       // C++1y doesn't require constexpr functions to contain a 'return'
2279       // statement. We still do, unless the return type might be void, because
2280       // otherwise if there's no return statement, the function cannot
2281       // be used in a core constant expression.
2282       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2283                 (Dcl->getReturnType()->isVoidType() ||
2284                  Dcl->getReturnType()->isDependentType());
2285       switch (Kind) {
2286       case Sema::CheckConstexprKind::Diagnose:
2287         SemaRef.Diag(Dcl->getLocation(),
2288                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2289                         : diag::err_constexpr_body_no_return)
2290             << Dcl->isConsteval();
2291         if (!OK)
2292           return false;
2293         break;
2294 
2295       case Sema::CheckConstexprKind::CheckValid:
2296         // The formal requirements don't include this rule in C++14, even
2297         // though the "must be able to produce a constant expression" rules
2298         // still imply it in some cases.
2299         if (!SemaRef.getLangOpts().CPlusPlus14)
2300           return false;
2301         break;
2302       }
2303     } else if (ReturnStmts.size() > 1) {
2304       switch (Kind) {
2305       case Sema::CheckConstexprKind::Diagnose:
2306         SemaRef.Diag(
2307             ReturnStmts.back(),
2308             SemaRef.getLangOpts().CPlusPlus14
2309                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2310                 : diag::ext_constexpr_body_multiple_return);
2311         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2312           SemaRef.Diag(ReturnStmts[I],
2313                        diag::note_constexpr_body_previous_return);
2314         break;
2315 
2316       case Sema::CheckConstexprKind::CheckValid:
2317         if (!SemaRef.getLangOpts().CPlusPlus14)
2318           return false;
2319         break;
2320       }
2321     }
2322   }
2323 
2324   // C++11 [dcl.constexpr]p5:
2325   //   if no function argument values exist such that the function invocation
2326   //   substitution would produce a constant expression, the program is
2327   //   ill-formed; no diagnostic required.
2328   // C++11 [dcl.constexpr]p3:
2329   //   - every constructor call and implicit conversion used in initializing the
2330   //     return value shall be one of those allowed in a constant expression.
2331   // C++11 [dcl.constexpr]p4:
2332   //   - every constructor involved in initializing non-static data members and
2333   //     base class sub-objects shall be a constexpr constructor.
2334   //
2335   // Note that this rule is distinct from the "requirements for a constexpr
2336   // function", so is not checked in CheckValid mode.
2337   SmallVector<PartialDiagnosticAt, 8> Diags;
2338   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2339       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2340     SemaRef.Diag(Dcl->getLocation(),
2341                  diag::ext_constexpr_function_never_constant_expr)
2342         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2343     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2344       SemaRef.Diag(Diags[I].first, Diags[I].second);
2345     // Don't return false here: we allow this for compatibility in
2346     // system headers.
2347   }
2348 
2349   return true;
2350 }
2351 
2352 /// Get the class that is directly named by the current context. This is the
2353 /// class for which an unqualified-id in this scope could name a constructor
2354 /// or destructor.
2355 ///
2356 /// If the scope specifier denotes a class, this will be that class.
2357 /// If the scope specifier is empty, this will be the class whose
2358 /// member-specification we are currently within. Otherwise, there
2359 /// is no such class.
2360 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2361   assert(getLangOpts().CPlusPlus && "No class names in C!");
2362 
2363   if (SS && SS->isInvalid())
2364     return nullptr;
2365 
2366   if (SS && SS->isNotEmpty()) {
2367     DeclContext *DC = computeDeclContext(*SS, true);
2368     return dyn_cast_or_null<CXXRecordDecl>(DC);
2369   }
2370 
2371   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2372 }
2373 
2374 /// isCurrentClassName - Determine whether the identifier II is the
2375 /// name of the class type currently being defined. In the case of
2376 /// nested classes, this will only return true if II is the name of
2377 /// the innermost class.
2378 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2379                               const CXXScopeSpec *SS) {
2380   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2381   return CurDecl && &II == CurDecl->getIdentifier();
2382 }
2383 
2384 /// Determine whether the identifier II is a typo for the name of
2385 /// the class type currently being defined. If so, update it to the identifier
2386 /// that should have been used.
2387 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2388   assert(getLangOpts().CPlusPlus && "No class names in C!");
2389 
2390   if (!getLangOpts().SpellChecking)
2391     return false;
2392 
2393   CXXRecordDecl *CurDecl;
2394   if (SS && SS->isSet() && !SS->isInvalid()) {
2395     DeclContext *DC = computeDeclContext(*SS, true);
2396     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2397   } else
2398     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2399 
2400   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2401       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2402           < II->getLength()) {
2403     II = CurDecl->getIdentifier();
2404     return true;
2405   }
2406 
2407   return false;
2408 }
2409 
2410 /// Determine whether the given class is a base class of the given
2411 /// class, including looking at dependent bases.
2412 static bool findCircularInheritance(const CXXRecordDecl *Class,
2413                                     const CXXRecordDecl *Current) {
2414   SmallVector<const CXXRecordDecl*, 8> Queue;
2415 
2416   Class = Class->getCanonicalDecl();
2417   while (true) {
2418     for (const auto &I : Current->bases()) {
2419       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2420       if (!Base)
2421         continue;
2422 
2423       Base = Base->getDefinition();
2424       if (!Base)
2425         continue;
2426 
2427       if (Base->getCanonicalDecl() == Class)
2428         return true;
2429 
2430       Queue.push_back(Base);
2431     }
2432 
2433     if (Queue.empty())
2434       return false;
2435 
2436     Current = Queue.pop_back_val();
2437   }
2438 
2439   return false;
2440 }
2441 
2442 /// Check the validity of a C++ base class specifier.
2443 ///
2444 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2445 /// and returns NULL otherwise.
2446 CXXBaseSpecifier *
2447 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2448                          SourceRange SpecifierRange,
2449                          bool Virtual, AccessSpecifier Access,
2450                          TypeSourceInfo *TInfo,
2451                          SourceLocation EllipsisLoc) {
2452   QualType BaseType = TInfo->getType();
2453   if (BaseType->containsErrors()) {
2454     // Already emitted a diagnostic when parsing the error type.
2455     return nullptr;
2456   }
2457   // C++ [class.union]p1:
2458   //   A union shall not have base classes.
2459   if (Class->isUnion()) {
2460     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2461       << SpecifierRange;
2462     return nullptr;
2463   }
2464 
2465   if (EllipsisLoc.isValid() &&
2466       !TInfo->getType()->containsUnexpandedParameterPack()) {
2467     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2468       << TInfo->getTypeLoc().getSourceRange();
2469     EllipsisLoc = SourceLocation();
2470   }
2471 
2472   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2473 
2474   if (BaseType->isDependentType()) {
2475     // Make sure that we don't have circular inheritance among our dependent
2476     // bases. For non-dependent bases, the check for completeness below handles
2477     // this.
2478     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2479       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2480           ((BaseDecl = BaseDecl->getDefinition()) &&
2481            findCircularInheritance(Class, BaseDecl))) {
2482         Diag(BaseLoc, diag::err_circular_inheritance)
2483           << BaseType << Context.getTypeDeclType(Class);
2484 
2485         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2486           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2487             << BaseType;
2488 
2489         return nullptr;
2490       }
2491     }
2492 
2493     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2494                                           Class->getTagKind() == TTK_Class,
2495                                           Access, TInfo, EllipsisLoc);
2496   }
2497 
2498   // Base specifiers must be record types.
2499   if (!BaseType->isRecordType()) {
2500     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2501     return nullptr;
2502   }
2503 
2504   // C++ [class.union]p1:
2505   //   A union shall not be used as a base class.
2506   if (BaseType->isUnionType()) {
2507     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2508     return nullptr;
2509   }
2510 
2511   // For the MS ABI, propagate DLL attributes to base class templates.
2512   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2513     if (Attr *ClassAttr = getDLLAttr(Class)) {
2514       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2515               BaseType->getAsCXXRecordDecl())) {
2516         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2517                                             BaseLoc);
2518       }
2519     }
2520   }
2521 
2522   // C++ [class.derived]p2:
2523   //   The class-name in a base-specifier shall not be an incompletely
2524   //   defined class.
2525   if (RequireCompleteType(BaseLoc, BaseType,
2526                           diag::err_incomplete_base_class, SpecifierRange)) {
2527     Class->setInvalidDecl();
2528     return nullptr;
2529   }
2530 
2531   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2532   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2533   assert(BaseDecl && "Record type has no declaration");
2534   BaseDecl = BaseDecl->getDefinition();
2535   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2536   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2537   assert(CXXBaseDecl && "Base type is not a C++ type");
2538 
2539   // Microsoft docs say:
2540   // "If a base-class has a code_seg attribute, derived classes must have the
2541   // same attribute."
2542   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2543   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2544   if ((DerivedCSA || BaseCSA) &&
2545       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2546     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2547     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2548       << CXXBaseDecl;
2549     return nullptr;
2550   }
2551 
2552   // A class which contains a flexible array member is not suitable for use as a
2553   // base class:
2554   //   - If the layout determines that a base comes before another base,
2555   //     the flexible array member would index into the subsequent base.
2556   //   - If the layout determines that base comes before the derived class,
2557   //     the flexible array member would index into the derived class.
2558   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2559     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2560       << CXXBaseDecl->getDeclName();
2561     return nullptr;
2562   }
2563 
2564   // C++ [class]p3:
2565   //   If a class is marked final and it appears as a base-type-specifier in
2566   //   base-clause, the program is ill-formed.
2567   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2568     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2569       << CXXBaseDecl->getDeclName()
2570       << FA->isSpelledAsSealed();
2571     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2572         << CXXBaseDecl->getDeclName() << FA->getRange();
2573     return nullptr;
2574   }
2575 
2576   if (BaseDecl->isInvalidDecl())
2577     Class->setInvalidDecl();
2578 
2579   // Create the base specifier.
2580   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2581                                         Class->getTagKind() == TTK_Class,
2582                                         Access, TInfo, EllipsisLoc);
2583 }
2584 
2585 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2586 /// one entry in the base class list of a class specifier, for
2587 /// example:
2588 ///    class foo : public bar, virtual private baz {
2589 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2590 BaseResult
2591 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2592                          ParsedAttributes &Attributes,
2593                          bool Virtual, AccessSpecifier Access,
2594                          ParsedType basetype, SourceLocation BaseLoc,
2595                          SourceLocation EllipsisLoc) {
2596   if (!classdecl)
2597     return true;
2598 
2599   AdjustDeclIfTemplate(classdecl);
2600   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2601   if (!Class)
2602     return true;
2603 
2604   // We haven't yet attached the base specifiers.
2605   Class->setIsParsingBaseSpecifiers();
2606 
2607   // We do not support any C++11 attributes on base-specifiers yet.
2608   // Diagnose any attributes we see.
2609   for (const ParsedAttr &AL : Attributes) {
2610     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2611       continue;
2612     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2613                           ? (unsigned)diag::warn_unknown_attribute_ignored
2614                           : (unsigned)diag::err_base_specifier_attribute)
2615         << AL;
2616   }
2617 
2618   TypeSourceInfo *TInfo = nullptr;
2619   GetTypeFromParser(basetype, &TInfo);
2620 
2621   if (EllipsisLoc.isInvalid() &&
2622       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2623                                       UPPC_BaseType))
2624     return true;
2625 
2626   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2627                                                       Virtual, Access, TInfo,
2628                                                       EllipsisLoc))
2629     return BaseSpec;
2630   else
2631     Class->setInvalidDecl();
2632 
2633   return true;
2634 }
2635 
2636 /// Use small set to collect indirect bases.  As this is only used
2637 /// locally, there's no need to abstract the small size parameter.
2638 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2639 
2640 /// Recursively add the bases of Type.  Don't add Type itself.
2641 static void
2642 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2643                   const QualType &Type)
2644 {
2645   // Even though the incoming type is a base, it might not be
2646   // a class -- it could be a template parm, for instance.
2647   if (auto Rec = Type->getAs<RecordType>()) {
2648     auto Decl = Rec->getAsCXXRecordDecl();
2649 
2650     // Iterate over its bases.
2651     for (const auto &BaseSpec : Decl->bases()) {
2652       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2653         .getUnqualifiedType();
2654       if (Set.insert(Base).second)
2655         // If we've not already seen it, recurse.
2656         NoteIndirectBases(Context, Set, Base);
2657     }
2658   }
2659 }
2660 
2661 /// Performs the actual work of attaching the given base class
2662 /// specifiers to a C++ class.
2663 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2664                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2665  if (Bases.empty())
2666     return false;
2667 
2668   // Used to keep track of which base types we have already seen, so
2669   // that we can properly diagnose redundant direct base types. Note
2670   // that the key is always the unqualified canonical type of the base
2671   // class.
2672   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2673 
2674   // Used to track indirect bases so we can see if a direct base is
2675   // ambiguous.
2676   IndirectBaseSet IndirectBaseTypes;
2677 
2678   // Copy non-redundant base specifiers into permanent storage.
2679   unsigned NumGoodBases = 0;
2680   bool Invalid = false;
2681   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2682     QualType NewBaseType
2683       = Context.getCanonicalType(Bases[idx]->getType());
2684     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2685 
2686     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2687     if (KnownBase) {
2688       // C++ [class.mi]p3:
2689       //   A class shall not be specified as a direct base class of a
2690       //   derived class more than once.
2691       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2692           << KnownBase->getType() << Bases[idx]->getSourceRange();
2693 
2694       // Delete the duplicate base class specifier; we're going to
2695       // overwrite its pointer later.
2696       Context.Deallocate(Bases[idx]);
2697 
2698       Invalid = true;
2699     } else {
2700       // Okay, add this new base class.
2701       KnownBase = Bases[idx];
2702       Bases[NumGoodBases++] = Bases[idx];
2703 
2704       // Note this base's direct & indirect bases, if there could be ambiguity.
2705       if (Bases.size() > 1)
2706         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2707 
2708       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2709         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2710         if (Class->isInterface() &&
2711               (!RD->isInterfaceLike() ||
2712                KnownBase->getAccessSpecifier() != AS_public)) {
2713           // The Microsoft extension __interface does not permit bases that
2714           // are not themselves public interfaces.
2715           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2716               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2717               << RD->getSourceRange();
2718           Invalid = true;
2719         }
2720         if (RD->hasAttr<WeakAttr>())
2721           Class->addAttr(WeakAttr::CreateImplicit(Context));
2722       }
2723     }
2724   }
2725 
2726   // Attach the remaining base class specifiers to the derived class.
2727   Class->setBases(Bases.data(), NumGoodBases);
2728 
2729   // Check that the only base classes that are duplicate are virtual.
2730   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2731     // Check whether this direct base is inaccessible due to ambiguity.
2732     QualType BaseType = Bases[idx]->getType();
2733 
2734     // Skip all dependent types in templates being used as base specifiers.
2735     // Checks below assume that the base specifier is a CXXRecord.
2736     if (BaseType->isDependentType())
2737       continue;
2738 
2739     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2740       .getUnqualifiedType();
2741 
2742     if (IndirectBaseTypes.count(CanonicalBase)) {
2743       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2744                          /*DetectVirtual=*/true);
2745       bool found
2746         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2747       assert(found);
2748       (void)found;
2749 
2750       if (Paths.isAmbiguous(CanonicalBase))
2751         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2752             << BaseType << getAmbiguousPathsDisplayString(Paths)
2753             << Bases[idx]->getSourceRange();
2754       else
2755         assert(Bases[idx]->isVirtual());
2756     }
2757 
2758     // Delete the base class specifier, since its data has been copied
2759     // into the CXXRecordDecl.
2760     Context.Deallocate(Bases[idx]);
2761   }
2762 
2763   return Invalid;
2764 }
2765 
2766 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2767 /// class, after checking whether there are any duplicate base
2768 /// classes.
2769 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2770                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2771   if (!ClassDecl || Bases.empty())
2772     return;
2773 
2774   AdjustDeclIfTemplate(ClassDecl);
2775   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2776 }
2777 
2778 /// Determine whether the type \p Derived is a C++ class that is
2779 /// derived from the type \p Base.
2780 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2781   if (!getLangOpts().CPlusPlus)
2782     return false;
2783 
2784   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2785   if (!DerivedRD)
2786     return false;
2787 
2788   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2789   if (!BaseRD)
2790     return false;
2791 
2792   // If either the base or the derived type is invalid, don't try to
2793   // check whether one is derived from the other.
2794   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2795     return false;
2796 
2797   // FIXME: In a modules build, do we need the entire path to be visible for us
2798   // to be able to use the inheritance relationship?
2799   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2800     return false;
2801 
2802   return DerivedRD->isDerivedFrom(BaseRD);
2803 }
2804 
2805 /// Determine whether the type \p Derived is a C++ class that is
2806 /// derived from the type \p Base.
2807 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2808                          CXXBasePaths &Paths) {
2809   if (!getLangOpts().CPlusPlus)
2810     return false;
2811 
2812   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2813   if (!DerivedRD)
2814     return false;
2815 
2816   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2817   if (!BaseRD)
2818     return false;
2819 
2820   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2821     return false;
2822 
2823   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2824 }
2825 
2826 static void BuildBasePathArray(const CXXBasePath &Path,
2827                                CXXCastPath &BasePathArray) {
2828   // We first go backward and check if we have a virtual base.
2829   // FIXME: It would be better if CXXBasePath had the base specifier for
2830   // the nearest virtual base.
2831   unsigned Start = 0;
2832   for (unsigned I = Path.size(); I != 0; --I) {
2833     if (Path[I - 1].Base->isVirtual()) {
2834       Start = I - 1;
2835       break;
2836     }
2837   }
2838 
2839   // Now add all bases.
2840   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2841     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2842 }
2843 
2844 
2845 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2846                               CXXCastPath &BasePathArray) {
2847   assert(BasePathArray.empty() && "Base path array must be empty!");
2848   assert(Paths.isRecordingPaths() && "Must record paths!");
2849   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2850 }
2851 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2852 /// conversion (where Derived and Base are class types) is
2853 /// well-formed, meaning that the conversion is unambiguous (and
2854 /// that all of the base classes are accessible). Returns true
2855 /// and emits a diagnostic if the code is ill-formed, returns false
2856 /// otherwise. Loc is the location where this routine should point to
2857 /// if there is an error, and Range is the source range to highlight
2858 /// if there is an error.
2859 ///
2860 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2861 /// diagnostic for the respective type of error will be suppressed, but the
2862 /// check for ill-formed code will still be performed.
2863 bool
2864 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2865                                    unsigned InaccessibleBaseID,
2866                                    unsigned AmbiguousBaseConvID,
2867                                    SourceLocation Loc, SourceRange Range,
2868                                    DeclarationName Name,
2869                                    CXXCastPath *BasePath,
2870                                    bool IgnoreAccess) {
2871   // First, determine whether the path from Derived to Base is
2872   // ambiguous. This is slightly more expensive than checking whether
2873   // the Derived to Base conversion exists, because here we need to
2874   // explore multiple paths to determine if there is an ambiguity.
2875   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2876                      /*DetectVirtual=*/false);
2877   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2878   if (!DerivationOkay)
2879     return true;
2880 
2881   const CXXBasePath *Path = nullptr;
2882   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2883     Path = &Paths.front();
2884 
2885   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2886   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2887   // user to access such bases.
2888   if (!Path && getLangOpts().MSVCCompat) {
2889     for (const CXXBasePath &PossiblePath : Paths) {
2890       if (PossiblePath.size() == 1) {
2891         Path = &PossiblePath;
2892         if (AmbiguousBaseConvID)
2893           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2894               << Base << Derived << Range;
2895         break;
2896       }
2897     }
2898   }
2899 
2900   if (Path) {
2901     if (!IgnoreAccess) {
2902       // Check that the base class can be accessed.
2903       switch (
2904           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2905       case AR_inaccessible:
2906         return true;
2907       case AR_accessible:
2908       case AR_dependent:
2909       case AR_delayed:
2910         break;
2911       }
2912     }
2913 
2914     // Build a base path if necessary.
2915     if (BasePath)
2916       ::BuildBasePathArray(*Path, *BasePath);
2917     return false;
2918   }
2919 
2920   if (AmbiguousBaseConvID) {
2921     // We know that the derived-to-base conversion is ambiguous, and
2922     // we're going to produce a diagnostic. Perform the derived-to-base
2923     // search just one more time to compute all of the possible paths so
2924     // that we can print them out. This is more expensive than any of
2925     // the previous derived-to-base checks we've done, but at this point
2926     // performance isn't as much of an issue.
2927     Paths.clear();
2928     Paths.setRecordingPaths(true);
2929     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2930     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2931     (void)StillOkay;
2932 
2933     // Build up a textual representation of the ambiguous paths, e.g.,
2934     // D -> B -> A, that will be used to illustrate the ambiguous
2935     // conversions in the diagnostic. We only print one of the paths
2936     // to each base class subobject.
2937     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2938 
2939     Diag(Loc, AmbiguousBaseConvID)
2940     << Derived << Base << PathDisplayStr << Range << Name;
2941   }
2942   return true;
2943 }
2944 
2945 bool
2946 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2947                                    SourceLocation Loc, SourceRange Range,
2948                                    CXXCastPath *BasePath,
2949                                    bool IgnoreAccess) {
2950   return CheckDerivedToBaseConversion(
2951       Derived, Base, diag::err_upcast_to_inaccessible_base,
2952       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2953       BasePath, IgnoreAccess);
2954 }
2955 
2956 
2957 /// Builds a string representing ambiguous paths from a
2958 /// specific derived class to different subobjects of the same base
2959 /// class.
2960 ///
2961 /// This function builds a string that can be used in error messages
2962 /// to show the different paths that one can take through the
2963 /// inheritance hierarchy to go from the derived class to different
2964 /// subobjects of a base class. The result looks something like this:
2965 /// @code
2966 /// struct D -> struct B -> struct A
2967 /// struct D -> struct C -> struct A
2968 /// @endcode
2969 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2970   std::string PathDisplayStr;
2971   std::set<unsigned> DisplayedPaths;
2972   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2973        Path != Paths.end(); ++Path) {
2974     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2975       // We haven't displayed a path to this particular base
2976       // class subobject yet.
2977       PathDisplayStr += "\n    ";
2978       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2979       for (CXXBasePath::const_iterator Element = Path->begin();
2980            Element != Path->end(); ++Element)
2981         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2982     }
2983   }
2984 
2985   return PathDisplayStr;
2986 }
2987 
2988 //===----------------------------------------------------------------------===//
2989 // C++ class member Handling
2990 //===----------------------------------------------------------------------===//
2991 
2992 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2993 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2994                                 SourceLocation ColonLoc,
2995                                 const ParsedAttributesView &Attrs) {
2996   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2997   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2998                                                   ASLoc, ColonLoc);
2999   CurContext->addHiddenDecl(ASDecl);
3000   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3001 }
3002 
3003 /// CheckOverrideControl - Check C++11 override control semantics.
3004 void Sema::CheckOverrideControl(NamedDecl *D) {
3005   if (D->isInvalidDecl())
3006     return;
3007 
3008   // We only care about "override" and "final" declarations.
3009   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3010     return;
3011 
3012   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3013 
3014   // We can't check dependent instance methods.
3015   if (MD && MD->isInstance() &&
3016       (MD->getParent()->hasAnyDependentBases() ||
3017        MD->getType()->isDependentType()))
3018     return;
3019 
3020   if (MD && !MD->isVirtual()) {
3021     // If we have a non-virtual method, check if if hides a virtual method.
3022     // (In that case, it's most likely the method has the wrong type.)
3023     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3024     FindHiddenVirtualMethods(MD, OverloadedMethods);
3025 
3026     if (!OverloadedMethods.empty()) {
3027       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3028         Diag(OA->getLocation(),
3029              diag::override_keyword_hides_virtual_member_function)
3030           << "override" << (OverloadedMethods.size() > 1);
3031       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3032         Diag(FA->getLocation(),
3033              diag::override_keyword_hides_virtual_member_function)
3034           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3035           << (OverloadedMethods.size() > 1);
3036       }
3037       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3038       MD->setInvalidDecl();
3039       return;
3040     }
3041     // Fall through into the general case diagnostic.
3042     // FIXME: We might want to attempt typo correction here.
3043   }
3044 
3045   if (!MD || !MD->isVirtual()) {
3046     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3047       Diag(OA->getLocation(),
3048            diag::override_keyword_only_allowed_on_virtual_member_functions)
3049         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3050       D->dropAttr<OverrideAttr>();
3051     }
3052     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3053       Diag(FA->getLocation(),
3054            diag::override_keyword_only_allowed_on_virtual_member_functions)
3055         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3056         << FixItHint::CreateRemoval(FA->getLocation());
3057       D->dropAttr<FinalAttr>();
3058     }
3059     return;
3060   }
3061 
3062   // C++11 [class.virtual]p5:
3063   //   If a function is marked with the virt-specifier override and
3064   //   does not override a member function of a base class, the program is
3065   //   ill-formed.
3066   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3067   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3068     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3069       << MD->getDeclName();
3070 }
3071 
3072 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3073   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3074     return;
3075   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3076   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3077     return;
3078 
3079   SourceLocation Loc = MD->getLocation();
3080   SourceLocation SpellingLoc = Loc;
3081   if (getSourceManager().isMacroArgExpansion(Loc))
3082     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3083   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3084   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3085       return;
3086 
3087   if (MD->size_overridden_methods() > 0) {
3088     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3089       unsigned DiagID =
3090           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3091               ? DiagInconsistent
3092               : DiagSuggest;
3093       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3094       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3095       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3096     };
3097     if (isa<CXXDestructorDecl>(MD))
3098       EmitDiag(
3099           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3100           diag::warn_suggest_destructor_marked_not_override_overriding);
3101     else
3102       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3103                diag::warn_suggest_function_marked_not_override_overriding);
3104   }
3105 }
3106 
3107 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3108 /// function overrides a virtual member function marked 'final', according to
3109 /// C++11 [class.virtual]p4.
3110 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3111                                                   const CXXMethodDecl *Old) {
3112   FinalAttr *FA = Old->getAttr<FinalAttr>();
3113   if (!FA)
3114     return false;
3115 
3116   Diag(New->getLocation(), diag::err_final_function_overridden)
3117     << New->getDeclName()
3118     << FA->isSpelledAsSealed();
3119   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3120   return true;
3121 }
3122 
3123 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3124   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3125   // FIXME: Destruction of ObjC lifetime types has side-effects.
3126   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3127     return !RD->isCompleteDefinition() ||
3128            !RD->hasTrivialDefaultConstructor() ||
3129            !RD->hasTrivialDestructor();
3130   return false;
3131 }
3132 
3133 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3134   ParsedAttributesView::const_iterator Itr =
3135       llvm::find_if(list, [](const ParsedAttr &AL) {
3136         return AL.isDeclspecPropertyAttribute();
3137       });
3138   if (Itr != list.end())
3139     return &*Itr;
3140   return nullptr;
3141 }
3142 
3143 // Check if there is a field shadowing.
3144 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3145                                       DeclarationName FieldName,
3146                                       const CXXRecordDecl *RD,
3147                                       bool DeclIsField) {
3148   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3149     return;
3150 
3151   // To record a shadowed field in a base
3152   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3153   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3154                            CXXBasePath &Path) {
3155     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3156     // Record an ambiguous path directly
3157     if (Bases.find(Base) != Bases.end())
3158       return true;
3159     for (const auto Field : Base->lookup(FieldName)) {
3160       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3161           Field->getAccess() != AS_private) {
3162         assert(Field->getAccess() != AS_none);
3163         assert(Bases.find(Base) == Bases.end());
3164         Bases[Base] = Field;
3165         return true;
3166       }
3167     }
3168     return false;
3169   };
3170 
3171   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3172                      /*DetectVirtual=*/true);
3173   if (!RD->lookupInBases(FieldShadowed, Paths))
3174     return;
3175 
3176   for (const auto &P : Paths) {
3177     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3178     auto It = Bases.find(Base);
3179     // Skip duplicated bases
3180     if (It == Bases.end())
3181       continue;
3182     auto BaseField = It->second;
3183     assert(BaseField->getAccess() != AS_private);
3184     if (AS_none !=
3185         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3186       Diag(Loc, diag::warn_shadow_field)
3187         << FieldName << RD << Base << DeclIsField;
3188       Diag(BaseField->getLocation(), diag::note_shadow_field);
3189       Bases.erase(It);
3190     }
3191   }
3192 }
3193 
3194 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3195 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3196 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3197 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3198 /// present (but parsing it has been deferred).
3199 NamedDecl *
3200 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3201                                MultiTemplateParamsArg TemplateParameterLists,
3202                                Expr *BW, const VirtSpecifiers &VS,
3203                                InClassInitStyle InitStyle) {
3204   const DeclSpec &DS = D.getDeclSpec();
3205   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3206   DeclarationName Name = NameInfo.getName();
3207   SourceLocation Loc = NameInfo.getLoc();
3208 
3209   // For anonymous bitfields, the location should point to the type.
3210   if (Loc.isInvalid())
3211     Loc = D.getBeginLoc();
3212 
3213   Expr *BitWidth = static_cast<Expr*>(BW);
3214 
3215   assert(isa<CXXRecordDecl>(CurContext));
3216   assert(!DS.isFriendSpecified());
3217 
3218   bool isFunc = D.isDeclarationOfFunction();
3219   const ParsedAttr *MSPropertyAttr =
3220       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3221 
3222   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3223     // The Microsoft extension __interface only permits public member functions
3224     // and prohibits constructors, destructors, operators, non-public member
3225     // functions, static methods and data members.
3226     unsigned InvalidDecl;
3227     bool ShowDeclName = true;
3228     if (!isFunc &&
3229         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3230       InvalidDecl = 0;
3231     else if (!isFunc)
3232       InvalidDecl = 1;
3233     else if (AS != AS_public)
3234       InvalidDecl = 2;
3235     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3236       InvalidDecl = 3;
3237     else switch (Name.getNameKind()) {
3238       case DeclarationName::CXXConstructorName:
3239         InvalidDecl = 4;
3240         ShowDeclName = false;
3241         break;
3242 
3243       case DeclarationName::CXXDestructorName:
3244         InvalidDecl = 5;
3245         ShowDeclName = false;
3246         break;
3247 
3248       case DeclarationName::CXXOperatorName:
3249       case DeclarationName::CXXConversionFunctionName:
3250         InvalidDecl = 6;
3251         break;
3252 
3253       default:
3254         InvalidDecl = 0;
3255         break;
3256     }
3257 
3258     if (InvalidDecl) {
3259       if (ShowDeclName)
3260         Diag(Loc, diag::err_invalid_member_in_interface)
3261           << (InvalidDecl-1) << Name;
3262       else
3263         Diag(Loc, diag::err_invalid_member_in_interface)
3264           << (InvalidDecl-1) << "";
3265       return nullptr;
3266     }
3267   }
3268 
3269   // C++ 9.2p6: A member shall not be declared to have automatic storage
3270   // duration (auto, register) or with the extern storage-class-specifier.
3271   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3272   // data members and cannot be applied to names declared const or static,
3273   // and cannot be applied to reference members.
3274   switch (DS.getStorageClassSpec()) {
3275   case DeclSpec::SCS_unspecified:
3276   case DeclSpec::SCS_typedef:
3277   case DeclSpec::SCS_static:
3278     break;
3279   case DeclSpec::SCS_mutable:
3280     if (isFunc) {
3281       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3282 
3283       // FIXME: It would be nicer if the keyword was ignored only for this
3284       // declarator. Otherwise we could get follow-up errors.
3285       D.getMutableDeclSpec().ClearStorageClassSpecs();
3286     }
3287     break;
3288   default:
3289     Diag(DS.getStorageClassSpecLoc(),
3290          diag::err_storageclass_invalid_for_member);
3291     D.getMutableDeclSpec().ClearStorageClassSpecs();
3292     break;
3293   }
3294 
3295   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3296                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3297                       !isFunc);
3298 
3299   if (DS.hasConstexprSpecifier() && isInstField) {
3300     SemaDiagnosticBuilder B =
3301         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3302     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3303     if (InitStyle == ICIS_NoInit) {
3304       B << 0 << 0;
3305       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3306         B << FixItHint::CreateRemoval(ConstexprLoc);
3307       else {
3308         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3309         D.getMutableDeclSpec().ClearConstexprSpec();
3310         const char *PrevSpec;
3311         unsigned DiagID;
3312         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3313             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3314         (void)Failed;
3315         assert(!Failed && "Making a constexpr member const shouldn't fail");
3316       }
3317     } else {
3318       B << 1;
3319       const char *PrevSpec;
3320       unsigned DiagID;
3321       if (D.getMutableDeclSpec().SetStorageClassSpec(
3322           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3323           Context.getPrintingPolicy())) {
3324         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3325                "This is the only DeclSpec that should fail to be applied");
3326         B << 1;
3327       } else {
3328         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3329         isInstField = false;
3330       }
3331     }
3332   }
3333 
3334   NamedDecl *Member;
3335   if (isInstField) {
3336     CXXScopeSpec &SS = D.getCXXScopeSpec();
3337 
3338     // Data members must have identifiers for names.
3339     if (!Name.isIdentifier()) {
3340       Diag(Loc, diag::err_bad_variable_name)
3341         << Name;
3342       return nullptr;
3343     }
3344 
3345     IdentifierInfo *II = Name.getAsIdentifierInfo();
3346 
3347     // Member field could not be with "template" keyword.
3348     // So TemplateParameterLists should be empty in this case.
3349     if (TemplateParameterLists.size()) {
3350       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3351       if (TemplateParams->size()) {
3352         // There is no such thing as a member field template.
3353         Diag(D.getIdentifierLoc(), diag::err_template_member)
3354             << II
3355             << SourceRange(TemplateParams->getTemplateLoc(),
3356                 TemplateParams->getRAngleLoc());
3357       } else {
3358         // There is an extraneous 'template<>' for this member.
3359         Diag(TemplateParams->getTemplateLoc(),
3360             diag::err_template_member_noparams)
3361             << II
3362             << SourceRange(TemplateParams->getTemplateLoc(),
3363                 TemplateParams->getRAngleLoc());
3364       }
3365       return nullptr;
3366     }
3367 
3368     if (SS.isSet() && !SS.isInvalid()) {
3369       // The user provided a superfluous scope specifier inside a class
3370       // definition:
3371       //
3372       // class X {
3373       //   int X::member;
3374       // };
3375       if (DeclContext *DC = computeDeclContext(SS, false))
3376         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3377                                      D.getName().getKind() ==
3378                                          UnqualifiedIdKind::IK_TemplateId);
3379       else
3380         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3381           << Name << SS.getRange();
3382 
3383       SS.clear();
3384     }
3385 
3386     if (MSPropertyAttr) {
3387       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3388                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3389       if (!Member)
3390         return nullptr;
3391       isInstField = false;
3392     } else {
3393       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3394                                 BitWidth, InitStyle, AS);
3395       if (!Member)
3396         return nullptr;
3397     }
3398 
3399     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3400   } else {
3401     Member = HandleDeclarator(S, D, TemplateParameterLists);
3402     if (!Member)
3403       return nullptr;
3404 
3405     // Non-instance-fields can't have a bitfield.
3406     if (BitWidth) {
3407       if (Member->isInvalidDecl()) {
3408         // don't emit another diagnostic.
3409       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3410         // C++ 9.6p3: A bit-field shall not be a static member.
3411         // "static member 'A' cannot be a bit-field"
3412         Diag(Loc, diag::err_static_not_bitfield)
3413           << Name << BitWidth->getSourceRange();
3414       } else if (isa<TypedefDecl>(Member)) {
3415         // "typedef member 'x' cannot be a bit-field"
3416         Diag(Loc, diag::err_typedef_not_bitfield)
3417           << Name << BitWidth->getSourceRange();
3418       } else {
3419         // A function typedef ("typedef int f(); f a;").
3420         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3421         Diag(Loc, diag::err_not_integral_type_bitfield)
3422           << Name << cast<ValueDecl>(Member)->getType()
3423           << BitWidth->getSourceRange();
3424       }
3425 
3426       BitWidth = nullptr;
3427       Member->setInvalidDecl();
3428     }
3429 
3430     NamedDecl *NonTemplateMember = Member;
3431     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3432       NonTemplateMember = FunTmpl->getTemplatedDecl();
3433     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3434       NonTemplateMember = VarTmpl->getTemplatedDecl();
3435 
3436     Member->setAccess(AS);
3437 
3438     // If we have declared a member function template or static data member
3439     // template, set the access of the templated declaration as well.
3440     if (NonTemplateMember != Member)
3441       NonTemplateMember->setAccess(AS);
3442 
3443     // C++ [temp.deduct.guide]p3:
3444     //   A deduction guide [...] for a member class template [shall be
3445     //   declared] with the same access [as the template].
3446     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3447       auto *TD = DG->getDeducedTemplate();
3448       // Access specifiers are only meaningful if both the template and the
3449       // deduction guide are from the same scope.
3450       if (AS != TD->getAccess() &&
3451           TD->getDeclContext()->getRedeclContext()->Equals(
3452               DG->getDeclContext()->getRedeclContext())) {
3453         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3454         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3455             << TD->getAccess();
3456         const AccessSpecDecl *LastAccessSpec = nullptr;
3457         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3458           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3459             LastAccessSpec = AccessSpec;
3460         }
3461         assert(LastAccessSpec && "differing access with no access specifier");
3462         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3463             << AS;
3464       }
3465     }
3466   }
3467 
3468   if (VS.isOverrideSpecified())
3469     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3470                                          AttributeCommonInfo::AS_Keyword));
3471   if (VS.isFinalSpecified())
3472     Member->addAttr(FinalAttr::Create(
3473         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3474         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3475 
3476   if (VS.getLastLocation().isValid()) {
3477     // Update the end location of a method that has a virt-specifiers.
3478     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3479       MD->setRangeEnd(VS.getLastLocation());
3480   }
3481 
3482   CheckOverrideControl(Member);
3483 
3484   assert((Name || isInstField) && "No identifier for non-field ?");
3485 
3486   if (isInstField) {
3487     FieldDecl *FD = cast<FieldDecl>(Member);
3488     FieldCollector->Add(FD);
3489 
3490     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3491       // Remember all explicit private FieldDecls that have a name, no side
3492       // effects and are not part of a dependent type declaration.
3493       if (!FD->isImplicit() && FD->getDeclName() &&
3494           FD->getAccess() == AS_private &&
3495           !FD->hasAttr<UnusedAttr>() &&
3496           !FD->getParent()->isDependentContext() &&
3497           !InitializationHasSideEffects(*FD))
3498         UnusedPrivateFields.insert(FD);
3499     }
3500   }
3501 
3502   return Member;
3503 }
3504 
3505 namespace {
3506   class UninitializedFieldVisitor
3507       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3508     Sema &S;
3509     // List of Decls to generate a warning on.  Also remove Decls that become
3510     // initialized.
3511     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3512     // List of base classes of the record.  Classes are removed after their
3513     // initializers.
3514     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3515     // Vector of decls to be removed from the Decl set prior to visiting the
3516     // nodes.  These Decls may have been initialized in the prior initializer.
3517     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3518     // If non-null, add a note to the warning pointing back to the constructor.
3519     const CXXConstructorDecl *Constructor;
3520     // Variables to hold state when processing an initializer list.  When
3521     // InitList is true, special case initialization of FieldDecls matching
3522     // InitListFieldDecl.
3523     bool InitList;
3524     FieldDecl *InitListFieldDecl;
3525     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3526 
3527   public:
3528     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3529     UninitializedFieldVisitor(Sema &S,
3530                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3531                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3532       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3533         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3534 
3535     // Returns true if the use of ME is not an uninitialized use.
3536     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3537                                          bool CheckReferenceOnly) {
3538       llvm::SmallVector<FieldDecl*, 4> Fields;
3539       bool ReferenceField = false;
3540       while (ME) {
3541         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3542         if (!FD)
3543           return false;
3544         Fields.push_back(FD);
3545         if (FD->getType()->isReferenceType())
3546           ReferenceField = true;
3547         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3548       }
3549 
3550       // Binding a reference to an uninitialized field is not an
3551       // uninitialized use.
3552       if (CheckReferenceOnly && !ReferenceField)
3553         return true;
3554 
3555       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3556       // Discard the first field since it is the field decl that is being
3557       // initialized.
3558       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3559         UsedFieldIndex.push_back((*I)->getFieldIndex());
3560       }
3561 
3562       for (auto UsedIter = UsedFieldIndex.begin(),
3563                 UsedEnd = UsedFieldIndex.end(),
3564                 OrigIter = InitFieldIndex.begin(),
3565                 OrigEnd = InitFieldIndex.end();
3566            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3567         if (*UsedIter < *OrigIter)
3568           return true;
3569         if (*UsedIter > *OrigIter)
3570           break;
3571       }
3572 
3573       return false;
3574     }
3575 
3576     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3577                           bool AddressOf) {
3578       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3579         return;
3580 
3581       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3582       // or union.
3583       MemberExpr *FieldME = ME;
3584 
3585       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3586 
3587       Expr *Base = ME;
3588       while (MemberExpr *SubME =
3589                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3590 
3591         if (isa<VarDecl>(SubME->getMemberDecl()))
3592           return;
3593 
3594         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3595           if (!FD->isAnonymousStructOrUnion())
3596             FieldME = SubME;
3597 
3598         if (!FieldME->getType().isPODType(S.Context))
3599           AllPODFields = false;
3600 
3601         Base = SubME->getBase();
3602       }
3603 
3604       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3605         Visit(Base);
3606         return;
3607       }
3608 
3609       if (AddressOf && AllPODFields)
3610         return;
3611 
3612       ValueDecl* FoundVD = FieldME->getMemberDecl();
3613 
3614       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3615         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3616           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3617         }
3618 
3619         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3620           QualType T = BaseCast->getType();
3621           if (T->isPointerType() &&
3622               BaseClasses.count(T->getPointeeType())) {
3623             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3624                 << T->getPointeeType() << FoundVD;
3625           }
3626         }
3627       }
3628 
3629       if (!Decls.count(FoundVD))
3630         return;
3631 
3632       const bool IsReference = FoundVD->getType()->isReferenceType();
3633 
3634       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3635         // Special checking for initializer lists.
3636         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3637           return;
3638         }
3639       } else {
3640         // Prevent double warnings on use of unbounded references.
3641         if (CheckReferenceOnly && !IsReference)
3642           return;
3643       }
3644 
3645       unsigned diag = IsReference
3646           ? diag::warn_reference_field_is_uninit
3647           : diag::warn_field_is_uninit;
3648       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3649       if (Constructor)
3650         S.Diag(Constructor->getLocation(),
3651                diag::note_uninit_in_this_constructor)
3652           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3653 
3654     }
3655 
3656     void HandleValue(Expr *E, bool AddressOf) {
3657       E = E->IgnoreParens();
3658 
3659       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3660         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3661                          AddressOf /*AddressOf*/);
3662         return;
3663       }
3664 
3665       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3666         Visit(CO->getCond());
3667         HandleValue(CO->getTrueExpr(), AddressOf);
3668         HandleValue(CO->getFalseExpr(), AddressOf);
3669         return;
3670       }
3671 
3672       if (BinaryConditionalOperator *BCO =
3673               dyn_cast<BinaryConditionalOperator>(E)) {
3674         Visit(BCO->getCond());
3675         HandleValue(BCO->getFalseExpr(), AddressOf);
3676         return;
3677       }
3678 
3679       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3680         HandleValue(OVE->getSourceExpr(), AddressOf);
3681         return;
3682       }
3683 
3684       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3685         switch (BO->getOpcode()) {
3686         default:
3687           break;
3688         case(BO_PtrMemD):
3689         case(BO_PtrMemI):
3690           HandleValue(BO->getLHS(), AddressOf);
3691           Visit(BO->getRHS());
3692           return;
3693         case(BO_Comma):
3694           Visit(BO->getLHS());
3695           HandleValue(BO->getRHS(), AddressOf);
3696           return;
3697         }
3698       }
3699 
3700       Visit(E);
3701     }
3702 
3703     void CheckInitListExpr(InitListExpr *ILE) {
3704       InitFieldIndex.push_back(0);
3705       for (auto Child : ILE->children()) {
3706         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3707           CheckInitListExpr(SubList);
3708         } else {
3709           Visit(Child);
3710         }
3711         ++InitFieldIndex.back();
3712       }
3713       InitFieldIndex.pop_back();
3714     }
3715 
3716     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3717                           FieldDecl *Field, const Type *BaseClass) {
3718       // Remove Decls that may have been initialized in the previous
3719       // initializer.
3720       for (ValueDecl* VD : DeclsToRemove)
3721         Decls.erase(VD);
3722       DeclsToRemove.clear();
3723 
3724       Constructor = FieldConstructor;
3725       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3726 
3727       if (ILE && Field) {
3728         InitList = true;
3729         InitListFieldDecl = Field;
3730         InitFieldIndex.clear();
3731         CheckInitListExpr(ILE);
3732       } else {
3733         InitList = false;
3734         Visit(E);
3735       }
3736 
3737       if (Field)
3738         Decls.erase(Field);
3739       if (BaseClass)
3740         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3741     }
3742 
3743     void VisitMemberExpr(MemberExpr *ME) {
3744       // All uses of unbounded reference fields will warn.
3745       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3746     }
3747 
3748     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3749       if (E->getCastKind() == CK_LValueToRValue) {
3750         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3751         return;
3752       }
3753 
3754       Inherited::VisitImplicitCastExpr(E);
3755     }
3756 
3757     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3758       if (E->getConstructor()->isCopyConstructor()) {
3759         Expr *ArgExpr = E->getArg(0);
3760         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3761           if (ILE->getNumInits() == 1)
3762             ArgExpr = ILE->getInit(0);
3763         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3764           if (ICE->getCastKind() == CK_NoOp)
3765             ArgExpr = ICE->getSubExpr();
3766         HandleValue(ArgExpr, false /*AddressOf*/);
3767         return;
3768       }
3769       Inherited::VisitCXXConstructExpr(E);
3770     }
3771 
3772     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3773       Expr *Callee = E->getCallee();
3774       if (isa<MemberExpr>(Callee)) {
3775         HandleValue(Callee, false /*AddressOf*/);
3776         for (auto Arg : E->arguments())
3777           Visit(Arg);
3778         return;
3779       }
3780 
3781       Inherited::VisitCXXMemberCallExpr(E);
3782     }
3783 
3784     void VisitCallExpr(CallExpr *E) {
3785       // Treat std::move as a use.
3786       if (E->isCallToStdMove()) {
3787         HandleValue(E->getArg(0), /*AddressOf=*/false);
3788         return;
3789       }
3790 
3791       Inherited::VisitCallExpr(E);
3792     }
3793 
3794     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3795       Expr *Callee = E->getCallee();
3796 
3797       if (isa<UnresolvedLookupExpr>(Callee))
3798         return Inherited::VisitCXXOperatorCallExpr(E);
3799 
3800       Visit(Callee);
3801       for (auto Arg : E->arguments())
3802         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3803     }
3804 
3805     void VisitBinaryOperator(BinaryOperator *E) {
3806       // If a field assignment is detected, remove the field from the
3807       // uninitiailized field set.
3808       if (E->getOpcode() == BO_Assign)
3809         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3810           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3811             if (!FD->getType()->isReferenceType())
3812               DeclsToRemove.push_back(FD);
3813 
3814       if (E->isCompoundAssignmentOp()) {
3815         HandleValue(E->getLHS(), false /*AddressOf*/);
3816         Visit(E->getRHS());
3817         return;
3818       }
3819 
3820       Inherited::VisitBinaryOperator(E);
3821     }
3822 
3823     void VisitUnaryOperator(UnaryOperator *E) {
3824       if (E->isIncrementDecrementOp()) {
3825         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3826         return;
3827       }
3828       if (E->getOpcode() == UO_AddrOf) {
3829         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3830           HandleValue(ME->getBase(), true /*AddressOf*/);
3831           return;
3832         }
3833       }
3834 
3835       Inherited::VisitUnaryOperator(E);
3836     }
3837   };
3838 
3839   // Diagnose value-uses of fields to initialize themselves, e.g.
3840   //   foo(foo)
3841   // where foo is not also a parameter to the constructor.
3842   // Also diagnose across field uninitialized use such as
3843   //   x(y), y(x)
3844   // TODO: implement -Wuninitialized and fold this into that framework.
3845   static void DiagnoseUninitializedFields(
3846       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3847 
3848     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3849                                            Constructor->getLocation())) {
3850       return;
3851     }
3852 
3853     if (Constructor->isInvalidDecl())
3854       return;
3855 
3856     const CXXRecordDecl *RD = Constructor->getParent();
3857 
3858     if (RD->isDependentContext())
3859       return;
3860 
3861     // Holds fields that are uninitialized.
3862     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3863 
3864     // At the beginning, all fields are uninitialized.
3865     for (auto *I : RD->decls()) {
3866       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3867         UninitializedFields.insert(FD);
3868       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3869         UninitializedFields.insert(IFD->getAnonField());
3870       }
3871     }
3872 
3873     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3874     for (auto I : RD->bases())
3875       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3876 
3877     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3878       return;
3879 
3880     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3881                                                    UninitializedFields,
3882                                                    UninitializedBaseClasses);
3883 
3884     for (const auto *FieldInit : Constructor->inits()) {
3885       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3886         break;
3887 
3888       Expr *InitExpr = FieldInit->getInit();
3889       if (!InitExpr)
3890         continue;
3891 
3892       if (CXXDefaultInitExpr *Default =
3893               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3894         InitExpr = Default->getExpr();
3895         if (!InitExpr)
3896           continue;
3897         // In class initializers will point to the constructor.
3898         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3899                                               FieldInit->getAnyMember(),
3900                                               FieldInit->getBaseClass());
3901       } else {
3902         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3903                                               FieldInit->getAnyMember(),
3904                                               FieldInit->getBaseClass());
3905       }
3906     }
3907   }
3908 } // namespace
3909 
3910 /// Enter a new C++ default initializer scope. After calling this, the
3911 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3912 /// parsing or instantiating the initializer failed.
3913 void Sema::ActOnStartCXXInClassMemberInitializer() {
3914   // Create a synthetic function scope to represent the call to the constructor
3915   // that notionally surrounds a use of this initializer.
3916   PushFunctionScope();
3917 }
3918 
3919 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3920   if (!D.isFunctionDeclarator())
3921     return;
3922   auto &FTI = D.getFunctionTypeInfo();
3923   if (!FTI.Params)
3924     return;
3925   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3926                                                           FTI.NumParams)) {
3927     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3928     if (ParamDecl->getDeclName())
3929       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3930   }
3931 }
3932 
3933 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3934   if (ConstraintExpr.isInvalid())
3935     return ExprError();
3936   return CorrectDelayedTyposInExpr(ConstraintExpr);
3937 }
3938 
3939 /// This is invoked after parsing an in-class initializer for a
3940 /// non-static C++ class member, and after instantiating an in-class initializer
3941 /// in a class template. Such actions are deferred until the class is complete.
3942 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3943                                                   SourceLocation InitLoc,
3944                                                   Expr *InitExpr) {
3945   // Pop the notional constructor scope we created earlier.
3946   PopFunctionScopeInfo(nullptr, D);
3947 
3948   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3949   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3950          "must set init style when field is created");
3951 
3952   if (!InitExpr) {
3953     D->setInvalidDecl();
3954     if (FD)
3955       FD->removeInClassInitializer();
3956     return;
3957   }
3958 
3959   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3960     FD->setInvalidDecl();
3961     FD->removeInClassInitializer();
3962     return;
3963   }
3964 
3965   ExprResult Init = InitExpr;
3966   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3967     InitializedEntity Entity =
3968         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3969     InitializationKind Kind =
3970         FD->getInClassInitStyle() == ICIS_ListInit
3971             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3972                                                    InitExpr->getBeginLoc(),
3973                                                    InitExpr->getEndLoc())
3974             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3975     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3976     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3977     if (Init.isInvalid()) {
3978       FD->setInvalidDecl();
3979       return;
3980     }
3981   }
3982 
3983   // C++11 [class.base.init]p7:
3984   //   The initialization of each base and member constitutes a
3985   //   full-expression.
3986   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3987   if (Init.isInvalid()) {
3988     FD->setInvalidDecl();
3989     return;
3990   }
3991 
3992   InitExpr = Init.get();
3993 
3994   FD->setInClassInitializer(InitExpr);
3995 }
3996 
3997 /// Find the direct and/or virtual base specifiers that
3998 /// correspond to the given base type, for use in base initialization
3999 /// within a constructor.
4000 static bool FindBaseInitializer(Sema &SemaRef,
4001                                 CXXRecordDecl *ClassDecl,
4002                                 QualType BaseType,
4003                                 const CXXBaseSpecifier *&DirectBaseSpec,
4004                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4005   // First, check for a direct base class.
4006   DirectBaseSpec = nullptr;
4007   for (const auto &Base : ClassDecl->bases()) {
4008     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4009       // We found a direct base of this type. That's what we're
4010       // initializing.
4011       DirectBaseSpec = &Base;
4012       break;
4013     }
4014   }
4015 
4016   // Check for a virtual base class.
4017   // FIXME: We might be able to short-circuit this if we know in advance that
4018   // there are no virtual bases.
4019   VirtualBaseSpec = nullptr;
4020   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4021     // We haven't found a base yet; search the class hierarchy for a
4022     // virtual base class.
4023     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4024                        /*DetectVirtual=*/false);
4025     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4026                               SemaRef.Context.getTypeDeclType(ClassDecl),
4027                               BaseType, Paths)) {
4028       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4029            Path != Paths.end(); ++Path) {
4030         if (Path->back().Base->isVirtual()) {
4031           VirtualBaseSpec = Path->back().Base;
4032           break;
4033         }
4034       }
4035     }
4036   }
4037 
4038   return DirectBaseSpec || VirtualBaseSpec;
4039 }
4040 
4041 /// Handle a C++ member initializer using braced-init-list syntax.
4042 MemInitResult
4043 Sema::ActOnMemInitializer(Decl *ConstructorD,
4044                           Scope *S,
4045                           CXXScopeSpec &SS,
4046                           IdentifierInfo *MemberOrBase,
4047                           ParsedType TemplateTypeTy,
4048                           const DeclSpec &DS,
4049                           SourceLocation IdLoc,
4050                           Expr *InitList,
4051                           SourceLocation EllipsisLoc) {
4052   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4053                              DS, IdLoc, InitList,
4054                              EllipsisLoc);
4055 }
4056 
4057 /// Handle a C++ member initializer using parentheses syntax.
4058 MemInitResult
4059 Sema::ActOnMemInitializer(Decl *ConstructorD,
4060                           Scope *S,
4061                           CXXScopeSpec &SS,
4062                           IdentifierInfo *MemberOrBase,
4063                           ParsedType TemplateTypeTy,
4064                           const DeclSpec &DS,
4065                           SourceLocation IdLoc,
4066                           SourceLocation LParenLoc,
4067                           ArrayRef<Expr *> Args,
4068                           SourceLocation RParenLoc,
4069                           SourceLocation EllipsisLoc) {
4070   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4071   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4072                              DS, IdLoc, List, EllipsisLoc);
4073 }
4074 
4075 namespace {
4076 
4077 // Callback to only accept typo corrections that can be a valid C++ member
4078 // intializer: either a non-static field member or a base class.
4079 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4080 public:
4081   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4082       : ClassDecl(ClassDecl) {}
4083 
4084   bool ValidateCandidate(const TypoCorrection &candidate) override {
4085     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4086       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4087         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4088       return isa<TypeDecl>(ND);
4089     }
4090     return false;
4091   }
4092 
4093   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4094     return std::make_unique<MemInitializerValidatorCCC>(*this);
4095   }
4096 
4097 private:
4098   CXXRecordDecl *ClassDecl;
4099 };
4100 
4101 }
4102 
4103 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4104                                              CXXScopeSpec &SS,
4105                                              ParsedType TemplateTypeTy,
4106                                              IdentifierInfo *MemberOrBase) {
4107   if (SS.getScopeRep() || TemplateTypeTy)
4108     return nullptr;
4109   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4110   if (Result.empty())
4111     return nullptr;
4112   ValueDecl *Member;
4113   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4114       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4115     return Member;
4116   return nullptr;
4117 }
4118 
4119 /// Handle a C++ member initializer.
4120 MemInitResult
4121 Sema::BuildMemInitializer(Decl *ConstructorD,
4122                           Scope *S,
4123                           CXXScopeSpec &SS,
4124                           IdentifierInfo *MemberOrBase,
4125                           ParsedType TemplateTypeTy,
4126                           const DeclSpec &DS,
4127                           SourceLocation IdLoc,
4128                           Expr *Init,
4129                           SourceLocation EllipsisLoc) {
4130   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4131   if (!Res.isUsable())
4132     return true;
4133   Init = Res.get();
4134 
4135   if (!ConstructorD)
4136     return true;
4137 
4138   AdjustDeclIfTemplate(ConstructorD);
4139 
4140   CXXConstructorDecl *Constructor
4141     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4142   if (!Constructor) {
4143     // The user wrote a constructor initializer on a function that is
4144     // not a C++ constructor. Ignore the error for now, because we may
4145     // have more member initializers coming; we'll diagnose it just
4146     // once in ActOnMemInitializers.
4147     return true;
4148   }
4149 
4150   CXXRecordDecl *ClassDecl = Constructor->getParent();
4151 
4152   // C++ [class.base.init]p2:
4153   //   Names in a mem-initializer-id are looked up in the scope of the
4154   //   constructor's class and, if not found in that scope, are looked
4155   //   up in the scope containing the constructor's definition.
4156   //   [Note: if the constructor's class contains a member with the
4157   //   same name as a direct or virtual base class of the class, a
4158   //   mem-initializer-id naming the member or base class and composed
4159   //   of a single identifier refers to the class member. A
4160   //   mem-initializer-id for the hidden base class may be specified
4161   //   using a qualified name. ]
4162 
4163   // Look for a member, first.
4164   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4165           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4166     if (EllipsisLoc.isValid())
4167       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4168           << MemberOrBase
4169           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4170 
4171     return BuildMemberInitializer(Member, Init, IdLoc);
4172   }
4173   // It didn't name a member, so see if it names a class.
4174   QualType BaseType;
4175   TypeSourceInfo *TInfo = nullptr;
4176 
4177   if (TemplateTypeTy) {
4178     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4179     if (BaseType.isNull())
4180       return true;
4181   } else if (DS.getTypeSpecType() == TST_decltype) {
4182     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4183   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4184     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4185     return true;
4186   } else {
4187     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4188     LookupParsedName(R, S, &SS);
4189 
4190     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4191     if (!TyD) {
4192       if (R.isAmbiguous()) return true;
4193 
4194       // We don't want access-control diagnostics here.
4195       R.suppressDiagnostics();
4196 
4197       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4198         bool NotUnknownSpecialization = false;
4199         DeclContext *DC = computeDeclContext(SS, false);
4200         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4201           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4202 
4203         if (!NotUnknownSpecialization) {
4204           // When the scope specifier can refer to a member of an unknown
4205           // specialization, we take it as a type name.
4206           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4207                                        SS.getWithLocInContext(Context),
4208                                        *MemberOrBase, IdLoc);
4209           if (BaseType.isNull())
4210             return true;
4211 
4212           TInfo = Context.CreateTypeSourceInfo(BaseType);
4213           DependentNameTypeLoc TL =
4214               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4215           if (!TL.isNull()) {
4216             TL.setNameLoc(IdLoc);
4217             TL.setElaboratedKeywordLoc(SourceLocation());
4218             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4219           }
4220 
4221           R.clear();
4222           R.setLookupName(MemberOrBase);
4223         }
4224       }
4225 
4226       // If no results were found, try to correct typos.
4227       TypoCorrection Corr;
4228       MemInitializerValidatorCCC CCC(ClassDecl);
4229       if (R.empty() && BaseType.isNull() &&
4230           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4231                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4232         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4233           // We have found a non-static data member with a similar
4234           // name to what was typed; complain and initialize that
4235           // member.
4236           diagnoseTypo(Corr,
4237                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4238                          << MemberOrBase << true);
4239           return BuildMemberInitializer(Member, Init, IdLoc);
4240         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4241           const CXXBaseSpecifier *DirectBaseSpec;
4242           const CXXBaseSpecifier *VirtualBaseSpec;
4243           if (FindBaseInitializer(*this, ClassDecl,
4244                                   Context.getTypeDeclType(Type),
4245                                   DirectBaseSpec, VirtualBaseSpec)) {
4246             // We have found a direct or virtual base class with a
4247             // similar name to what was typed; complain and initialize
4248             // that base class.
4249             diagnoseTypo(Corr,
4250                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4251                            << MemberOrBase << false,
4252                          PDiag() /*Suppress note, we provide our own.*/);
4253 
4254             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4255                                                               : VirtualBaseSpec;
4256             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4257                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4258 
4259             TyD = Type;
4260           }
4261         }
4262       }
4263 
4264       if (!TyD && BaseType.isNull()) {
4265         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4266           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4267         return true;
4268       }
4269     }
4270 
4271     if (BaseType.isNull()) {
4272       BaseType = Context.getTypeDeclType(TyD);
4273       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4274       if (SS.isSet()) {
4275         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4276                                              BaseType);
4277         TInfo = Context.CreateTypeSourceInfo(BaseType);
4278         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4279         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4280         TL.setElaboratedKeywordLoc(SourceLocation());
4281         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4282       }
4283     }
4284   }
4285 
4286   if (!TInfo)
4287     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4288 
4289   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4290 }
4291 
4292 MemInitResult
4293 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4294                              SourceLocation IdLoc) {
4295   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4296   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4297   assert((DirectMember || IndirectMember) &&
4298          "Member must be a FieldDecl or IndirectFieldDecl");
4299 
4300   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4301     return true;
4302 
4303   if (Member->isInvalidDecl())
4304     return true;
4305 
4306   MultiExprArg Args;
4307   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4308     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4309   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4310     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4311   } else {
4312     // Template instantiation doesn't reconstruct ParenListExprs for us.
4313     Args = Init;
4314   }
4315 
4316   SourceRange InitRange = Init->getSourceRange();
4317 
4318   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4319     // Can't check initialization for a member of dependent type or when
4320     // any of the arguments are type-dependent expressions.
4321     DiscardCleanupsInEvaluationContext();
4322   } else {
4323     bool InitList = false;
4324     if (isa<InitListExpr>(Init)) {
4325       InitList = true;
4326       Args = Init;
4327     }
4328 
4329     // Initialize the member.
4330     InitializedEntity MemberEntity =
4331       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4332                    : InitializedEntity::InitializeMember(IndirectMember,
4333                                                          nullptr);
4334     InitializationKind Kind =
4335         InitList ? InitializationKind::CreateDirectList(
4336                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4337                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4338                                                     InitRange.getEnd());
4339 
4340     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4341     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4342                                             nullptr);
4343     if (MemberInit.isInvalid())
4344       return true;
4345 
4346     // C++11 [class.base.init]p7:
4347     //   The initialization of each base and member constitutes a
4348     //   full-expression.
4349     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4350                                      /*DiscardedValue*/ false);
4351     if (MemberInit.isInvalid())
4352       return true;
4353 
4354     Init = MemberInit.get();
4355   }
4356 
4357   if (DirectMember) {
4358     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4359                                             InitRange.getBegin(), Init,
4360                                             InitRange.getEnd());
4361   } else {
4362     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4363                                             InitRange.getBegin(), Init,
4364                                             InitRange.getEnd());
4365   }
4366 }
4367 
4368 MemInitResult
4369 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4370                                  CXXRecordDecl *ClassDecl) {
4371   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4372   if (!LangOpts.CPlusPlus11)
4373     return Diag(NameLoc, diag::err_delegating_ctor)
4374       << TInfo->getTypeLoc().getLocalSourceRange();
4375   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4376 
4377   bool InitList = true;
4378   MultiExprArg Args = Init;
4379   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4380     InitList = false;
4381     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4382   }
4383 
4384   SourceRange InitRange = Init->getSourceRange();
4385   // Initialize the object.
4386   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4387                                      QualType(ClassDecl->getTypeForDecl(), 0));
4388   InitializationKind Kind =
4389       InitList ? InitializationKind::CreateDirectList(
4390                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4391                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4392                                                   InitRange.getEnd());
4393   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4394   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4395                                               Args, nullptr);
4396   if (DelegationInit.isInvalid())
4397     return true;
4398 
4399   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4400          "Delegating constructor with no target?");
4401 
4402   // C++11 [class.base.init]p7:
4403   //   The initialization of each base and member constitutes a
4404   //   full-expression.
4405   DelegationInit = ActOnFinishFullExpr(
4406       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4407   if (DelegationInit.isInvalid())
4408     return true;
4409 
4410   // If we are in a dependent context, template instantiation will
4411   // perform this type-checking again. Just save the arguments that we
4412   // received in a ParenListExpr.
4413   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4414   // of the information that we have about the base
4415   // initializer. However, deconstructing the ASTs is a dicey process,
4416   // and this approach is far more likely to get the corner cases right.
4417   if (CurContext->isDependentContext())
4418     DelegationInit = Init;
4419 
4420   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4421                                           DelegationInit.getAs<Expr>(),
4422                                           InitRange.getEnd());
4423 }
4424 
4425 MemInitResult
4426 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4427                            Expr *Init, CXXRecordDecl *ClassDecl,
4428                            SourceLocation EllipsisLoc) {
4429   SourceLocation BaseLoc
4430     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4431 
4432   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4433     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4434              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4435 
4436   // C++ [class.base.init]p2:
4437   //   [...] Unless the mem-initializer-id names a nonstatic data
4438   //   member of the constructor's class or a direct or virtual base
4439   //   of that class, the mem-initializer is ill-formed. A
4440   //   mem-initializer-list can initialize a base class using any
4441   //   name that denotes that base class type.
4442   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4443 
4444   SourceRange InitRange = Init->getSourceRange();
4445   if (EllipsisLoc.isValid()) {
4446     // This is a pack expansion.
4447     if (!BaseType->containsUnexpandedParameterPack())  {
4448       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4449         << SourceRange(BaseLoc, InitRange.getEnd());
4450 
4451       EllipsisLoc = SourceLocation();
4452     }
4453   } else {
4454     // Check for any unexpanded parameter packs.
4455     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4456       return true;
4457 
4458     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4459       return true;
4460   }
4461 
4462   // Check for direct and virtual base classes.
4463   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4464   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4465   if (!Dependent) {
4466     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4467                                        BaseType))
4468       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4469 
4470     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4471                         VirtualBaseSpec);
4472 
4473     // C++ [base.class.init]p2:
4474     // Unless the mem-initializer-id names a nonstatic data member of the
4475     // constructor's class or a direct or virtual base of that class, the
4476     // mem-initializer is ill-formed.
4477     if (!DirectBaseSpec && !VirtualBaseSpec) {
4478       // If the class has any dependent bases, then it's possible that
4479       // one of those types will resolve to the same type as
4480       // BaseType. Therefore, just treat this as a dependent base
4481       // class initialization.  FIXME: Should we try to check the
4482       // initialization anyway? It seems odd.
4483       if (ClassDecl->hasAnyDependentBases())
4484         Dependent = true;
4485       else
4486         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4487           << BaseType << Context.getTypeDeclType(ClassDecl)
4488           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4489     }
4490   }
4491 
4492   if (Dependent) {
4493     DiscardCleanupsInEvaluationContext();
4494 
4495     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4496                                             /*IsVirtual=*/false,
4497                                             InitRange.getBegin(), Init,
4498                                             InitRange.getEnd(), EllipsisLoc);
4499   }
4500 
4501   // C++ [base.class.init]p2:
4502   //   If a mem-initializer-id is ambiguous because it designates both
4503   //   a direct non-virtual base class and an inherited virtual base
4504   //   class, the mem-initializer is ill-formed.
4505   if (DirectBaseSpec && VirtualBaseSpec)
4506     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4507       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4508 
4509   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4510   if (!BaseSpec)
4511     BaseSpec = VirtualBaseSpec;
4512 
4513   // Initialize the base.
4514   bool InitList = true;
4515   MultiExprArg Args = Init;
4516   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4517     InitList = false;
4518     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4519   }
4520 
4521   InitializedEntity BaseEntity =
4522     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4523   InitializationKind Kind =
4524       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4525                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4526                                                   InitRange.getEnd());
4527   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4528   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4529   if (BaseInit.isInvalid())
4530     return true;
4531 
4532   // C++11 [class.base.init]p7:
4533   //   The initialization of each base and member constitutes a
4534   //   full-expression.
4535   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4536                                  /*DiscardedValue*/ false);
4537   if (BaseInit.isInvalid())
4538     return true;
4539 
4540   // If we are in a dependent context, template instantiation will
4541   // perform this type-checking again. Just save the arguments that we
4542   // received in a ParenListExpr.
4543   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4544   // of the information that we have about the base
4545   // initializer. However, deconstructing the ASTs is a dicey process,
4546   // and this approach is far more likely to get the corner cases right.
4547   if (CurContext->isDependentContext())
4548     BaseInit = Init;
4549 
4550   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4551                                           BaseSpec->isVirtual(),
4552                                           InitRange.getBegin(),
4553                                           BaseInit.getAs<Expr>(),
4554                                           InitRange.getEnd(), EllipsisLoc);
4555 }
4556 
4557 // Create a static_cast\<T&&>(expr).
4558 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4559   if (T.isNull()) T = E->getType();
4560   QualType TargetType = SemaRef.BuildReferenceType(
4561       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4562   SourceLocation ExprLoc = E->getBeginLoc();
4563   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4564       TargetType, ExprLoc);
4565 
4566   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4567                                    SourceRange(ExprLoc, ExprLoc),
4568                                    E->getSourceRange()).get();
4569 }
4570 
4571 /// ImplicitInitializerKind - How an implicit base or member initializer should
4572 /// initialize its base or member.
4573 enum ImplicitInitializerKind {
4574   IIK_Default,
4575   IIK_Copy,
4576   IIK_Move,
4577   IIK_Inherit
4578 };
4579 
4580 static bool
4581 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4582                              ImplicitInitializerKind ImplicitInitKind,
4583                              CXXBaseSpecifier *BaseSpec,
4584                              bool IsInheritedVirtualBase,
4585                              CXXCtorInitializer *&CXXBaseInit) {
4586   InitializedEntity InitEntity
4587     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4588                                         IsInheritedVirtualBase);
4589 
4590   ExprResult BaseInit;
4591 
4592   switch (ImplicitInitKind) {
4593   case IIK_Inherit:
4594   case IIK_Default: {
4595     InitializationKind InitKind
4596       = InitializationKind::CreateDefault(Constructor->getLocation());
4597     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4598     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4599     break;
4600   }
4601 
4602   case IIK_Move:
4603   case IIK_Copy: {
4604     bool Moving = ImplicitInitKind == IIK_Move;
4605     ParmVarDecl *Param = Constructor->getParamDecl(0);
4606     QualType ParamType = Param->getType().getNonReferenceType();
4607 
4608     Expr *CopyCtorArg =
4609       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4610                           SourceLocation(), Param, false,
4611                           Constructor->getLocation(), ParamType,
4612                           VK_LValue, nullptr);
4613 
4614     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4615 
4616     // Cast to the base class to avoid ambiguities.
4617     QualType ArgTy =
4618       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4619                                        ParamType.getQualifiers());
4620 
4621     if (Moving) {
4622       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4623     }
4624 
4625     CXXCastPath BasePath;
4626     BasePath.push_back(BaseSpec);
4627     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4628                                             CK_UncheckedDerivedToBase,
4629                                             Moving ? VK_XValue : VK_LValue,
4630                                             &BasePath).get();
4631 
4632     InitializationKind InitKind
4633       = InitializationKind::CreateDirect(Constructor->getLocation(),
4634                                          SourceLocation(), SourceLocation());
4635     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4636     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4637     break;
4638   }
4639   }
4640 
4641   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4642   if (BaseInit.isInvalid())
4643     return true;
4644 
4645   CXXBaseInit =
4646     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4647                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4648                                                         SourceLocation()),
4649                                              BaseSpec->isVirtual(),
4650                                              SourceLocation(),
4651                                              BaseInit.getAs<Expr>(),
4652                                              SourceLocation(),
4653                                              SourceLocation());
4654 
4655   return false;
4656 }
4657 
4658 static bool RefersToRValueRef(Expr *MemRef) {
4659   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4660   return Referenced->getType()->isRValueReferenceType();
4661 }
4662 
4663 static bool
4664 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4665                                ImplicitInitializerKind ImplicitInitKind,
4666                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4667                                CXXCtorInitializer *&CXXMemberInit) {
4668   if (Field->isInvalidDecl())
4669     return true;
4670 
4671   SourceLocation Loc = Constructor->getLocation();
4672 
4673   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4674     bool Moving = ImplicitInitKind == IIK_Move;
4675     ParmVarDecl *Param = Constructor->getParamDecl(0);
4676     QualType ParamType = Param->getType().getNonReferenceType();
4677 
4678     // Suppress copying zero-width bitfields.
4679     if (Field->isZeroLengthBitField(SemaRef.Context))
4680       return false;
4681 
4682     Expr *MemberExprBase =
4683       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4684                           SourceLocation(), Param, false,
4685                           Loc, ParamType, VK_LValue, nullptr);
4686 
4687     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4688 
4689     if (Moving) {
4690       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4691     }
4692 
4693     // Build a reference to this field within the parameter.
4694     CXXScopeSpec SS;
4695     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4696                               Sema::LookupMemberName);
4697     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4698                                   : cast<ValueDecl>(Field), AS_public);
4699     MemberLookup.resolveKind();
4700     ExprResult CtorArg
4701       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4702                                          ParamType, Loc,
4703                                          /*IsArrow=*/false,
4704                                          SS,
4705                                          /*TemplateKWLoc=*/SourceLocation(),
4706                                          /*FirstQualifierInScope=*/nullptr,
4707                                          MemberLookup,
4708                                          /*TemplateArgs=*/nullptr,
4709                                          /*S*/nullptr);
4710     if (CtorArg.isInvalid())
4711       return true;
4712 
4713     // C++11 [class.copy]p15:
4714     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4715     //     with static_cast<T&&>(x.m);
4716     if (RefersToRValueRef(CtorArg.get())) {
4717       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4718     }
4719 
4720     InitializedEntity Entity =
4721         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4722                                                        /*Implicit*/ true)
4723                  : InitializedEntity::InitializeMember(Field, nullptr,
4724                                                        /*Implicit*/ true);
4725 
4726     // Direct-initialize to use the copy constructor.
4727     InitializationKind InitKind =
4728       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4729 
4730     Expr *CtorArgE = CtorArg.getAs<Expr>();
4731     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4732     ExprResult MemberInit =
4733         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4734     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4735     if (MemberInit.isInvalid())
4736       return true;
4737 
4738     if (Indirect)
4739       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4740           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4741     else
4742       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4743           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4744     return false;
4745   }
4746 
4747   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4748          "Unhandled implicit init kind!");
4749 
4750   QualType FieldBaseElementType =
4751     SemaRef.Context.getBaseElementType(Field->getType());
4752 
4753   if (FieldBaseElementType->isRecordType()) {
4754     InitializedEntity InitEntity =
4755         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4756                                                        /*Implicit*/ true)
4757                  : InitializedEntity::InitializeMember(Field, nullptr,
4758                                                        /*Implicit*/ true);
4759     InitializationKind InitKind =
4760       InitializationKind::CreateDefault(Loc);
4761 
4762     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4763     ExprResult MemberInit =
4764       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4765 
4766     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4767     if (MemberInit.isInvalid())
4768       return true;
4769 
4770     if (Indirect)
4771       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4772                                                                Indirect, Loc,
4773                                                                Loc,
4774                                                                MemberInit.get(),
4775                                                                Loc);
4776     else
4777       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4778                                                                Field, Loc, Loc,
4779                                                                MemberInit.get(),
4780                                                                Loc);
4781     return false;
4782   }
4783 
4784   if (!Field->getParent()->isUnion()) {
4785     if (FieldBaseElementType->isReferenceType()) {
4786       SemaRef.Diag(Constructor->getLocation(),
4787                    diag::err_uninitialized_member_in_ctor)
4788       << (int)Constructor->isImplicit()
4789       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4790       << 0 << Field->getDeclName();
4791       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4792       return true;
4793     }
4794 
4795     if (FieldBaseElementType.isConstQualified()) {
4796       SemaRef.Diag(Constructor->getLocation(),
4797                    diag::err_uninitialized_member_in_ctor)
4798       << (int)Constructor->isImplicit()
4799       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4800       << 1 << Field->getDeclName();
4801       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4802       return true;
4803     }
4804   }
4805 
4806   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4807     // ARC and Weak:
4808     //   Default-initialize Objective-C pointers to NULL.
4809     CXXMemberInit
4810       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4811                                                  Loc, Loc,
4812                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4813                                                  Loc);
4814     return false;
4815   }
4816 
4817   // Nothing to initialize.
4818   CXXMemberInit = nullptr;
4819   return false;
4820 }
4821 
4822 namespace {
4823 struct BaseAndFieldInfo {
4824   Sema &S;
4825   CXXConstructorDecl *Ctor;
4826   bool AnyErrorsInInits;
4827   ImplicitInitializerKind IIK;
4828   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4829   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4830   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4831 
4832   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4833     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4834     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4835     if (Ctor->getInheritedConstructor())
4836       IIK = IIK_Inherit;
4837     else if (Generated && Ctor->isCopyConstructor())
4838       IIK = IIK_Copy;
4839     else if (Generated && Ctor->isMoveConstructor())
4840       IIK = IIK_Move;
4841     else
4842       IIK = IIK_Default;
4843   }
4844 
4845   bool isImplicitCopyOrMove() const {
4846     switch (IIK) {
4847     case IIK_Copy:
4848     case IIK_Move:
4849       return true;
4850 
4851     case IIK_Default:
4852     case IIK_Inherit:
4853       return false;
4854     }
4855 
4856     llvm_unreachable("Invalid ImplicitInitializerKind!");
4857   }
4858 
4859   bool addFieldInitializer(CXXCtorInitializer *Init) {
4860     AllToInit.push_back(Init);
4861 
4862     // Check whether this initializer makes the field "used".
4863     if (Init->getInit()->HasSideEffects(S.Context))
4864       S.UnusedPrivateFields.remove(Init->getAnyMember());
4865 
4866     return false;
4867   }
4868 
4869   bool isInactiveUnionMember(FieldDecl *Field) {
4870     RecordDecl *Record = Field->getParent();
4871     if (!Record->isUnion())
4872       return false;
4873 
4874     if (FieldDecl *Active =
4875             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4876       return Active != Field->getCanonicalDecl();
4877 
4878     // In an implicit copy or move constructor, ignore any in-class initializer.
4879     if (isImplicitCopyOrMove())
4880       return true;
4881 
4882     // If there's no explicit initialization, the field is active only if it
4883     // has an in-class initializer...
4884     if (Field->hasInClassInitializer())
4885       return false;
4886     // ... or it's an anonymous struct or union whose class has an in-class
4887     // initializer.
4888     if (!Field->isAnonymousStructOrUnion())
4889       return true;
4890     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4891     return !FieldRD->hasInClassInitializer();
4892   }
4893 
4894   /// Determine whether the given field is, or is within, a union member
4895   /// that is inactive (because there was an initializer given for a different
4896   /// member of the union, or because the union was not initialized at all).
4897   bool isWithinInactiveUnionMember(FieldDecl *Field,
4898                                    IndirectFieldDecl *Indirect) {
4899     if (!Indirect)
4900       return isInactiveUnionMember(Field);
4901 
4902     for (auto *C : Indirect->chain()) {
4903       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4904       if (Field && isInactiveUnionMember(Field))
4905         return true;
4906     }
4907     return false;
4908   }
4909 };
4910 }
4911 
4912 /// Determine whether the given type is an incomplete or zero-lenfgth
4913 /// array type.
4914 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4915   if (T->isIncompleteArrayType())
4916     return true;
4917 
4918   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4919     if (!ArrayT->getSize())
4920       return true;
4921 
4922     T = ArrayT->getElementType();
4923   }
4924 
4925   return false;
4926 }
4927 
4928 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4929                                     FieldDecl *Field,
4930                                     IndirectFieldDecl *Indirect = nullptr) {
4931   if (Field->isInvalidDecl())
4932     return false;
4933 
4934   // Overwhelmingly common case: we have a direct initializer for this field.
4935   if (CXXCtorInitializer *Init =
4936           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4937     return Info.addFieldInitializer(Init);
4938 
4939   // C++11 [class.base.init]p8:
4940   //   if the entity is a non-static data member that has a
4941   //   brace-or-equal-initializer and either
4942   //   -- the constructor's class is a union and no other variant member of that
4943   //      union is designated by a mem-initializer-id or
4944   //   -- the constructor's class is not a union, and, if the entity is a member
4945   //      of an anonymous union, no other member of that union is designated by
4946   //      a mem-initializer-id,
4947   //   the entity is initialized as specified in [dcl.init].
4948   //
4949   // We also apply the same rules to handle anonymous structs within anonymous
4950   // unions.
4951   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4952     return false;
4953 
4954   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4955     ExprResult DIE =
4956         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4957     if (DIE.isInvalid())
4958       return true;
4959 
4960     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4961     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4962 
4963     CXXCtorInitializer *Init;
4964     if (Indirect)
4965       Init = new (SemaRef.Context)
4966           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4967                              SourceLocation(), DIE.get(), SourceLocation());
4968     else
4969       Init = new (SemaRef.Context)
4970           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4971                              SourceLocation(), DIE.get(), SourceLocation());
4972     return Info.addFieldInitializer(Init);
4973   }
4974 
4975   // Don't initialize incomplete or zero-length arrays.
4976   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4977     return false;
4978 
4979   // Don't try to build an implicit initializer if there were semantic
4980   // errors in any of the initializers (and therefore we might be
4981   // missing some that the user actually wrote).
4982   if (Info.AnyErrorsInInits)
4983     return false;
4984 
4985   CXXCtorInitializer *Init = nullptr;
4986   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4987                                      Indirect, Init))
4988     return true;
4989 
4990   if (!Init)
4991     return false;
4992 
4993   return Info.addFieldInitializer(Init);
4994 }
4995 
4996 bool
4997 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4998                                CXXCtorInitializer *Initializer) {
4999   assert(Initializer->isDelegatingInitializer());
5000   Constructor->setNumCtorInitializers(1);
5001   CXXCtorInitializer **initializer =
5002     new (Context) CXXCtorInitializer*[1];
5003   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5004   Constructor->setCtorInitializers(initializer);
5005 
5006   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5007     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5008     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5009   }
5010 
5011   DelegatingCtorDecls.push_back(Constructor);
5012 
5013   DiagnoseUninitializedFields(*this, Constructor);
5014 
5015   return false;
5016 }
5017 
5018 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5019                                ArrayRef<CXXCtorInitializer *> Initializers) {
5020   if (Constructor->isDependentContext()) {
5021     // Just store the initializers as written, they will be checked during
5022     // instantiation.
5023     if (!Initializers.empty()) {
5024       Constructor->setNumCtorInitializers(Initializers.size());
5025       CXXCtorInitializer **baseOrMemberInitializers =
5026         new (Context) CXXCtorInitializer*[Initializers.size()];
5027       memcpy(baseOrMemberInitializers, Initializers.data(),
5028              Initializers.size() * sizeof(CXXCtorInitializer*));
5029       Constructor->setCtorInitializers(baseOrMemberInitializers);
5030     }
5031 
5032     // Let template instantiation know whether we had errors.
5033     if (AnyErrors)
5034       Constructor->setInvalidDecl();
5035 
5036     return false;
5037   }
5038 
5039   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5040 
5041   // We need to build the initializer AST according to order of construction
5042   // and not what user specified in the Initializers list.
5043   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5044   if (!ClassDecl)
5045     return true;
5046 
5047   bool HadError = false;
5048 
5049   for (unsigned i = 0; i < Initializers.size(); i++) {
5050     CXXCtorInitializer *Member = Initializers[i];
5051 
5052     if (Member->isBaseInitializer())
5053       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5054     else {
5055       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5056 
5057       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5058         for (auto *C : F->chain()) {
5059           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5060           if (FD && FD->getParent()->isUnion())
5061             Info.ActiveUnionMember.insert(std::make_pair(
5062                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5063         }
5064       } else if (FieldDecl *FD = Member->getMember()) {
5065         if (FD->getParent()->isUnion())
5066           Info.ActiveUnionMember.insert(std::make_pair(
5067               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5068       }
5069     }
5070   }
5071 
5072   // Keep track of the direct virtual bases.
5073   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5074   for (auto &I : ClassDecl->bases()) {
5075     if (I.isVirtual())
5076       DirectVBases.insert(&I);
5077   }
5078 
5079   // Push virtual bases before others.
5080   for (auto &VBase : ClassDecl->vbases()) {
5081     if (CXXCtorInitializer *Value
5082         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5083       // [class.base.init]p7, per DR257:
5084       //   A mem-initializer where the mem-initializer-id names a virtual base
5085       //   class is ignored during execution of a constructor of any class that
5086       //   is not the most derived class.
5087       if (ClassDecl->isAbstract()) {
5088         // FIXME: Provide a fixit to remove the base specifier. This requires
5089         // tracking the location of the associated comma for a base specifier.
5090         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5091           << VBase.getType() << ClassDecl;
5092         DiagnoseAbstractType(ClassDecl);
5093       }
5094 
5095       Info.AllToInit.push_back(Value);
5096     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5097       // [class.base.init]p8, per DR257:
5098       //   If a given [...] base class is not named by a mem-initializer-id
5099       //   [...] and the entity is not a virtual base class of an abstract
5100       //   class, then [...] the entity is default-initialized.
5101       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5102       CXXCtorInitializer *CXXBaseInit;
5103       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5104                                        &VBase, IsInheritedVirtualBase,
5105                                        CXXBaseInit)) {
5106         HadError = true;
5107         continue;
5108       }
5109 
5110       Info.AllToInit.push_back(CXXBaseInit);
5111     }
5112   }
5113 
5114   // Non-virtual bases.
5115   for (auto &Base : ClassDecl->bases()) {
5116     // Virtuals are in the virtual base list and already constructed.
5117     if (Base.isVirtual())
5118       continue;
5119 
5120     if (CXXCtorInitializer *Value
5121           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5122       Info.AllToInit.push_back(Value);
5123     } else if (!AnyErrors) {
5124       CXXCtorInitializer *CXXBaseInit;
5125       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5126                                        &Base, /*IsInheritedVirtualBase=*/false,
5127                                        CXXBaseInit)) {
5128         HadError = true;
5129         continue;
5130       }
5131 
5132       Info.AllToInit.push_back(CXXBaseInit);
5133     }
5134   }
5135 
5136   // Fields.
5137   for (auto *Mem : ClassDecl->decls()) {
5138     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5139       // C++ [class.bit]p2:
5140       //   A declaration for a bit-field that omits the identifier declares an
5141       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5142       //   initialized.
5143       if (F->isUnnamedBitfield())
5144         continue;
5145 
5146       // If we're not generating the implicit copy/move constructor, then we'll
5147       // handle anonymous struct/union fields based on their individual
5148       // indirect fields.
5149       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5150         continue;
5151 
5152       if (CollectFieldInitializer(*this, Info, F))
5153         HadError = true;
5154       continue;
5155     }
5156 
5157     // Beyond this point, we only consider default initialization.
5158     if (Info.isImplicitCopyOrMove())
5159       continue;
5160 
5161     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5162       if (F->getType()->isIncompleteArrayType()) {
5163         assert(ClassDecl->hasFlexibleArrayMember() &&
5164                "Incomplete array type is not valid");
5165         continue;
5166       }
5167 
5168       // Initialize each field of an anonymous struct individually.
5169       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5170         HadError = true;
5171 
5172       continue;
5173     }
5174   }
5175 
5176   unsigned NumInitializers = Info.AllToInit.size();
5177   if (NumInitializers > 0) {
5178     Constructor->setNumCtorInitializers(NumInitializers);
5179     CXXCtorInitializer **baseOrMemberInitializers =
5180       new (Context) CXXCtorInitializer*[NumInitializers];
5181     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5182            NumInitializers * sizeof(CXXCtorInitializer*));
5183     Constructor->setCtorInitializers(baseOrMemberInitializers);
5184 
5185     // Constructors implicitly reference the base and member
5186     // destructors.
5187     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5188                                            Constructor->getParent());
5189   }
5190 
5191   return HadError;
5192 }
5193 
5194 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5195   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5196     const RecordDecl *RD = RT->getDecl();
5197     if (RD->isAnonymousStructOrUnion()) {
5198       for (auto *Field : RD->fields())
5199         PopulateKeysForFields(Field, IdealInits);
5200       return;
5201     }
5202   }
5203   IdealInits.push_back(Field->getCanonicalDecl());
5204 }
5205 
5206 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5207   return Context.getCanonicalType(BaseType).getTypePtr();
5208 }
5209 
5210 static const void *GetKeyForMember(ASTContext &Context,
5211                                    CXXCtorInitializer *Member) {
5212   if (!Member->isAnyMemberInitializer())
5213     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5214 
5215   return Member->getAnyMember()->getCanonicalDecl();
5216 }
5217 
5218 static void DiagnoseBaseOrMemInitializerOrder(
5219     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5220     ArrayRef<CXXCtorInitializer *> Inits) {
5221   if (Constructor->getDeclContext()->isDependentContext())
5222     return;
5223 
5224   // Don't check initializers order unless the warning is enabled at the
5225   // location of at least one initializer.
5226   bool ShouldCheckOrder = false;
5227   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5228     CXXCtorInitializer *Init = Inits[InitIndex];
5229     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5230                                  Init->getSourceLocation())) {
5231       ShouldCheckOrder = true;
5232       break;
5233     }
5234   }
5235   if (!ShouldCheckOrder)
5236     return;
5237 
5238   // Build the list of bases and members in the order that they'll
5239   // actually be initialized.  The explicit initializers should be in
5240   // this same order but may be missing things.
5241   SmallVector<const void*, 32> IdealInitKeys;
5242 
5243   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5244 
5245   // 1. Virtual bases.
5246   for (const auto &VBase : ClassDecl->vbases())
5247     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5248 
5249   // 2. Non-virtual bases.
5250   for (const auto &Base : ClassDecl->bases()) {
5251     if (Base.isVirtual())
5252       continue;
5253     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5254   }
5255 
5256   // 3. Direct fields.
5257   for (auto *Field : ClassDecl->fields()) {
5258     if (Field->isUnnamedBitfield())
5259       continue;
5260 
5261     PopulateKeysForFields(Field, IdealInitKeys);
5262   }
5263 
5264   unsigned NumIdealInits = IdealInitKeys.size();
5265   unsigned IdealIndex = 0;
5266 
5267   CXXCtorInitializer *PrevInit = nullptr;
5268   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5269     CXXCtorInitializer *Init = Inits[InitIndex];
5270     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5271 
5272     // Scan forward to try to find this initializer in the idealized
5273     // initializers list.
5274     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5275       if (InitKey == IdealInitKeys[IdealIndex])
5276         break;
5277 
5278     // If we didn't find this initializer, it must be because we
5279     // scanned past it on a previous iteration.  That can only
5280     // happen if we're out of order;  emit a warning.
5281     if (IdealIndex == NumIdealInits && PrevInit) {
5282       Sema::SemaDiagnosticBuilder D =
5283         SemaRef.Diag(PrevInit->getSourceLocation(),
5284                      diag::warn_initializer_out_of_order);
5285 
5286       if (PrevInit->isAnyMemberInitializer())
5287         D << 0 << PrevInit->getAnyMember()->getDeclName();
5288       else
5289         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5290 
5291       if (Init->isAnyMemberInitializer())
5292         D << 0 << Init->getAnyMember()->getDeclName();
5293       else
5294         D << 1 << Init->getTypeSourceInfo()->getType();
5295 
5296       // Move back to the initializer's location in the ideal list.
5297       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5298         if (InitKey == IdealInitKeys[IdealIndex])
5299           break;
5300 
5301       assert(IdealIndex < NumIdealInits &&
5302              "initializer not found in initializer list");
5303     }
5304 
5305     PrevInit = Init;
5306   }
5307 }
5308 
5309 namespace {
5310 bool CheckRedundantInit(Sema &S,
5311                         CXXCtorInitializer *Init,
5312                         CXXCtorInitializer *&PrevInit) {
5313   if (!PrevInit) {
5314     PrevInit = Init;
5315     return false;
5316   }
5317 
5318   if (FieldDecl *Field = Init->getAnyMember())
5319     S.Diag(Init->getSourceLocation(),
5320            diag::err_multiple_mem_initialization)
5321       << Field->getDeclName()
5322       << Init->getSourceRange();
5323   else {
5324     const Type *BaseClass = Init->getBaseClass();
5325     assert(BaseClass && "neither field nor base");
5326     S.Diag(Init->getSourceLocation(),
5327            diag::err_multiple_base_initialization)
5328       << QualType(BaseClass, 0)
5329       << Init->getSourceRange();
5330   }
5331   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5332     << 0 << PrevInit->getSourceRange();
5333 
5334   return true;
5335 }
5336 
5337 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5338 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5339 
5340 bool CheckRedundantUnionInit(Sema &S,
5341                              CXXCtorInitializer *Init,
5342                              RedundantUnionMap &Unions) {
5343   FieldDecl *Field = Init->getAnyMember();
5344   RecordDecl *Parent = Field->getParent();
5345   NamedDecl *Child = Field;
5346 
5347   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5348     if (Parent->isUnion()) {
5349       UnionEntry &En = Unions[Parent];
5350       if (En.first && En.first != Child) {
5351         S.Diag(Init->getSourceLocation(),
5352                diag::err_multiple_mem_union_initialization)
5353           << Field->getDeclName()
5354           << Init->getSourceRange();
5355         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5356           << 0 << En.second->getSourceRange();
5357         return true;
5358       }
5359       if (!En.first) {
5360         En.first = Child;
5361         En.second = Init;
5362       }
5363       if (!Parent->isAnonymousStructOrUnion())
5364         return false;
5365     }
5366 
5367     Child = Parent;
5368     Parent = cast<RecordDecl>(Parent->getDeclContext());
5369   }
5370 
5371   return false;
5372 }
5373 }
5374 
5375 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5376 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5377                                 SourceLocation ColonLoc,
5378                                 ArrayRef<CXXCtorInitializer*> MemInits,
5379                                 bool AnyErrors) {
5380   if (!ConstructorDecl)
5381     return;
5382 
5383   AdjustDeclIfTemplate(ConstructorDecl);
5384 
5385   CXXConstructorDecl *Constructor
5386     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5387 
5388   if (!Constructor) {
5389     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5390     return;
5391   }
5392 
5393   // Mapping for the duplicate initializers check.
5394   // For member initializers, this is keyed with a FieldDecl*.
5395   // For base initializers, this is keyed with a Type*.
5396   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5397 
5398   // Mapping for the inconsistent anonymous-union initializers check.
5399   RedundantUnionMap MemberUnions;
5400 
5401   bool HadError = false;
5402   for (unsigned i = 0; i < MemInits.size(); i++) {
5403     CXXCtorInitializer *Init = MemInits[i];
5404 
5405     // Set the source order index.
5406     Init->setSourceOrder(i);
5407 
5408     if (Init->isAnyMemberInitializer()) {
5409       const void *Key = GetKeyForMember(Context, Init);
5410       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5411           CheckRedundantUnionInit(*this, Init, MemberUnions))
5412         HadError = true;
5413     } else if (Init->isBaseInitializer()) {
5414       const void *Key = GetKeyForMember(Context, Init);
5415       if (CheckRedundantInit(*this, Init, Members[Key]))
5416         HadError = true;
5417     } else {
5418       assert(Init->isDelegatingInitializer());
5419       // This must be the only initializer
5420       if (MemInits.size() != 1) {
5421         Diag(Init->getSourceLocation(),
5422              diag::err_delegating_initializer_alone)
5423           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5424         // We will treat this as being the only initializer.
5425       }
5426       SetDelegatingInitializer(Constructor, MemInits[i]);
5427       // Return immediately as the initializer is set.
5428       return;
5429     }
5430   }
5431 
5432   if (HadError)
5433     return;
5434 
5435   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5436 
5437   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5438 
5439   DiagnoseUninitializedFields(*this, Constructor);
5440 }
5441 
5442 void
5443 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5444                                              CXXRecordDecl *ClassDecl) {
5445   // Ignore dependent contexts. Also ignore unions, since their members never
5446   // have destructors implicitly called.
5447   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5448     return;
5449 
5450   // FIXME: all the access-control diagnostics are positioned on the
5451   // field/base declaration.  That's probably good; that said, the
5452   // user might reasonably want to know why the destructor is being
5453   // emitted, and we currently don't say.
5454 
5455   // Non-static data members.
5456   for (auto *Field : ClassDecl->fields()) {
5457     if (Field->isInvalidDecl())
5458       continue;
5459 
5460     // Don't destroy incomplete or zero-length arrays.
5461     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5462       continue;
5463 
5464     QualType FieldType = Context.getBaseElementType(Field->getType());
5465 
5466     const RecordType* RT = FieldType->getAs<RecordType>();
5467     if (!RT)
5468       continue;
5469 
5470     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5471     if (FieldClassDecl->isInvalidDecl())
5472       continue;
5473     if (FieldClassDecl->hasIrrelevantDestructor())
5474       continue;
5475     // The destructor for an implicit anonymous union member is never invoked.
5476     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5477       continue;
5478 
5479     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5480     assert(Dtor && "No dtor found for FieldClassDecl!");
5481     CheckDestructorAccess(Field->getLocation(), Dtor,
5482                           PDiag(diag::err_access_dtor_field)
5483                             << Field->getDeclName()
5484                             << FieldType);
5485 
5486     MarkFunctionReferenced(Location, Dtor);
5487     DiagnoseUseOfDecl(Dtor, Location);
5488   }
5489 
5490   // We only potentially invoke the destructors of potentially constructed
5491   // subobjects.
5492   bool VisitVirtualBases = !ClassDecl->isAbstract();
5493 
5494   // If the destructor exists and has already been marked used in the MS ABI,
5495   // then virtual base destructors have already been checked and marked used.
5496   // Skip checking them again to avoid duplicate diagnostics.
5497   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5498     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5499     if (Dtor && Dtor->isUsed())
5500       VisitVirtualBases = false;
5501   }
5502 
5503   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5504 
5505   // Bases.
5506   for (const auto &Base : ClassDecl->bases()) {
5507     // Bases are always records in a well-formed non-dependent class.
5508     const RecordType *RT = Base.getType()->getAs<RecordType>();
5509 
5510     // Remember direct virtual bases.
5511     if (Base.isVirtual()) {
5512       if (!VisitVirtualBases)
5513         continue;
5514       DirectVirtualBases.insert(RT);
5515     }
5516 
5517     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5518     // If our base class is invalid, we probably can't get its dtor anyway.
5519     if (BaseClassDecl->isInvalidDecl())
5520       continue;
5521     if (BaseClassDecl->hasIrrelevantDestructor())
5522       continue;
5523 
5524     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5525     assert(Dtor && "No dtor found for BaseClassDecl!");
5526 
5527     // FIXME: caret should be on the start of the class name
5528     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5529                           PDiag(diag::err_access_dtor_base)
5530                               << Base.getType() << Base.getSourceRange(),
5531                           Context.getTypeDeclType(ClassDecl));
5532 
5533     MarkFunctionReferenced(Location, Dtor);
5534     DiagnoseUseOfDecl(Dtor, Location);
5535   }
5536 
5537   if (VisitVirtualBases)
5538     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5539                                          &DirectVirtualBases);
5540 }
5541 
5542 void Sema::MarkVirtualBaseDestructorsReferenced(
5543     SourceLocation Location, CXXRecordDecl *ClassDecl,
5544     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5545   // Virtual bases.
5546   for (const auto &VBase : ClassDecl->vbases()) {
5547     // Bases are always records in a well-formed non-dependent class.
5548     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5549 
5550     // Ignore already visited direct virtual bases.
5551     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5552       continue;
5553 
5554     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5555     // If our base class is invalid, we probably can't get its dtor anyway.
5556     if (BaseClassDecl->isInvalidDecl())
5557       continue;
5558     if (BaseClassDecl->hasIrrelevantDestructor())
5559       continue;
5560 
5561     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5562     assert(Dtor && "No dtor found for BaseClassDecl!");
5563     if (CheckDestructorAccess(
5564             ClassDecl->getLocation(), Dtor,
5565             PDiag(diag::err_access_dtor_vbase)
5566                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5567             Context.getTypeDeclType(ClassDecl)) ==
5568         AR_accessible) {
5569       CheckDerivedToBaseConversion(
5570           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5571           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5572           SourceRange(), DeclarationName(), nullptr);
5573     }
5574 
5575     MarkFunctionReferenced(Location, Dtor);
5576     DiagnoseUseOfDecl(Dtor, Location);
5577   }
5578 }
5579 
5580 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5581   if (!CDtorDecl)
5582     return;
5583 
5584   if (CXXConstructorDecl *Constructor
5585       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5586     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5587     DiagnoseUninitializedFields(*this, Constructor);
5588   }
5589 }
5590 
5591 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5592   if (!getLangOpts().CPlusPlus)
5593     return false;
5594 
5595   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5596   if (!RD)
5597     return false;
5598 
5599   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5600   // class template specialization here, but doing so breaks a lot of code.
5601 
5602   // We can't answer whether something is abstract until it has a
5603   // definition. If it's currently being defined, we'll walk back
5604   // over all the declarations when we have a full definition.
5605   const CXXRecordDecl *Def = RD->getDefinition();
5606   if (!Def || Def->isBeingDefined())
5607     return false;
5608 
5609   return RD->isAbstract();
5610 }
5611 
5612 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5613                                   TypeDiagnoser &Diagnoser) {
5614   if (!isAbstractType(Loc, T))
5615     return false;
5616 
5617   T = Context.getBaseElementType(T);
5618   Diagnoser.diagnose(*this, Loc, T);
5619   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5620   return true;
5621 }
5622 
5623 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5624   // Check if we've already emitted the list of pure virtual functions
5625   // for this class.
5626   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5627     return;
5628 
5629   // If the diagnostic is suppressed, don't emit the notes. We're only
5630   // going to emit them once, so try to attach them to a diagnostic we're
5631   // actually going to show.
5632   if (Diags.isLastDiagnosticIgnored())
5633     return;
5634 
5635   CXXFinalOverriderMap FinalOverriders;
5636   RD->getFinalOverriders(FinalOverriders);
5637 
5638   // Keep a set of seen pure methods so we won't diagnose the same method
5639   // more than once.
5640   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5641 
5642   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5643                                    MEnd = FinalOverriders.end();
5644        M != MEnd;
5645        ++M) {
5646     for (OverridingMethods::iterator SO = M->second.begin(),
5647                                   SOEnd = M->second.end();
5648          SO != SOEnd; ++SO) {
5649       // C++ [class.abstract]p4:
5650       //   A class is abstract if it contains or inherits at least one
5651       //   pure virtual function for which the final overrider is pure
5652       //   virtual.
5653 
5654       //
5655       if (SO->second.size() != 1)
5656         continue;
5657 
5658       if (!SO->second.front().Method->isPure())
5659         continue;
5660 
5661       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5662         continue;
5663 
5664       Diag(SO->second.front().Method->getLocation(),
5665            diag::note_pure_virtual_function)
5666         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5667     }
5668   }
5669 
5670   if (!PureVirtualClassDiagSet)
5671     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5672   PureVirtualClassDiagSet->insert(RD);
5673 }
5674 
5675 namespace {
5676 struct AbstractUsageInfo {
5677   Sema &S;
5678   CXXRecordDecl *Record;
5679   CanQualType AbstractType;
5680   bool Invalid;
5681 
5682   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5683     : S(S), Record(Record),
5684       AbstractType(S.Context.getCanonicalType(
5685                    S.Context.getTypeDeclType(Record))),
5686       Invalid(false) {}
5687 
5688   void DiagnoseAbstractType() {
5689     if (Invalid) return;
5690     S.DiagnoseAbstractType(Record);
5691     Invalid = true;
5692   }
5693 
5694   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5695 };
5696 
5697 struct CheckAbstractUsage {
5698   AbstractUsageInfo &Info;
5699   const NamedDecl *Ctx;
5700 
5701   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5702     : Info(Info), Ctx(Ctx) {}
5703 
5704   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5705     switch (TL.getTypeLocClass()) {
5706 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5707 #define TYPELOC(CLASS, PARENT) \
5708     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5709 #include "clang/AST/TypeLocNodes.def"
5710     }
5711   }
5712 
5713   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5714     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5715     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5716       if (!TL.getParam(I))
5717         continue;
5718 
5719       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5720       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5721     }
5722   }
5723 
5724   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5725     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5726   }
5727 
5728   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5729     // Visit the type parameters from a permissive context.
5730     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5731       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5732       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5733         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5734           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5735       // TODO: other template argument types?
5736     }
5737   }
5738 
5739   // Visit pointee types from a permissive context.
5740 #define CheckPolymorphic(Type) \
5741   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5742     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5743   }
5744   CheckPolymorphic(PointerTypeLoc)
5745   CheckPolymorphic(ReferenceTypeLoc)
5746   CheckPolymorphic(MemberPointerTypeLoc)
5747   CheckPolymorphic(BlockPointerTypeLoc)
5748   CheckPolymorphic(AtomicTypeLoc)
5749 
5750   /// Handle all the types we haven't given a more specific
5751   /// implementation for above.
5752   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5753     // Every other kind of type that we haven't called out already
5754     // that has an inner type is either (1) sugar or (2) contains that
5755     // inner type in some way as a subobject.
5756     if (TypeLoc Next = TL.getNextTypeLoc())
5757       return Visit(Next, Sel);
5758 
5759     // If there's no inner type and we're in a permissive context,
5760     // don't diagnose.
5761     if (Sel == Sema::AbstractNone) return;
5762 
5763     // Check whether the type matches the abstract type.
5764     QualType T = TL.getType();
5765     if (T->isArrayType()) {
5766       Sel = Sema::AbstractArrayType;
5767       T = Info.S.Context.getBaseElementType(T);
5768     }
5769     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5770     if (CT != Info.AbstractType) return;
5771 
5772     // It matched; do some magic.
5773     if (Sel == Sema::AbstractArrayType) {
5774       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5775         << T << TL.getSourceRange();
5776     } else {
5777       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5778         << Sel << T << TL.getSourceRange();
5779     }
5780     Info.DiagnoseAbstractType();
5781   }
5782 };
5783 
5784 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5785                                   Sema::AbstractDiagSelID Sel) {
5786   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5787 }
5788 
5789 }
5790 
5791 /// Check for invalid uses of an abstract type in a method declaration.
5792 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5793                                     CXXMethodDecl *MD) {
5794   // No need to do the check on definitions, which require that
5795   // the return/param types be complete.
5796   if (MD->doesThisDeclarationHaveABody())
5797     return;
5798 
5799   // For safety's sake, just ignore it if we don't have type source
5800   // information.  This should never happen for non-implicit methods,
5801   // but...
5802   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5803     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5804 }
5805 
5806 /// Check for invalid uses of an abstract type within a class definition.
5807 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5808                                     CXXRecordDecl *RD) {
5809   for (auto *D : RD->decls()) {
5810     if (D->isImplicit()) continue;
5811 
5812     // Methods and method templates.
5813     if (isa<CXXMethodDecl>(D)) {
5814       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5815     } else if (isa<FunctionTemplateDecl>(D)) {
5816       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5817       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5818 
5819     // Fields and static variables.
5820     } else if (isa<FieldDecl>(D)) {
5821       FieldDecl *FD = cast<FieldDecl>(D);
5822       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5823         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5824     } else if (isa<VarDecl>(D)) {
5825       VarDecl *VD = cast<VarDecl>(D);
5826       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5827         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5828 
5829     // Nested classes and class templates.
5830     } else if (isa<CXXRecordDecl>(D)) {
5831       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5832     } else if (isa<ClassTemplateDecl>(D)) {
5833       CheckAbstractClassUsage(Info,
5834                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5835     }
5836   }
5837 }
5838 
5839 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5840   Attr *ClassAttr = getDLLAttr(Class);
5841   if (!ClassAttr)
5842     return;
5843 
5844   assert(ClassAttr->getKind() == attr::DLLExport);
5845 
5846   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5847 
5848   if (TSK == TSK_ExplicitInstantiationDeclaration)
5849     // Don't go any further if this is just an explicit instantiation
5850     // declaration.
5851     return;
5852 
5853   // Add a context note to explain how we got to any diagnostics produced below.
5854   struct MarkingClassDllexported {
5855     Sema &S;
5856     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5857                             SourceLocation AttrLoc)
5858         : S(S) {
5859       Sema::CodeSynthesisContext Ctx;
5860       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5861       Ctx.PointOfInstantiation = AttrLoc;
5862       Ctx.Entity = Class;
5863       S.pushCodeSynthesisContext(Ctx);
5864     }
5865     ~MarkingClassDllexported() {
5866       S.popCodeSynthesisContext();
5867     }
5868   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5869 
5870   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5871     S.MarkVTableUsed(Class->getLocation(), Class, true);
5872 
5873   for (Decl *Member : Class->decls()) {
5874     // Defined static variables that are members of an exported base
5875     // class must be marked export too.
5876     auto *VD = dyn_cast<VarDecl>(Member);
5877     if (VD && Member->getAttr<DLLExportAttr>() &&
5878         VD->getStorageClass() == SC_Static &&
5879         TSK == TSK_ImplicitInstantiation)
5880       S.MarkVariableReferenced(VD->getLocation(), VD);
5881 
5882     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5883     if (!MD)
5884       continue;
5885 
5886     if (Member->getAttr<DLLExportAttr>()) {
5887       if (MD->isUserProvided()) {
5888         // Instantiate non-default class member functions ...
5889 
5890         // .. except for certain kinds of template specializations.
5891         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5892           continue;
5893 
5894         S.MarkFunctionReferenced(Class->getLocation(), MD);
5895 
5896         // The function will be passed to the consumer when its definition is
5897         // encountered.
5898       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5899                  MD->isCopyAssignmentOperator() ||
5900                  MD->isMoveAssignmentOperator()) {
5901         // Synthesize and instantiate non-trivial implicit methods, explicitly
5902         // defaulted methods, and the copy and move assignment operators. The
5903         // latter are exported even if they are trivial, because the address of
5904         // an operator can be taken and should compare equal across libraries.
5905         S.MarkFunctionReferenced(Class->getLocation(), MD);
5906 
5907         // There is no later point when we will see the definition of this
5908         // function, so pass it to the consumer now.
5909         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5910       }
5911     }
5912   }
5913 }
5914 
5915 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5916                                                         CXXRecordDecl *Class) {
5917   // Only the MS ABI has default constructor closures, so we don't need to do
5918   // this semantic checking anywhere else.
5919   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5920     return;
5921 
5922   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5923   for (Decl *Member : Class->decls()) {
5924     // Look for exported default constructors.
5925     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5926     if (!CD || !CD->isDefaultConstructor())
5927       continue;
5928     auto *Attr = CD->getAttr<DLLExportAttr>();
5929     if (!Attr)
5930       continue;
5931 
5932     // If the class is non-dependent, mark the default arguments as ODR-used so
5933     // that we can properly codegen the constructor closure.
5934     if (!Class->isDependentContext()) {
5935       for (ParmVarDecl *PD : CD->parameters()) {
5936         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5937         S.DiscardCleanupsInEvaluationContext();
5938       }
5939     }
5940 
5941     if (LastExportedDefaultCtor) {
5942       S.Diag(LastExportedDefaultCtor->getLocation(),
5943              diag::err_attribute_dll_ambiguous_default_ctor)
5944           << Class;
5945       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5946           << CD->getDeclName();
5947       return;
5948     }
5949     LastExportedDefaultCtor = CD;
5950   }
5951 }
5952 
5953 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5954                                                        CXXRecordDecl *Class) {
5955   bool ErrorReported = false;
5956   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5957                                                      ClassTemplateDecl *TD) {
5958     if (ErrorReported)
5959       return;
5960     S.Diag(TD->getLocation(),
5961            diag::err_cuda_device_builtin_surftex_cls_template)
5962         << /*surface*/ 0 << TD;
5963     ErrorReported = true;
5964   };
5965 
5966   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5967   if (!TD) {
5968     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5969     if (!SD) {
5970       S.Diag(Class->getLocation(),
5971              diag::err_cuda_device_builtin_surftex_ref_decl)
5972           << /*surface*/ 0 << Class;
5973       S.Diag(Class->getLocation(),
5974              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5975           << Class;
5976       return;
5977     }
5978     TD = SD->getSpecializedTemplate();
5979   }
5980 
5981   TemplateParameterList *Params = TD->getTemplateParameters();
5982   unsigned N = Params->size();
5983 
5984   if (N != 2) {
5985     reportIllegalClassTemplate(S, TD);
5986     S.Diag(TD->getLocation(),
5987            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5988         << TD << 2;
5989   }
5990   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5991     reportIllegalClassTemplate(S, TD);
5992     S.Diag(TD->getLocation(),
5993            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5994         << TD << /*1st*/ 0 << /*type*/ 0;
5995   }
5996   if (N > 1) {
5997     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5998     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5999       reportIllegalClassTemplate(S, TD);
6000       S.Diag(TD->getLocation(),
6001              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6002           << TD << /*2nd*/ 1 << /*integer*/ 1;
6003     }
6004   }
6005 }
6006 
6007 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6008                                                        CXXRecordDecl *Class) {
6009   bool ErrorReported = false;
6010   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6011                                                      ClassTemplateDecl *TD) {
6012     if (ErrorReported)
6013       return;
6014     S.Diag(TD->getLocation(),
6015            diag::err_cuda_device_builtin_surftex_cls_template)
6016         << /*texture*/ 1 << TD;
6017     ErrorReported = true;
6018   };
6019 
6020   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6021   if (!TD) {
6022     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6023     if (!SD) {
6024       S.Diag(Class->getLocation(),
6025              diag::err_cuda_device_builtin_surftex_ref_decl)
6026           << /*texture*/ 1 << Class;
6027       S.Diag(Class->getLocation(),
6028              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6029           << Class;
6030       return;
6031     }
6032     TD = SD->getSpecializedTemplate();
6033   }
6034 
6035   TemplateParameterList *Params = TD->getTemplateParameters();
6036   unsigned N = Params->size();
6037 
6038   if (N != 3) {
6039     reportIllegalClassTemplate(S, TD);
6040     S.Diag(TD->getLocation(),
6041            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6042         << TD << 3;
6043   }
6044   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6045     reportIllegalClassTemplate(S, TD);
6046     S.Diag(TD->getLocation(),
6047            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6048         << TD << /*1st*/ 0 << /*type*/ 0;
6049   }
6050   if (N > 1) {
6051     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6052     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6053       reportIllegalClassTemplate(S, TD);
6054       S.Diag(TD->getLocation(),
6055              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6056           << TD << /*2nd*/ 1 << /*integer*/ 1;
6057     }
6058   }
6059   if (N > 2) {
6060     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6061     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6062       reportIllegalClassTemplate(S, TD);
6063       S.Diag(TD->getLocation(),
6064              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6065           << TD << /*3rd*/ 2 << /*integer*/ 1;
6066     }
6067   }
6068 }
6069 
6070 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6071   // Mark any compiler-generated routines with the implicit code_seg attribute.
6072   for (auto *Method : Class->methods()) {
6073     if (Method->isUserProvided())
6074       continue;
6075     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6076       Method->addAttr(A);
6077   }
6078 }
6079 
6080 /// Check class-level dllimport/dllexport attribute.
6081 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6082   Attr *ClassAttr = getDLLAttr(Class);
6083 
6084   // MSVC inherits DLL attributes to partial class template specializations.
6085   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6086        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) && !ClassAttr) {
6087     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6088       if (Attr *TemplateAttr =
6089               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6090         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6091         A->setInherited(true);
6092         ClassAttr = A;
6093       }
6094     }
6095   }
6096 
6097   if (!ClassAttr)
6098     return;
6099 
6100   if (!Class->isExternallyVisible()) {
6101     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6102         << Class << ClassAttr;
6103     return;
6104   }
6105 
6106   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6107        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
6108       !ClassAttr->isInherited()) {
6109     // Diagnose dll attributes on members of class with dll attribute.
6110     for (Decl *Member : Class->decls()) {
6111       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6112         continue;
6113       InheritableAttr *MemberAttr = getDLLAttr(Member);
6114       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6115         continue;
6116 
6117       Diag(MemberAttr->getLocation(),
6118              diag::err_attribute_dll_member_of_dll_class)
6119           << MemberAttr << ClassAttr;
6120       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6121       Member->setInvalidDecl();
6122     }
6123   }
6124 
6125   if (Class->getDescribedClassTemplate())
6126     // Don't inherit dll attribute until the template is instantiated.
6127     return;
6128 
6129   // The class is either imported or exported.
6130   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6131 
6132   // Check if this was a dllimport attribute propagated from a derived class to
6133   // a base class template specialization. We don't apply these attributes to
6134   // static data members.
6135   const bool PropagatedImport =
6136       !ClassExported &&
6137       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6138 
6139   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6140 
6141   // Ignore explicit dllexport on explicit class template instantiation
6142   // declarations, except in MinGW mode.
6143   if (ClassExported && !ClassAttr->isInherited() &&
6144       TSK == TSK_ExplicitInstantiationDeclaration &&
6145       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6146     Class->dropAttr<DLLExportAttr>();
6147     return;
6148   }
6149 
6150   // Force declaration of implicit members so they can inherit the attribute.
6151   ForceDeclarationOfImplicitMembers(Class);
6152 
6153   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6154   // seem to be true in practice?
6155 
6156   for (Decl *Member : Class->decls()) {
6157     VarDecl *VD = dyn_cast<VarDecl>(Member);
6158     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6159 
6160     // Only methods and static fields inherit the attributes.
6161     if (!VD && !MD)
6162       continue;
6163 
6164     if (MD) {
6165       // Don't process deleted methods.
6166       if (MD->isDeleted())
6167         continue;
6168 
6169       if (MD->isInlined()) {
6170         // MinGW does not import or export inline methods. But do it for
6171         // template instantiations.
6172         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6173             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6174             TSK != TSK_ExplicitInstantiationDeclaration &&
6175             TSK != TSK_ExplicitInstantiationDefinition)
6176           continue;
6177 
6178         // MSVC versions before 2015 don't export the move assignment operators
6179         // and move constructor, so don't attempt to import/export them if
6180         // we have a definition.
6181         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6182         if ((MD->isMoveAssignmentOperator() ||
6183              (Ctor && Ctor->isMoveConstructor())) &&
6184             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6185           continue;
6186 
6187         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6188         // operator is exported anyway.
6189         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6190             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6191           continue;
6192       }
6193     }
6194 
6195     // Don't apply dllimport attributes to static data members of class template
6196     // instantiations when the attribute is propagated from a derived class.
6197     if (VD && PropagatedImport)
6198       continue;
6199 
6200     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6201       continue;
6202 
6203     if (!getDLLAttr(Member)) {
6204       InheritableAttr *NewAttr = nullptr;
6205 
6206       // Do not export/import inline function when -fno-dllexport-inlines is
6207       // passed. But add attribute for later local static var check.
6208       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6209           TSK != TSK_ExplicitInstantiationDeclaration &&
6210           TSK != TSK_ExplicitInstantiationDefinition) {
6211         if (ClassExported) {
6212           NewAttr = ::new (getASTContext())
6213               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6214         } else {
6215           NewAttr = ::new (getASTContext())
6216               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6217         }
6218       } else {
6219         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6220       }
6221 
6222       NewAttr->setInherited(true);
6223       Member->addAttr(NewAttr);
6224 
6225       if (MD) {
6226         // Propagate DLLAttr to friend re-declarations of MD that have already
6227         // been constructed.
6228         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6229              FD = FD->getPreviousDecl()) {
6230           if (FD->getFriendObjectKind() == Decl::FOK_None)
6231             continue;
6232           assert(!getDLLAttr(FD) &&
6233                  "friend re-decl should not already have a DLLAttr");
6234           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6235           NewAttr->setInherited(true);
6236           FD->addAttr(NewAttr);
6237         }
6238       }
6239     }
6240   }
6241 
6242   if (ClassExported)
6243     DelayedDllExportClasses.push_back(Class);
6244 }
6245 
6246 /// Perform propagation of DLL attributes from a derived class to a
6247 /// templated base class for MS compatibility.
6248 void Sema::propagateDLLAttrToBaseClassTemplate(
6249     CXXRecordDecl *Class, Attr *ClassAttr,
6250     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6251   if (getDLLAttr(
6252           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6253     // If the base class template has a DLL attribute, don't try to change it.
6254     return;
6255   }
6256 
6257   auto TSK = BaseTemplateSpec->getSpecializationKind();
6258   if (!getDLLAttr(BaseTemplateSpec) &&
6259       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6260        TSK == TSK_ImplicitInstantiation)) {
6261     // The template hasn't been instantiated yet (or it has, but only as an
6262     // explicit instantiation declaration or implicit instantiation, which means
6263     // we haven't codegenned any members yet), so propagate the attribute.
6264     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6265     NewAttr->setInherited(true);
6266     BaseTemplateSpec->addAttr(NewAttr);
6267 
6268     // If this was an import, mark that we propagated it from a derived class to
6269     // a base class template specialization.
6270     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6271       ImportAttr->setPropagatedToBaseTemplate();
6272 
6273     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6274     // needs to be run again to work see the new attribute. Otherwise this will
6275     // get run whenever the template is instantiated.
6276     if (TSK != TSK_Undeclared)
6277       checkClassLevelDLLAttribute(BaseTemplateSpec);
6278 
6279     return;
6280   }
6281 
6282   if (getDLLAttr(BaseTemplateSpec)) {
6283     // The template has already been specialized or instantiated with an
6284     // attribute, explicitly or through propagation. We should not try to change
6285     // it.
6286     return;
6287   }
6288 
6289   // The template was previously instantiated or explicitly specialized without
6290   // a dll attribute, It's too late for us to add an attribute, so warn that
6291   // this is unsupported.
6292   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6293       << BaseTemplateSpec->isExplicitSpecialization();
6294   Diag(ClassAttr->getLocation(), diag::note_attribute);
6295   if (BaseTemplateSpec->isExplicitSpecialization()) {
6296     Diag(BaseTemplateSpec->getLocation(),
6297            diag::note_template_class_explicit_specialization_was_here)
6298         << BaseTemplateSpec;
6299   } else {
6300     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6301            diag::note_template_class_instantiation_was_here)
6302         << BaseTemplateSpec;
6303   }
6304 }
6305 
6306 /// Determine the kind of defaulting that would be done for a given function.
6307 ///
6308 /// If the function is both a default constructor and a copy / move constructor
6309 /// (due to having a default argument for the first parameter), this picks
6310 /// CXXDefaultConstructor.
6311 ///
6312 /// FIXME: Check that case is properly handled by all callers.
6313 Sema::DefaultedFunctionKind
6314 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6315   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6316     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6317       if (Ctor->isDefaultConstructor())
6318         return Sema::CXXDefaultConstructor;
6319 
6320       if (Ctor->isCopyConstructor())
6321         return Sema::CXXCopyConstructor;
6322 
6323       if (Ctor->isMoveConstructor())
6324         return Sema::CXXMoveConstructor;
6325     }
6326 
6327     if (MD->isCopyAssignmentOperator())
6328       return Sema::CXXCopyAssignment;
6329 
6330     if (MD->isMoveAssignmentOperator())
6331       return Sema::CXXMoveAssignment;
6332 
6333     if (isa<CXXDestructorDecl>(FD))
6334       return Sema::CXXDestructor;
6335   }
6336 
6337   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6338   case OO_EqualEqual:
6339     return DefaultedComparisonKind::Equal;
6340 
6341   case OO_ExclaimEqual:
6342     return DefaultedComparisonKind::NotEqual;
6343 
6344   case OO_Spaceship:
6345     // No point allowing this if <=> doesn't exist in the current language mode.
6346     if (!getLangOpts().CPlusPlus20)
6347       break;
6348     return DefaultedComparisonKind::ThreeWay;
6349 
6350   case OO_Less:
6351   case OO_LessEqual:
6352   case OO_Greater:
6353   case OO_GreaterEqual:
6354     // No point allowing this if <=> doesn't exist in the current language mode.
6355     if (!getLangOpts().CPlusPlus20)
6356       break;
6357     return DefaultedComparisonKind::Relational;
6358 
6359   default:
6360     break;
6361   }
6362 
6363   // Not defaultable.
6364   return DefaultedFunctionKind();
6365 }
6366 
6367 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6368                                     SourceLocation DefaultLoc) {
6369   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6370   if (DFK.isComparison())
6371     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6372 
6373   switch (DFK.asSpecialMember()) {
6374   case Sema::CXXDefaultConstructor:
6375     S.DefineImplicitDefaultConstructor(DefaultLoc,
6376                                        cast<CXXConstructorDecl>(FD));
6377     break;
6378   case Sema::CXXCopyConstructor:
6379     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6380     break;
6381   case Sema::CXXCopyAssignment:
6382     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6383     break;
6384   case Sema::CXXDestructor:
6385     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6386     break;
6387   case Sema::CXXMoveConstructor:
6388     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6389     break;
6390   case Sema::CXXMoveAssignment:
6391     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6392     break;
6393   case Sema::CXXInvalid:
6394     llvm_unreachable("Invalid special member.");
6395   }
6396 }
6397 
6398 /// Determine whether a type is permitted to be passed or returned in
6399 /// registers, per C++ [class.temporary]p3.
6400 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6401                                TargetInfo::CallingConvKind CCK) {
6402   if (D->isDependentType() || D->isInvalidDecl())
6403     return false;
6404 
6405   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6406   // The PS4 platform ABI follows the behavior of Clang 3.2.
6407   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6408     return !D->hasNonTrivialDestructorForCall() &&
6409            !D->hasNonTrivialCopyConstructorForCall();
6410 
6411   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6412     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6413     bool DtorIsTrivialForCall = false;
6414 
6415     // If a class has at least one non-deleted, trivial copy constructor, it
6416     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6417     //
6418     // Note: This permits classes with non-trivial copy or move ctors to be
6419     // passed in registers, so long as they *also* have a trivial copy ctor,
6420     // which is non-conforming.
6421     if (D->needsImplicitCopyConstructor()) {
6422       if (!D->defaultedCopyConstructorIsDeleted()) {
6423         if (D->hasTrivialCopyConstructor())
6424           CopyCtorIsTrivial = true;
6425         if (D->hasTrivialCopyConstructorForCall())
6426           CopyCtorIsTrivialForCall = true;
6427       }
6428     } else {
6429       for (const CXXConstructorDecl *CD : D->ctors()) {
6430         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6431           if (CD->isTrivial())
6432             CopyCtorIsTrivial = true;
6433           if (CD->isTrivialForCall())
6434             CopyCtorIsTrivialForCall = true;
6435         }
6436       }
6437     }
6438 
6439     if (D->needsImplicitDestructor()) {
6440       if (!D->defaultedDestructorIsDeleted() &&
6441           D->hasTrivialDestructorForCall())
6442         DtorIsTrivialForCall = true;
6443     } else if (const auto *DD = D->getDestructor()) {
6444       if (!DD->isDeleted() && DD->isTrivialForCall())
6445         DtorIsTrivialForCall = true;
6446     }
6447 
6448     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6449     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6450       return true;
6451 
6452     // If a class has a destructor, we'd really like to pass it indirectly
6453     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6454     // impossible for small types, which it will pass in a single register or
6455     // stack slot. Most objects with dtors are large-ish, so handle that early.
6456     // We can't call out all large objects as being indirect because there are
6457     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6458     // how we pass large POD types.
6459 
6460     // Note: This permits small classes with nontrivial destructors to be
6461     // passed in registers, which is non-conforming.
6462     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6463     uint64_t TypeSize = isAArch64 ? 128 : 64;
6464 
6465     if (CopyCtorIsTrivial &&
6466         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6467       return true;
6468     return false;
6469   }
6470 
6471   // Per C++ [class.temporary]p3, the relevant condition is:
6472   //   each copy constructor, move constructor, and destructor of X is
6473   //   either trivial or deleted, and X has at least one non-deleted copy
6474   //   or move constructor
6475   bool HasNonDeletedCopyOrMove = false;
6476 
6477   if (D->needsImplicitCopyConstructor() &&
6478       !D->defaultedCopyConstructorIsDeleted()) {
6479     if (!D->hasTrivialCopyConstructorForCall())
6480       return false;
6481     HasNonDeletedCopyOrMove = true;
6482   }
6483 
6484   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6485       !D->defaultedMoveConstructorIsDeleted()) {
6486     if (!D->hasTrivialMoveConstructorForCall())
6487       return false;
6488     HasNonDeletedCopyOrMove = true;
6489   }
6490 
6491   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6492       !D->hasTrivialDestructorForCall())
6493     return false;
6494 
6495   for (const CXXMethodDecl *MD : D->methods()) {
6496     if (MD->isDeleted())
6497       continue;
6498 
6499     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6500     if (CD && CD->isCopyOrMoveConstructor())
6501       HasNonDeletedCopyOrMove = true;
6502     else if (!isa<CXXDestructorDecl>(MD))
6503       continue;
6504 
6505     if (!MD->isTrivialForCall())
6506       return false;
6507   }
6508 
6509   return HasNonDeletedCopyOrMove;
6510 }
6511 
6512 /// Report an error regarding overriding, along with any relevant
6513 /// overridden methods.
6514 ///
6515 /// \param DiagID the primary error to report.
6516 /// \param MD the overriding method.
6517 static bool
6518 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6519                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6520   bool IssuedDiagnostic = false;
6521   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6522     if (Report(O)) {
6523       if (!IssuedDiagnostic) {
6524         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6525         IssuedDiagnostic = true;
6526       }
6527       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6528     }
6529   }
6530   return IssuedDiagnostic;
6531 }
6532 
6533 /// Perform semantic checks on a class definition that has been
6534 /// completing, introducing implicitly-declared members, checking for
6535 /// abstract types, etc.
6536 ///
6537 /// \param S The scope in which the class was parsed. Null if we didn't just
6538 ///        parse a class definition.
6539 /// \param Record The completed class.
6540 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6541   if (!Record)
6542     return;
6543 
6544   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6545     AbstractUsageInfo Info(*this, Record);
6546     CheckAbstractClassUsage(Info, Record);
6547   }
6548 
6549   // If this is not an aggregate type and has no user-declared constructor,
6550   // complain about any non-static data members of reference or const scalar
6551   // type, since they will never get initializers.
6552   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6553       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6554       !Record->isLambda()) {
6555     bool Complained = false;
6556     for (const auto *F : Record->fields()) {
6557       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6558         continue;
6559 
6560       if (F->getType()->isReferenceType() ||
6561           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6562         if (!Complained) {
6563           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6564             << Record->getTagKind() << Record;
6565           Complained = true;
6566         }
6567 
6568         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6569           << F->getType()->isReferenceType()
6570           << F->getDeclName();
6571       }
6572     }
6573   }
6574 
6575   if (Record->getIdentifier()) {
6576     // C++ [class.mem]p13:
6577     //   If T is the name of a class, then each of the following shall have a
6578     //   name different from T:
6579     //     - every member of every anonymous union that is a member of class T.
6580     //
6581     // C++ [class.mem]p14:
6582     //   In addition, if class T has a user-declared constructor (12.1), every
6583     //   non-static data member of class T shall have a name different from T.
6584     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6585     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6586          ++I) {
6587       NamedDecl *D = (*I)->getUnderlyingDecl();
6588       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6589            Record->hasUserDeclaredConstructor()) ||
6590           isa<IndirectFieldDecl>(D)) {
6591         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6592           << D->getDeclName();
6593         break;
6594       }
6595     }
6596   }
6597 
6598   // Warn if the class has virtual methods but non-virtual public destructor.
6599   if (Record->isPolymorphic() && !Record->isDependentType()) {
6600     CXXDestructorDecl *dtor = Record->getDestructor();
6601     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6602         !Record->hasAttr<FinalAttr>())
6603       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6604            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6605   }
6606 
6607   if (Record->isAbstract()) {
6608     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6609       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6610         << FA->isSpelledAsSealed();
6611       DiagnoseAbstractType(Record);
6612     }
6613   }
6614 
6615   // Warn if the class has a final destructor but is not itself marked final.
6616   if (!Record->hasAttr<FinalAttr>()) {
6617     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6618       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6619         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6620             << FA->isSpelledAsSealed()
6621             << FixItHint::CreateInsertion(
6622                    getLocForEndOfToken(Record->getLocation()),
6623                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6624         Diag(Record->getLocation(),
6625              diag::note_final_dtor_non_final_class_silence)
6626             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6627       }
6628     }
6629   }
6630 
6631   // See if trivial_abi has to be dropped.
6632   if (Record->hasAttr<TrivialABIAttr>())
6633     checkIllFormedTrivialABIStruct(*Record);
6634 
6635   // Set HasTrivialSpecialMemberForCall if the record has attribute
6636   // "trivial_abi".
6637   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6638 
6639   if (HasTrivialABI)
6640     Record->setHasTrivialSpecialMemberForCall();
6641 
6642   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6643   // We check these last because they can depend on the properties of the
6644   // primary comparison functions (==, <=>).
6645   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6646 
6647   // Perform checks that can't be done until we know all the properties of a
6648   // member function (whether it's defaulted, deleted, virtual, overriding,
6649   // ...).
6650   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6651     // A static function cannot override anything.
6652     if (MD->getStorageClass() == SC_Static) {
6653       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6654                           [](const CXXMethodDecl *) { return true; }))
6655         return;
6656     }
6657 
6658     // A deleted function cannot override a non-deleted function and vice
6659     // versa.
6660     if (ReportOverrides(*this,
6661                         MD->isDeleted() ? diag::err_deleted_override
6662                                         : diag::err_non_deleted_override,
6663                         MD, [&](const CXXMethodDecl *V) {
6664                           return MD->isDeleted() != V->isDeleted();
6665                         })) {
6666       if (MD->isDefaulted() && MD->isDeleted())
6667         // Explain why this defaulted function was deleted.
6668         DiagnoseDeletedDefaultedFunction(MD);
6669       return;
6670     }
6671 
6672     // A consteval function cannot override a non-consteval function and vice
6673     // versa.
6674     if (ReportOverrides(*this,
6675                         MD->isConsteval() ? diag::err_consteval_override
6676                                           : diag::err_non_consteval_override,
6677                         MD, [&](const CXXMethodDecl *V) {
6678                           return MD->isConsteval() != V->isConsteval();
6679                         })) {
6680       if (MD->isDefaulted() && MD->isDeleted())
6681         // Explain why this defaulted function was deleted.
6682         DiagnoseDeletedDefaultedFunction(MD);
6683       return;
6684     }
6685   };
6686 
6687   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6688     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6689       return false;
6690 
6691     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6692     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6693         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6694       DefaultedSecondaryComparisons.push_back(FD);
6695       return true;
6696     }
6697 
6698     CheckExplicitlyDefaultedFunction(S, FD);
6699     return false;
6700   };
6701 
6702   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6703     // Check whether the explicitly-defaulted members are valid.
6704     bool Incomplete = CheckForDefaultedFunction(M);
6705 
6706     // Skip the rest of the checks for a member of a dependent class.
6707     if (Record->isDependentType())
6708       return;
6709 
6710     // For an explicitly defaulted or deleted special member, we defer
6711     // determining triviality until the class is complete. That time is now!
6712     CXXSpecialMember CSM = getSpecialMember(M);
6713     if (!M->isImplicit() && !M->isUserProvided()) {
6714       if (CSM != CXXInvalid) {
6715         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6716         // Inform the class that we've finished declaring this member.
6717         Record->finishedDefaultedOrDeletedMember(M);
6718         M->setTrivialForCall(
6719             HasTrivialABI ||
6720             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6721         Record->setTrivialForCallFlags(M);
6722       }
6723     }
6724 
6725     // Set triviality for the purpose of calls if this is a user-provided
6726     // copy/move constructor or destructor.
6727     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6728          CSM == CXXDestructor) && M->isUserProvided()) {
6729       M->setTrivialForCall(HasTrivialABI);
6730       Record->setTrivialForCallFlags(M);
6731     }
6732 
6733     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6734         M->hasAttr<DLLExportAttr>()) {
6735       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6736           M->isTrivial() &&
6737           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6738            CSM == CXXDestructor))
6739         M->dropAttr<DLLExportAttr>();
6740 
6741       if (M->hasAttr<DLLExportAttr>()) {
6742         // Define after any fields with in-class initializers have been parsed.
6743         DelayedDllExportMemberFunctions.push_back(M);
6744       }
6745     }
6746 
6747     // Define defaulted constexpr virtual functions that override a base class
6748     // function right away.
6749     // FIXME: We can defer doing this until the vtable is marked as used.
6750     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6751       DefineDefaultedFunction(*this, M, M->getLocation());
6752 
6753     if (!Incomplete)
6754       CheckCompletedMemberFunction(M);
6755   };
6756 
6757   // Check the destructor before any other member function. We need to
6758   // determine whether it's trivial in order to determine whether the claas
6759   // type is a literal type, which is a prerequisite for determining whether
6760   // other special member functions are valid and whether they're implicitly
6761   // 'constexpr'.
6762   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6763     CompleteMemberFunction(Dtor);
6764 
6765   bool HasMethodWithOverrideControl = false,
6766        HasOverridingMethodWithoutOverrideControl = false;
6767   for (auto *D : Record->decls()) {
6768     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6769       // FIXME: We could do this check for dependent types with non-dependent
6770       // bases.
6771       if (!Record->isDependentType()) {
6772         // See if a method overloads virtual methods in a base
6773         // class without overriding any.
6774         if (!M->isStatic())
6775           DiagnoseHiddenVirtualMethods(M);
6776         if (M->hasAttr<OverrideAttr>())
6777           HasMethodWithOverrideControl = true;
6778         else if (M->size_overridden_methods() > 0)
6779           HasOverridingMethodWithoutOverrideControl = true;
6780       }
6781 
6782       if (!isa<CXXDestructorDecl>(M))
6783         CompleteMemberFunction(M);
6784     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6785       CheckForDefaultedFunction(
6786           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6787     }
6788   }
6789 
6790   if (HasOverridingMethodWithoutOverrideControl) {
6791     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6792     for (auto *M : Record->methods())
6793       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6794   }
6795 
6796   // Check the defaulted secondary comparisons after any other member functions.
6797   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6798     CheckExplicitlyDefaultedFunction(S, FD);
6799 
6800     // If this is a member function, we deferred checking it until now.
6801     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6802       CheckCompletedMemberFunction(MD);
6803   }
6804 
6805   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6806   // whether this class uses any C++ features that are implemented
6807   // completely differently in MSVC, and if so, emit a diagnostic.
6808   // That diagnostic defaults to an error, but we allow projects to
6809   // map it down to a warning (or ignore it).  It's a fairly common
6810   // practice among users of the ms_struct pragma to mass-annotate
6811   // headers, sweeping up a bunch of types that the project doesn't
6812   // really rely on MSVC-compatible layout for.  We must therefore
6813   // support "ms_struct except for C++ stuff" as a secondary ABI.
6814   // Don't emit this diagnostic if the feature was enabled as a
6815   // language option (as opposed to via a pragma or attribute), as
6816   // the option -mms-bitfields otherwise essentially makes it impossible
6817   // to build C++ code, unless this diagnostic is turned off.
6818   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6819       (Record->isPolymorphic() || Record->getNumBases())) {
6820     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6821   }
6822 
6823   checkClassLevelDLLAttribute(Record);
6824   checkClassLevelCodeSegAttribute(Record);
6825 
6826   bool ClangABICompat4 =
6827       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6828   TargetInfo::CallingConvKind CCK =
6829       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6830   bool CanPass = canPassInRegisters(*this, Record, CCK);
6831 
6832   // Do not change ArgPassingRestrictions if it has already been set to
6833   // APK_CanNeverPassInRegs.
6834   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6835     Record->setArgPassingRestrictions(CanPass
6836                                           ? RecordDecl::APK_CanPassInRegs
6837                                           : RecordDecl::APK_CannotPassInRegs);
6838 
6839   // If canPassInRegisters returns true despite the record having a non-trivial
6840   // destructor, the record is destructed in the callee. This happens only when
6841   // the record or one of its subobjects has a field annotated with trivial_abi
6842   // or a field qualified with ObjC __strong/__weak.
6843   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6844     Record->setParamDestroyedInCallee(true);
6845   else if (Record->hasNonTrivialDestructor())
6846     Record->setParamDestroyedInCallee(CanPass);
6847 
6848   if (getLangOpts().ForceEmitVTables) {
6849     // If we want to emit all the vtables, we need to mark it as used.  This
6850     // is especially required for cases like vtable assumption loads.
6851     MarkVTableUsed(Record->getInnerLocStart(), Record);
6852   }
6853 
6854   if (getLangOpts().CUDA) {
6855     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6856       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6857     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6858       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6859   }
6860 }
6861 
6862 /// Look up the special member function that would be called by a special
6863 /// member function for a subobject of class type.
6864 ///
6865 /// \param Class The class type of the subobject.
6866 /// \param CSM The kind of special member function.
6867 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6868 /// \param ConstRHS True if this is a copy operation with a const object
6869 ///        on its RHS, that is, if the argument to the outer special member
6870 ///        function is 'const' and this is not a field marked 'mutable'.
6871 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6872     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6873     unsigned FieldQuals, bool ConstRHS) {
6874   unsigned LHSQuals = 0;
6875   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6876     LHSQuals = FieldQuals;
6877 
6878   unsigned RHSQuals = FieldQuals;
6879   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6880     RHSQuals = 0;
6881   else if (ConstRHS)
6882     RHSQuals |= Qualifiers::Const;
6883 
6884   return S.LookupSpecialMember(Class, CSM,
6885                                RHSQuals & Qualifiers::Const,
6886                                RHSQuals & Qualifiers::Volatile,
6887                                false,
6888                                LHSQuals & Qualifiers::Const,
6889                                LHSQuals & Qualifiers::Volatile);
6890 }
6891 
6892 class Sema::InheritedConstructorInfo {
6893   Sema &S;
6894   SourceLocation UseLoc;
6895 
6896   /// A mapping from the base classes through which the constructor was
6897   /// inherited to the using shadow declaration in that base class (or a null
6898   /// pointer if the constructor was declared in that base class).
6899   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6900       InheritedFromBases;
6901 
6902 public:
6903   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6904                            ConstructorUsingShadowDecl *Shadow)
6905       : S(S), UseLoc(UseLoc) {
6906     bool DiagnosedMultipleConstructedBases = false;
6907     CXXRecordDecl *ConstructedBase = nullptr;
6908     UsingDecl *ConstructedBaseUsing = nullptr;
6909 
6910     // Find the set of such base class subobjects and check that there's a
6911     // unique constructed subobject.
6912     for (auto *D : Shadow->redecls()) {
6913       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6914       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6915       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6916 
6917       InheritedFromBases.insert(
6918           std::make_pair(DNominatedBase->getCanonicalDecl(),
6919                          DShadow->getNominatedBaseClassShadowDecl()));
6920       if (DShadow->constructsVirtualBase())
6921         InheritedFromBases.insert(
6922             std::make_pair(DConstructedBase->getCanonicalDecl(),
6923                            DShadow->getConstructedBaseClassShadowDecl()));
6924       else
6925         assert(DNominatedBase == DConstructedBase);
6926 
6927       // [class.inhctor.init]p2:
6928       //   If the constructor was inherited from multiple base class subobjects
6929       //   of type B, the program is ill-formed.
6930       if (!ConstructedBase) {
6931         ConstructedBase = DConstructedBase;
6932         ConstructedBaseUsing = D->getUsingDecl();
6933       } else if (ConstructedBase != DConstructedBase &&
6934                  !Shadow->isInvalidDecl()) {
6935         if (!DiagnosedMultipleConstructedBases) {
6936           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6937               << Shadow->getTargetDecl();
6938           S.Diag(ConstructedBaseUsing->getLocation(),
6939                diag::note_ambiguous_inherited_constructor_using)
6940               << ConstructedBase;
6941           DiagnosedMultipleConstructedBases = true;
6942         }
6943         S.Diag(D->getUsingDecl()->getLocation(),
6944                diag::note_ambiguous_inherited_constructor_using)
6945             << DConstructedBase;
6946       }
6947     }
6948 
6949     if (DiagnosedMultipleConstructedBases)
6950       Shadow->setInvalidDecl();
6951   }
6952 
6953   /// Find the constructor to use for inherited construction of a base class,
6954   /// and whether that base class constructor inherits the constructor from a
6955   /// virtual base class (in which case it won't actually invoke it).
6956   std::pair<CXXConstructorDecl *, bool>
6957   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6958     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6959     if (It == InheritedFromBases.end())
6960       return std::make_pair(nullptr, false);
6961 
6962     // This is an intermediary class.
6963     if (It->second)
6964       return std::make_pair(
6965           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6966           It->second->constructsVirtualBase());
6967 
6968     // This is the base class from which the constructor was inherited.
6969     return std::make_pair(Ctor, false);
6970   }
6971 };
6972 
6973 /// Is the special member function which would be selected to perform the
6974 /// specified operation on the specified class type a constexpr constructor?
6975 static bool
6976 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6977                          Sema::CXXSpecialMember CSM, unsigned Quals,
6978                          bool ConstRHS,
6979                          CXXConstructorDecl *InheritedCtor = nullptr,
6980                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6981   // If we're inheriting a constructor, see if we need to call it for this base
6982   // class.
6983   if (InheritedCtor) {
6984     assert(CSM == Sema::CXXDefaultConstructor);
6985     auto BaseCtor =
6986         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6987     if (BaseCtor)
6988       return BaseCtor->isConstexpr();
6989   }
6990 
6991   if (CSM == Sema::CXXDefaultConstructor)
6992     return ClassDecl->hasConstexprDefaultConstructor();
6993   if (CSM == Sema::CXXDestructor)
6994     return ClassDecl->hasConstexprDestructor();
6995 
6996   Sema::SpecialMemberOverloadResult SMOR =
6997       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6998   if (!SMOR.getMethod())
6999     // A constructor we wouldn't select can't be "involved in initializing"
7000     // anything.
7001     return true;
7002   return SMOR.getMethod()->isConstexpr();
7003 }
7004 
7005 /// Determine whether the specified special member function would be constexpr
7006 /// if it were implicitly defined.
7007 static bool defaultedSpecialMemberIsConstexpr(
7008     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7009     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7010     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7011   if (!S.getLangOpts().CPlusPlus11)
7012     return false;
7013 
7014   // C++11 [dcl.constexpr]p4:
7015   // In the definition of a constexpr constructor [...]
7016   bool Ctor = true;
7017   switch (CSM) {
7018   case Sema::CXXDefaultConstructor:
7019     if (Inherited)
7020       break;
7021     // Since default constructor lookup is essentially trivial (and cannot
7022     // involve, for instance, template instantiation), we compute whether a
7023     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7024     //
7025     // This is important for performance; we need to know whether the default
7026     // constructor is constexpr to determine whether the type is a literal type.
7027     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7028 
7029   case Sema::CXXCopyConstructor:
7030   case Sema::CXXMoveConstructor:
7031     // For copy or move constructors, we need to perform overload resolution.
7032     break;
7033 
7034   case Sema::CXXCopyAssignment:
7035   case Sema::CXXMoveAssignment:
7036     if (!S.getLangOpts().CPlusPlus14)
7037       return false;
7038     // In C++1y, we need to perform overload resolution.
7039     Ctor = false;
7040     break;
7041 
7042   case Sema::CXXDestructor:
7043     return ClassDecl->defaultedDestructorIsConstexpr();
7044 
7045   case Sema::CXXInvalid:
7046     return false;
7047   }
7048 
7049   //   -- if the class is a non-empty union, or for each non-empty anonymous
7050   //      union member of a non-union class, exactly one non-static data member
7051   //      shall be initialized; [DR1359]
7052   //
7053   // If we squint, this is guaranteed, since exactly one non-static data member
7054   // will be initialized (if the constructor isn't deleted), we just don't know
7055   // which one.
7056   if (Ctor && ClassDecl->isUnion())
7057     return CSM == Sema::CXXDefaultConstructor
7058                ? ClassDecl->hasInClassInitializer() ||
7059                      !ClassDecl->hasVariantMembers()
7060                : true;
7061 
7062   //   -- the class shall not have any virtual base classes;
7063   if (Ctor && ClassDecl->getNumVBases())
7064     return false;
7065 
7066   // C++1y [class.copy]p26:
7067   //   -- [the class] is a literal type, and
7068   if (!Ctor && !ClassDecl->isLiteral())
7069     return false;
7070 
7071   //   -- every constructor involved in initializing [...] base class
7072   //      sub-objects shall be a constexpr constructor;
7073   //   -- the assignment operator selected to copy/move each direct base
7074   //      class is a constexpr function, and
7075   for (const auto &B : ClassDecl->bases()) {
7076     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7077     if (!BaseType) continue;
7078 
7079     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7080     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7081                                   InheritedCtor, Inherited))
7082       return false;
7083   }
7084 
7085   //   -- every constructor involved in initializing non-static data members
7086   //      [...] shall be a constexpr constructor;
7087   //   -- every non-static data member and base class sub-object shall be
7088   //      initialized
7089   //   -- for each non-static data member of X that is of class type (or array
7090   //      thereof), the assignment operator selected to copy/move that member is
7091   //      a constexpr function
7092   for (const auto *F : ClassDecl->fields()) {
7093     if (F->isInvalidDecl())
7094       continue;
7095     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7096       continue;
7097     QualType BaseType = S.Context.getBaseElementType(F->getType());
7098     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7099       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7100       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7101                                     BaseType.getCVRQualifiers(),
7102                                     ConstArg && !F->isMutable()))
7103         return false;
7104     } else if (CSM == Sema::CXXDefaultConstructor) {
7105       return false;
7106     }
7107   }
7108 
7109   // All OK, it's constexpr!
7110   return true;
7111 }
7112 
7113 namespace {
7114 /// RAII object to register a defaulted function as having its exception
7115 /// specification computed.
7116 struct ComputingExceptionSpec {
7117   Sema &S;
7118 
7119   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7120       : S(S) {
7121     Sema::CodeSynthesisContext Ctx;
7122     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7123     Ctx.PointOfInstantiation = Loc;
7124     Ctx.Entity = FD;
7125     S.pushCodeSynthesisContext(Ctx);
7126   }
7127   ~ComputingExceptionSpec() {
7128     S.popCodeSynthesisContext();
7129   }
7130 };
7131 }
7132 
7133 static Sema::ImplicitExceptionSpecification
7134 ComputeDefaultedSpecialMemberExceptionSpec(
7135     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7136     Sema::InheritedConstructorInfo *ICI);
7137 
7138 static Sema::ImplicitExceptionSpecification
7139 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7140                                         FunctionDecl *FD,
7141                                         Sema::DefaultedComparisonKind DCK);
7142 
7143 static Sema::ImplicitExceptionSpecification
7144 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7145   auto DFK = S.getDefaultedFunctionKind(FD);
7146   if (DFK.isSpecialMember())
7147     return ComputeDefaultedSpecialMemberExceptionSpec(
7148         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7149   if (DFK.isComparison())
7150     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7151                                                    DFK.asComparison());
7152 
7153   auto *CD = cast<CXXConstructorDecl>(FD);
7154   assert(CD->getInheritedConstructor() &&
7155          "only defaulted functions and inherited constructors have implicit "
7156          "exception specs");
7157   Sema::InheritedConstructorInfo ICI(
7158       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7159   return ComputeDefaultedSpecialMemberExceptionSpec(
7160       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7161 }
7162 
7163 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7164                                                             CXXMethodDecl *MD) {
7165   FunctionProtoType::ExtProtoInfo EPI;
7166 
7167   // Build an exception specification pointing back at this member.
7168   EPI.ExceptionSpec.Type = EST_Unevaluated;
7169   EPI.ExceptionSpec.SourceDecl = MD;
7170 
7171   // Set the calling convention to the default for C++ instance methods.
7172   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7173       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7174                                             /*IsCXXMethod=*/true));
7175   return EPI;
7176 }
7177 
7178 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7179   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7180   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7181     return;
7182 
7183   // Evaluate the exception specification.
7184   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7185   auto ESI = IES.getExceptionSpec();
7186 
7187   // Update the type of the special member to use it.
7188   UpdateExceptionSpec(FD, ESI);
7189 }
7190 
7191 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7192   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7193 
7194   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7195   if (!DefKind) {
7196     assert(FD->getDeclContext()->isDependentContext());
7197     return;
7198   }
7199 
7200   if (DefKind.isSpecialMember()
7201           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7202                                                   DefKind.asSpecialMember())
7203           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7204     FD->setInvalidDecl();
7205 }
7206 
7207 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7208                                                  CXXSpecialMember CSM) {
7209   CXXRecordDecl *RD = MD->getParent();
7210 
7211   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7212          "not an explicitly-defaulted special member");
7213 
7214   // Defer all checking for special members of a dependent type.
7215   if (RD->isDependentType())
7216     return false;
7217 
7218   // Whether this was the first-declared instance of the constructor.
7219   // This affects whether we implicitly add an exception spec and constexpr.
7220   bool First = MD == MD->getCanonicalDecl();
7221 
7222   bool HadError = false;
7223 
7224   // C++11 [dcl.fct.def.default]p1:
7225   //   A function that is explicitly defaulted shall
7226   //     -- be a special member function [...] (checked elsewhere),
7227   //     -- have the same type (except for ref-qualifiers, and except that a
7228   //        copy operation can take a non-const reference) as an implicit
7229   //        declaration, and
7230   //     -- not have default arguments.
7231   // C++2a changes the second bullet to instead delete the function if it's
7232   // defaulted on its first declaration, unless it's "an assignment operator,
7233   // and its return type differs or its parameter type is not a reference".
7234   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7235   bool ShouldDeleteForTypeMismatch = false;
7236   unsigned ExpectedParams = 1;
7237   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7238     ExpectedParams = 0;
7239   if (MD->getNumParams() != ExpectedParams) {
7240     // This checks for default arguments: a copy or move constructor with a
7241     // default argument is classified as a default constructor, and assignment
7242     // operations and destructors can't have default arguments.
7243     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7244       << CSM << MD->getSourceRange();
7245     HadError = true;
7246   } else if (MD->isVariadic()) {
7247     if (DeleteOnTypeMismatch)
7248       ShouldDeleteForTypeMismatch = true;
7249     else {
7250       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7251         << CSM << MD->getSourceRange();
7252       HadError = true;
7253     }
7254   }
7255 
7256   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7257 
7258   bool CanHaveConstParam = false;
7259   if (CSM == CXXCopyConstructor)
7260     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7261   else if (CSM == CXXCopyAssignment)
7262     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7263 
7264   QualType ReturnType = Context.VoidTy;
7265   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7266     // Check for return type matching.
7267     ReturnType = Type->getReturnType();
7268 
7269     QualType DeclType = Context.getTypeDeclType(RD);
7270     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7271     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7272 
7273     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7274       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7275         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7276       HadError = true;
7277     }
7278 
7279     // A defaulted special member cannot have cv-qualifiers.
7280     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7281       if (DeleteOnTypeMismatch)
7282         ShouldDeleteForTypeMismatch = true;
7283       else {
7284         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7285           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7286         HadError = true;
7287       }
7288     }
7289   }
7290 
7291   // Check for parameter type matching.
7292   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7293   bool HasConstParam = false;
7294   if (ExpectedParams && ArgType->isReferenceType()) {
7295     // Argument must be reference to possibly-const T.
7296     QualType ReferentType = ArgType->getPointeeType();
7297     HasConstParam = ReferentType.isConstQualified();
7298 
7299     if (ReferentType.isVolatileQualified()) {
7300       if (DeleteOnTypeMismatch)
7301         ShouldDeleteForTypeMismatch = true;
7302       else {
7303         Diag(MD->getLocation(),
7304              diag::err_defaulted_special_member_volatile_param) << CSM;
7305         HadError = true;
7306       }
7307     }
7308 
7309     if (HasConstParam && !CanHaveConstParam) {
7310       if (DeleteOnTypeMismatch)
7311         ShouldDeleteForTypeMismatch = true;
7312       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7313         Diag(MD->getLocation(),
7314              diag::err_defaulted_special_member_copy_const_param)
7315           << (CSM == CXXCopyAssignment);
7316         // FIXME: Explain why this special member can't be const.
7317         HadError = true;
7318       } else {
7319         Diag(MD->getLocation(),
7320              diag::err_defaulted_special_member_move_const_param)
7321           << (CSM == CXXMoveAssignment);
7322         HadError = true;
7323       }
7324     }
7325   } else if (ExpectedParams) {
7326     // A copy assignment operator can take its argument by value, but a
7327     // defaulted one cannot.
7328     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7329     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7330     HadError = true;
7331   }
7332 
7333   // C++11 [dcl.fct.def.default]p2:
7334   //   An explicitly-defaulted function may be declared constexpr only if it
7335   //   would have been implicitly declared as constexpr,
7336   // Do not apply this rule to members of class templates, since core issue 1358
7337   // makes such functions always instantiate to constexpr functions. For
7338   // functions which cannot be constexpr (for non-constructors in C++11 and for
7339   // destructors in C++14 and C++17), this is checked elsewhere.
7340   //
7341   // FIXME: This should not apply if the member is deleted.
7342   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7343                                                      HasConstParam);
7344   if ((getLangOpts().CPlusPlus20 ||
7345        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7346                                   : isa<CXXConstructorDecl>(MD))) &&
7347       MD->isConstexpr() && !Constexpr &&
7348       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7349     Diag(MD->getBeginLoc(), MD->isConsteval()
7350                                 ? diag::err_incorrect_defaulted_consteval
7351                                 : diag::err_incorrect_defaulted_constexpr)
7352         << CSM;
7353     // FIXME: Explain why the special member can't be constexpr.
7354     HadError = true;
7355   }
7356 
7357   if (First) {
7358     // C++2a [dcl.fct.def.default]p3:
7359     //   If a function is explicitly defaulted on its first declaration, it is
7360     //   implicitly considered to be constexpr if the implicit declaration
7361     //   would be.
7362     MD->setConstexprKind(
7363         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7364                   : CSK_unspecified);
7365 
7366     if (!Type->hasExceptionSpec()) {
7367       // C++2a [except.spec]p3:
7368       //   If a declaration of a function does not have a noexcept-specifier
7369       //   [and] is defaulted on its first declaration, [...] the exception
7370       //   specification is as specified below
7371       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7372       EPI.ExceptionSpec.Type = EST_Unevaluated;
7373       EPI.ExceptionSpec.SourceDecl = MD;
7374       MD->setType(Context.getFunctionType(ReturnType,
7375                                           llvm::makeArrayRef(&ArgType,
7376                                                              ExpectedParams),
7377                                           EPI));
7378     }
7379   }
7380 
7381   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7382     if (First) {
7383       SetDeclDeleted(MD, MD->getLocation());
7384       if (!inTemplateInstantiation() && !HadError) {
7385         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7386         if (ShouldDeleteForTypeMismatch) {
7387           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7388         } else {
7389           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7390         }
7391       }
7392       if (ShouldDeleteForTypeMismatch && !HadError) {
7393         Diag(MD->getLocation(),
7394              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7395       }
7396     } else {
7397       // C++11 [dcl.fct.def.default]p4:
7398       //   [For a] user-provided explicitly-defaulted function [...] if such a
7399       //   function is implicitly defined as deleted, the program is ill-formed.
7400       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7401       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7402       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7403       HadError = true;
7404     }
7405   }
7406 
7407   return HadError;
7408 }
7409 
7410 namespace {
7411 /// Helper class for building and checking a defaulted comparison.
7412 ///
7413 /// Defaulted functions are built in two phases:
7414 ///
7415 ///  * First, the set of operations that the function will perform are
7416 ///    identified, and some of them are checked. If any of the checked
7417 ///    operations is invalid in certain ways, the comparison function is
7418 ///    defined as deleted and no body is built.
7419 ///  * Then, if the function is not defined as deleted, the body is built.
7420 ///
7421 /// This is accomplished by performing two visitation steps over the eventual
7422 /// body of the function.
7423 template<typename Derived, typename ResultList, typename Result,
7424          typename Subobject>
7425 class DefaultedComparisonVisitor {
7426 public:
7427   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7428 
7429   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7430                              DefaultedComparisonKind DCK)
7431       : S(S), RD(RD), FD(FD), DCK(DCK) {
7432     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7433       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7434       // UnresolvedSet to avoid this copy.
7435       Fns.assign(Info->getUnqualifiedLookups().begin(),
7436                  Info->getUnqualifiedLookups().end());
7437     }
7438   }
7439 
7440   ResultList visit() {
7441     // The type of an lvalue naming a parameter of this function.
7442     QualType ParamLvalType =
7443         FD->getParamDecl(0)->getType().getNonReferenceType();
7444 
7445     ResultList Results;
7446 
7447     switch (DCK) {
7448     case DefaultedComparisonKind::None:
7449       llvm_unreachable("not a defaulted comparison");
7450 
7451     case DefaultedComparisonKind::Equal:
7452     case DefaultedComparisonKind::ThreeWay:
7453       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7454       return Results;
7455 
7456     case DefaultedComparisonKind::NotEqual:
7457     case DefaultedComparisonKind::Relational:
7458       Results.add(getDerived().visitExpandedSubobject(
7459           ParamLvalType, getDerived().getCompleteObject()));
7460       return Results;
7461     }
7462     llvm_unreachable("");
7463   }
7464 
7465 protected:
7466   Derived &getDerived() { return static_cast<Derived&>(*this); }
7467 
7468   /// Visit the expanded list of subobjects of the given type, as specified in
7469   /// C++2a [class.compare.default].
7470   ///
7471   /// \return \c true if the ResultList object said we're done, \c false if not.
7472   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7473                        Qualifiers Quals) {
7474     // C++2a [class.compare.default]p4:
7475     //   The direct base class subobjects of C
7476     for (CXXBaseSpecifier &Base : Record->bases())
7477       if (Results.add(getDerived().visitSubobject(
7478               S.Context.getQualifiedType(Base.getType(), Quals),
7479               getDerived().getBase(&Base))))
7480         return true;
7481 
7482     //   followed by the non-static data members of C
7483     for (FieldDecl *Field : Record->fields()) {
7484       // Recursively expand anonymous structs.
7485       if (Field->isAnonymousStructOrUnion()) {
7486         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7487                             Quals))
7488           return true;
7489         continue;
7490       }
7491 
7492       // Figure out the type of an lvalue denoting this field.
7493       Qualifiers FieldQuals = Quals;
7494       if (Field->isMutable())
7495         FieldQuals.removeConst();
7496       QualType FieldType =
7497           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7498 
7499       if (Results.add(getDerived().visitSubobject(
7500               FieldType, getDerived().getField(Field))))
7501         return true;
7502     }
7503 
7504     //   form a list of subobjects.
7505     return false;
7506   }
7507 
7508   Result visitSubobject(QualType Type, Subobject Subobj) {
7509     //   In that list, any subobject of array type is recursively expanded
7510     const ArrayType *AT = S.Context.getAsArrayType(Type);
7511     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7512       return getDerived().visitSubobjectArray(CAT->getElementType(),
7513                                               CAT->getSize(), Subobj);
7514     return getDerived().visitExpandedSubobject(Type, Subobj);
7515   }
7516 
7517   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7518                              Subobject Subobj) {
7519     return getDerived().visitSubobject(Type, Subobj);
7520   }
7521 
7522 protected:
7523   Sema &S;
7524   CXXRecordDecl *RD;
7525   FunctionDecl *FD;
7526   DefaultedComparisonKind DCK;
7527   UnresolvedSet<16> Fns;
7528 };
7529 
7530 /// Information about a defaulted comparison, as determined by
7531 /// DefaultedComparisonAnalyzer.
7532 struct DefaultedComparisonInfo {
7533   bool Deleted = false;
7534   bool Constexpr = true;
7535   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7536 
7537   static DefaultedComparisonInfo deleted() {
7538     DefaultedComparisonInfo Deleted;
7539     Deleted.Deleted = true;
7540     return Deleted;
7541   }
7542 
7543   bool add(const DefaultedComparisonInfo &R) {
7544     Deleted |= R.Deleted;
7545     Constexpr &= R.Constexpr;
7546     Category = commonComparisonType(Category, R.Category);
7547     return Deleted;
7548   }
7549 };
7550 
7551 /// An element in the expanded list of subobjects of a defaulted comparison, as
7552 /// specified in C++2a [class.compare.default]p4.
7553 struct DefaultedComparisonSubobject {
7554   enum { CompleteObject, Member, Base } Kind;
7555   NamedDecl *Decl;
7556   SourceLocation Loc;
7557 };
7558 
7559 /// A visitor over the notional body of a defaulted comparison that determines
7560 /// whether that body would be deleted or constexpr.
7561 class DefaultedComparisonAnalyzer
7562     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7563                                         DefaultedComparisonInfo,
7564                                         DefaultedComparisonInfo,
7565                                         DefaultedComparisonSubobject> {
7566 public:
7567   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7568 
7569 private:
7570   DiagnosticKind Diagnose;
7571 
7572 public:
7573   using Base = DefaultedComparisonVisitor;
7574   using Result = DefaultedComparisonInfo;
7575   using Subobject = DefaultedComparisonSubobject;
7576 
7577   friend Base;
7578 
7579   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7580                               DefaultedComparisonKind DCK,
7581                               DiagnosticKind Diagnose = NoDiagnostics)
7582       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7583 
7584   Result visit() {
7585     if ((DCK == DefaultedComparisonKind::Equal ||
7586          DCK == DefaultedComparisonKind::ThreeWay) &&
7587         RD->hasVariantMembers()) {
7588       // C++2a [class.compare.default]p2 [P2002R0]:
7589       //   A defaulted comparison operator function for class C is defined as
7590       //   deleted if [...] C has variant members.
7591       if (Diagnose == ExplainDeleted) {
7592         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7593           << FD << RD->isUnion() << RD;
7594       }
7595       return Result::deleted();
7596     }
7597 
7598     return Base::visit();
7599   }
7600 
7601 private:
7602   Subobject getCompleteObject() {
7603     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7604   }
7605 
7606   Subobject getBase(CXXBaseSpecifier *Base) {
7607     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7608                      Base->getBaseTypeLoc()};
7609   }
7610 
7611   Subobject getField(FieldDecl *Field) {
7612     return Subobject{Subobject::Member, Field, Field->getLocation()};
7613   }
7614 
7615   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7616     // C++2a [class.compare.default]p2 [P2002R0]:
7617     //   A defaulted <=> or == operator function for class C is defined as
7618     //   deleted if any non-static data member of C is of reference type
7619     if (Type->isReferenceType()) {
7620       if (Diagnose == ExplainDeleted) {
7621         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7622             << FD << RD;
7623       }
7624       return Result::deleted();
7625     }
7626 
7627     // [...] Let xi be an lvalue denoting the ith element [...]
7628     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7629     Expr *Args[] = {&Xi, &Xi};
7630 
7631     // All operators start by trying to apply that same operator recursively.
7632     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7633     assert(OO != OO_None && "not an overloaded operator!");
7634     return visitBinaryOperator(OO, Args, Subobj);
7635   }
7636 
7637   Result
7638   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7639                       Subobject Subobj,
7640                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7641     // Note that there is no need to consider rewritten candidates here if
7642     // we've already found there is no viable 'operator<=>' candidate (and are
7643     // considering synthesizing a '<=>' from '==' and '<').
7644     OverloadCandidateSet CandidateSet(
7645         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7646         OverloadCandidateSet::OperatorRewriteInfo(
7647             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7648 
7649     /// C++2a [class.compare.default]p1 [P2002R0]:
7650     ///   [...] the defaulted function itself is never a candidate for overload
7651     ///   resolution [...]
7652     CandidateSet.exclude(FD);
7653 
7654     if (Args[0]->getType()->isOverloadableType())
7655       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7656     else {
7657       // FIXME: We determine whether this is a valid expression by checking to
7658       // see if there's a viable builtin operator candidate for it. That isn't
7659       // really what the rules ask us to do, but should give the right results.
7660       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7661     }
7662 
7663     Result R;
7664 
7665     OverloadCandidateSet::iterator Best;
7666     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7667     case OR_Success: {
7668       // C++2a [class.compare.secondary]p2 [P2002R0]:
7669       //   The operator function [...] is defined as deleted if [...] the
7670       //   candidate selected by overload resolution is not a rewritten
7671       //   candidate.
7672       if ((DCK == DefaultedComparisonKind::NotEqual ||
7673            DCK == DefaultedComparisonKind::Relational) &&
7674           !Best->RewriteKind) {
7675         if (Diagnose == ExplainDeleted) {
7676           S.Diag(Best->Function->getLocation(),
7677                  diag::note_defaulted_comparison_not_rewritten_callee)
7678               << FD;
7679         }
7680         return Result::deleted();
7681       }
7682 
7683       // Throughout C++2a [class.compare]: if overload resolution does not
7684       // result in a usable function, the candidate function is defined as
7685       // deleted. This requires that we selected an accessible function.
7686       //
7687       // Note that this only considers the access of the function when named
7688       // within the type of the subobject, and not the access path for any
7689       // derived-to-base conversion.
7690       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7691       if (ArgClass && Best->FoundDecl.getDecl() &&
7692           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7693         QualType ObjectType = Subobj.Kind == Subobject::Member
7694                                   ? Args[0]->getType()
7695                                   : S.Context.getRecordType(RD);
7696         if (!S.isMemberAccessibleForDeletion(
7697                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7698                 Diagnose == ExplainDeleted
7699                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7700                           << FD << Subobj.Kind << Subobj.Decl
7701                     : S.PDiag()))
7702           return Result::deleted();
7703       }
7704 
7705       // C++2a [class.compare.default]p3 [P2002R0]:
7706       //   A defaulted comparison function is constexpr-compatible if [...]
7707       //   no overlod resolution performed [...] results in a non-constexpr
7708       //   function.
7709       if (FunctionDecl *BestFD = Best->Function) {
7710         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7711         // If it's not constexpr, explain why not.
7712         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7713           if (Subobj.Kind != Subobject::CompleteObject)
7714             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7715               << Subobj.Kind << Subobj.Decl;
7716           S.Diag(BestFD->getLocation(),
7717                  diag::note_defaulted_comparison_not_constexpr_here);
7718           // Bail out after explaining; we don't want any more notes.
7719           return Result::deleted();
7720         }
7721         R.Constexpr &= BestFD->isConstexpr();
7722       }
7723 
7724       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7725         if (auto *BestFD = Best->Function) {
7726           // If any callee has an undeduced return type, deduce it now.
7727           // FIXME: It's not clear how a failure here should be handled. For
7728           // now, we produce an eager diagnostic, because that is forward
7729           // compatible with most (all?) other reasonable options.
7730           if (BestFD->getReturnType()->isUndeducedType() &&
7731               S.DeduceReturnType(BestFD, FD->getLocation(),
7732                                  /*Diagnose=*/false)) {
7733             // Don't produce a duplicate error when asked to explain why the
7734             // comparison is deleted: we diagnosed that when initially checking
7735             // the defaulted operator.
7736             if (Diagnose == NoDiagnostics) {
7737               S.Diag(
7738                   FD->getLocation(),
7739                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7740                   << Subobj.Kind << Subobj.Decl;
7741               S.Diag(
7742                   Subobj.Loc,
7743                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7744                   << Subobj.Kind << Subobj.Decl;
7745               S.Diag(BestFD->getLocation(),
7746                      diag::note_defaulted_comparison_cannot_deduce_callee)
7747                   << Subobj.Kind << Subobj.Decl;
7748             }
7749             return Result::deleted();
7750           }
7751           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7752               BestFD->getCallResultType())) {
7753             R.Category = Info->Kind;
7754           } else {
7755             if (Diagnose == ExplainDeleted) {
7756               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7757                   << Subobj.Kind << Subobj.Decl
7758                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7759               S.Diag(BestFD->getLocation(),
7760                      diag::note_defaulted_comparison_cannot_deduce_callee)
7761                   << Subobj.Kind << Subobj.Decl;
7762             }
7763             return Result::deleted();
7764           }
7765         } else {
7766           Optional<ComparisonCategoryType> Cat =
7767               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7768           assert(Cat && "no category for builtin comparison?");
7769           R.Category = *Cat;
7770         }
7771       }
7772 
7773       // Note that we might be rewriting to a different operator. That call is
7774       // not considered until we come to actually build the comparison function.
7775       break;
7776     }
7777 
7778     case OR_Ambiguous:
7779       if (Diagnose == ExplainDeleted) {
7780         unsigned Kind = 0;
7781         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7782           Kind = OO == OO_EqualEqual ? 1 : 2;
7783         CandidateSet.NoteCandidates(
7784             PartialDiagnosticAt(
7785                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7786                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7787             S, OCD_AmbiguousCandidates, Args);
7788       }
7789       R = Result::deleted();
7790       break;
7791 
7792     case OR_Deleted:
7793       if (Diagnose == ExplainDeleted) {
7794         if ((DCK == DefaultedComparisonKind::NotEqual ||
7795              DCK == DefaultedComparisonKind::Relational) &&
7796             !Best->RewriteKind) {
7797           S.Diag(Best->Function->getLocation(),
7798                  diag::note_defaulted_comparison_not_rewritten_callee)
7799               << FD;
7800         } else {
7801           S.Diag(Subobj.Loc,
7802                  diag::note_defaulted_comparison_calls_deleted)
7803               << FD << Subobj.Kind << Subobj.Decl;
7804           S.NoteDeletedFunction(Best->Function);
7805         }
7806       }
7807       R = Result::deleted();
7808       break;
7809 
7810     case OR_No_Viable_Function:
7811       // If there's no usable candidate, we're done unless we can rewrite a
7812       // '<=>' in terms of '==' and '<'.
7813       if (OO == OO_Spaceship &&
7814           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7815         // For any kind of comparison category return type, we need a usable
7816         // '==' and a usable '<'.
7817         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7818                                        &CandidateSet)))
7819           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7820         break;
7821       }
7822 
7823       if (Diagnose == ExplainDeleted) {
7824         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7825             << FD << Subobj.Kind << Subobj.Decl;
7826 
7827         // For a three-way comparison, list both the candidates for the
7828         // original operator and the candidates for the synthesized operator.
7829         if (SpaceshipCandidates) {
7830           SpaceshipCandidates->NoteCandidates(
7831               S, Args,
7832               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7833                                                       Args, FD->getLocation()));
7834           S.Diag(Subobj.Loc,
7835                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7836               << (OO == OO_EqualEqual ? 0 : 1);
7837         }
7838 
7839         CandidateSet.NoteCandidates(
7840             S, Args,
7841             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7842                                             FD->getLocation()));
7843       }
7844       R = Result::deleted();
7845       break;
7846     }
7847 
7848     return R;
7849   }
7850 };
7851 
7852 /// A list of statements.
7853 struct StmtListResult {
7854   bool IsInvalid = false;
7855   llvm::SmallVector<Stmt*, 16> Stmts;
7856 
7857   bool add(const StmtResult &S) {
7858     IsInvalid |= S.isInvalid();
7859     if (IsInvalid)
7860       return true;
7861     Stmts.push_back(S.get());
7862     return false;
7863   }
7864 };
7865 
7866 /// A visitor over the notional body of a defaulted comparison that synthesizes
7867 /// the actual body.
7868 class DefaultedComparisonSynthesizer
7869     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7870                                         StmtListResult, StmtResult,
7871                                         std::pair<ExprResult, ExprResult>> {
7872   SourceLocation Loc;
7873   unsigned ArrayDepth = 0;
7874 
7875 public:
7876   using Base = DefaultedComparisonVisitor;
7877   using ExprPair = std::pair<ExprResult, ExprResult>;
7878 
7879   friend Base;
7880 
7881   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7882                                  DefaultedComparisonKind DCK,
7883                                  SourceLocation BodyLoc)
7884       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7885 
7886   /// Build a suitable function body for this defaulted comparison operator.
7887   StmtResult build() {
7888     Sema::CompoundScopeRAII CompoundScope(S);
7889 
7890     StmtListResult Stmts = visit();
7891     if (Stmts.IsInvalid)
7892       return StmtError();
7893 
7894     ExprResult RetVal;
7895     switch (DCK) {
7896     case DefaultedComparisonKind::None:
7897       llvm_unreachable("not a defaulted comparison");
7898 
7899     case DefaultedComparisonKind::Equal: {
7900       // C++2a [class.eq]p3:
7901       //   [...] compar[e] the corresponding elements [...] until the first
7902       //   index i where xi == yi yields [...] false. If no such index exists,
7903       //   V is true. Otherwise, V is false.
7904       //
7905       // Join the comparisons with '&&'s and return the result. Use a right
7906       // fold (traversing the conditions right-to-left), because that
7907       // short-circuits more naturally.
7908       auto OldStmts = std::move(Stmts.Stmts);
7909       Stmts.Stmts.clear();
7910       ExprResult CmpSoFar;
7911       // Finish a particular comparison chain.
7912       auto FinishCmp = [&] {
7913         if (Expr *Prior = CmpSoFar.get()) {
7914           // Convert the last expression to 'return ...;'
7915           if (RetVal.isUnset() && Stmts.Stmts.empty())
7916             RetVal = CmpSoFar;
7917           // Convert any prior comparison to 'if (!(...)) return false;'
7918           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7919             return true;
7920           CmpSoFar = ExprResult();
7921         }
7922         return false;
7923       };
7924       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7925         Expr *E = dyn_cast<Expr>(EAsStmt);
7926         if (!E) {
7927           // Found an array comparison.
7928           if (FinishCmp() || Stmts.add(EAsStmt))
7929             return StmtError();
7930           continue;
7931         }
7932 
7933         if (CmpSoFar.isUnset()) {
7934           CmpSoFar = E;
7935           continue;
7936         }
7937         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7938         if (CmpSoFar.isInvalid())
7939           return StmtError();
7940       }
7941       if (FinishCmp())
7942         return StmtError();
7943       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7944       //   If no such index exists, V is true.
7945       if (RetVal.isUnset())
7946         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7947       break;
7948     }
7949 
7950     case DefaultedComparisonKind::ThreeWay: {
7951       // Per C++2a [class.spaceship]p3, as a fallback add:
7952       // return static_cast<R>(std::strong_ordering::equal);
7953       QualType StrongOrdering = S.CheckComparisonCategoryType(
7954           ComparisonCategoryType::StrongOrdering, Loc,
7955           Sema::ComparisonCategoryUsage::DefaultedOperator);
7956       if (StrongOrdering.isNull())
7957         return StmtError();
7958       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7959                              .getValueInfo(ComparisonCategoryResult::Equal)
7960                              ->VD;
7961       RetVal = getDecl(EqualVD);
7962       if (RetVal.isInvalid())
7963         return StmtError();
7964       RetVal = buildStaticCastToR(RetVal.get());
7965       break;
7966     }
7967 
7968     case DefaultedComparisonKind::NotEqual:
7969     case DefaultedComparisonKind::Relational:
7970       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7971       break;
7972     }
7973 
7974     // Build the final return statement.
7975     if (RetVal.isInvalid())
7976       return StmtError();
7977     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7978     if (ReturnStmt.isInvalid())
7979       return StmtError();
7980     Stmts.Stmts.push_back(ReturnStmt.get());
7981 
7982     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7983   }
7984 
7985 private:
7986   ExprResult getDecl(ValueDecl *VD) {
7987     return S.BuildDeclarationNameExpr(
7988         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7989   }
7990 
7991   ExprResult getParam(unsigned I) {
7992     ParmVarDecl *PD = FD->getParamDecl(I);
7993     return getDecl(PD);
7994   }
7995 
7996   ExprPair getCompleteObject() {
7997     unsigned Param = 0;
7998     ExprResult LHS;
7999     if (isa<CXXMethodDecl>(FD)) {
8000       // LHS is '*this'.
8001       LHS = S.ActOnCXXThis(Loc);
8002       if (!LHS.isInvalid())
8003         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8004     } else {
8005       LHS = getParam(Param++);
8006     }
8007     ExprResult RHS = getParam(Param++);
8008     assert(Param == FD->getNumParams());
8009     return {LHS, RHS};
8010   }
8011 
8012   ExprPair getBase(CXXBaseSpecifier *Base) {
8013     ExprPair Obj = getCompleteObject();
8014     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8015       return {ExprError(), ExprError()};
8016     CXXCastPath Path = {Base};
8017     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8018                                 CK_DerivedToBase, VK_LValue, &Path),
8019             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8020                                 CK_DerivedToBase, VK_LValue, &Path)};
8021   }
8022 
8023   ExprPair getField(FieldDecl *Field) {
8024     ExprPair Obj = getCompleteObject();
8025     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8026       return {ExprError(), ExprError()};
8027 
8028     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8029     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8030     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8031                                       CXXScopeSpec(), Field, Found, NameInfo),
8032             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8033                                       CXXScopeSpec(), Field, Found, NameInfo)};
8034   }
8035 
8036   // FIXME: When expanding a subobject, register a note in the code synthesis
8037   // stack to say which subobject we're comparing.
8038 
8039   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8040     if (Cond.isInvalid())
8041       return StmtError();
8042 
8043     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8044     if (NotCond.isInvalid())
8045       return StmtError();
8046 
8047     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8048     assert(!False.isInvalid() && "should never fail");
8049     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8050     if (ReturnFalse.isInvalid())
8051       return StmtError();
8052 
8053     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8054                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8055                                           Sema::ConditionKind::Boolean),
8056                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8057   }
8058 
8059   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8060                                  ExprPair Subobj) {
8061     QualType SizeType = S.Context.getSizeType();
8062     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8063 
8064     // Build 'size_t i$n = 0'.
8065     IdentifierInfo *IterationVarName = nullptr;
8066     {
8067       SmallString<8> Str;
8068       llvm::raw_svector_ostream OS(Str);
8069       OS << "i" << ArrayDepth;
8070       IterationVarName = &S.Context.Idents.get(OS.str());
8071     }
8072     VarDecl *IterationVar = VarDecl::Create(
8073         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8074         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8075     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8076     IterationVar->setInit(
8077         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8078     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8079 
8080     auto IterRef = [&] {
8081       ExprResult Ref = S.BuildDeclarationNameExpr(
8082           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8083           IterationVar);
8084       assert(!Ref.isInvalid() && "can't reference our own variable?");
8085       return Ref.get();
8086     };
8087 
8088     // Build 'i$n != Size'.
8089     ExprResult Cond = S.CreateBuiltinBinOp(
8090         Loc, BO_NE, IterRef(),
8091         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8092     assert(!Cond.isInvalid() && "should never fail");
8093 
8094     // Build '++i$n'.
8095     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8096     assert(!Inc.isInvalid() && "should never fail");
8097 
8098     // Build 'a[i$n]' and 'b[i$n]'.
8099     auto Index = [&](ExprResult E) {
8100       if (E.isInvalid())
8101         return ExprError();
8102       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8103     };
8104     Subobj.first = Index(Subobj.first);
8105     Subobj.second = Index(Subobj.second);
8106 
8107     // Compare the array elements.
8108     ++ArrayDepth;
8109     StmtResult Substmt = visitSubobject(Type, Subobj);
8110     --ArrayDepth;
8111 
8112     if (Substmt.isInvalid())
8113       return StmtError();
8114 
8115     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8116     // For outer levels or for an 'operator<=>' we already have a suitable
8117     // statement that returns as necessary.
8118     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8119       assert(DCK == DefaultedComparisonKind::Equal &&
8120              "should have non-expression statement");
8121       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8122       if (Substmt.isInvalid())
8123         return StmtError();
8124     }
8125 
8126     // Build 'for (...) ...'
8127     return S.ActOnForStmt(Loc, Loc, Init,
8128                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8129                                            Sema::ConditionKind::Boolean),
8130                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8131                           Substmt.get());
8132   }
8133 
8134   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8135     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8136       return StmtError();
8137 
8138     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8139     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8140     ExprResult Op;
8141     if (Type->isOverloadableType())
8142       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8143                                    Obj.second.get(), /*PerformADL=*/true,
8144                                    /*AllowRewrittenCandidates=*/true, FD);
8145     else
8146       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8147     if (Op.isInvalid())
8148       return StmtError();
8149 
8150     switch (DCK) {
8151     case DefaultedComparisonKind::None:
8152       llvm_unreachable("not a defaulted comparison");
8153 
8154     case DefaultedComparisonKind::Equal:
8155       // Per C++2a [class.eq]p2, each comparison is individually contextually
8156       // converted to bool.
8157       Op = S.PerformContextuallyConvertToBool(Op.get());
8158       if (Op.isInvalid())
8159         return StmtError();
8160       return Op.get();
8161 
8162     case DefaultedComparisonKind::ThreeWay: {
8163       // Per C++2a [class.spaceship]p3, form:
8164       //   if (R cmp = static_cast<R>(op); cmp != 0)
8165       //     return cmp;
8166       QualType R = FD->getReturnType();
8167       Op = buildStaticCastToR(Op.get());
8168       if (Op.isInvalid())
8169         return StmtError();
8170 
8171       // R cmp = ...;
8172       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8173       VarDecl *VD =
8174           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8175                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8176       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8177       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8178 
8179       // cmp != 0
8180       ExprResult VDRef = getDecl(VD);
8181       if (VDRef.isInvalid())
8182         return StmtError();
8183       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8184       Expr *Zero =
8185           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8186       ExprResult Comp;
8187       if (VDRef.get()->getType()->isOverloadableType())
8188         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8189                                        true, FD);
8190       else
8191         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8192       if (Comp.isInvalid())
8193         return StmtError();
8194       Sema::ConditionResult Cond = S.ActOnCondition(
8195           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8196       if (Cond.isInvalid())
8197         return StmtError();
8198 
8199       // return cmp;
8200       VDRef = getDecl(VD);
8201       if (VDRef.isInvalid())
8202         return StmtError();
8203       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8204       if (ReturnStmt.isInvalid())
8205         return StmtError();
8206 
8207       // if (...)
8208       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8209                            ReturnStmt.get(),
8210                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8211     }
8212 
8213     case DefaultedComparisonKind::NotEqual:
8214     case DefaultedComparisonKind::Relational:
8215       // C++2a [class.compare.secondary]p2:
8216       //   Otherwise, the operator function yields x @ y.
8217       return Op.get();
8218     }
8219     llvm_unreachable("");
8220   }
8221 
8222   /// Build "static_cast<R>(E)".
8223   ExprResult buildStaticCastToR(Expr *E) {
8224     QualType R = FD->getReturnType();
8225     assert(!R->isUndeducedType() && "type should have been deduced already");
8226 
8227     // Don't bother forming a no-op cast in the common case.
8228     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8229       return E;
8230     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8231                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8232                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8233   }
8234 };
8235 }
8236 
8237 /// Perform the unqualified lookups that might be needed to form a defaulted
8238 /// comparison function for the given operator.
8239 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8240                                                   UnresolvedSetImpl &Operators,
8241                                                   OverloadedOperatorKind Op) {
8242   auto Lookup = [&](OverloadedOperatorKind OO) {
8243     Self.LookupOverloadedOperatorName(OO, S, Operators);
8244   };
8245 
8246   // Every defaulted operator looks up itself.
8247   Lookup(Op);
8248   // ... and the rewritten form of itself, if any.
8249   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8250     Lookup(ExtraOp);
8251 
8252   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8253   // synthesize a three-way comparison from '<' and '=='. In a dependent
8254   // context, we also need to look up '==' in case we implicitly declare a
8255   // defaulted 'operator=='.
8256   if (Op == OO_Spaceship) {
8257     Lookup(OO_ExclaimEqual);
8258     Lookup(OO_Less);
8259     Lookup(OO_EqualEqual);
8260   }
8261 }
8262 
8263 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8264                                               DefaultedComparisonKind DCK) {
8265   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8266 
8267   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8268   assert(RD && "defaulted comparison is not defaulted in a class");
8269 
8270   // Perform any unqualified lookups we're going to need to default this
8271   // function.
8272   if (S) {
8273     UnresolvedSet<32> Operators;
8274     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8275                                           FD->getOverloadedOperator());
8276     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8277         Context, Operators.pairs()));
8278   }
8279 
8280   // C++2a [class.compare.default]p1:
8281   //   A defaulted comparison operator function for some class C shall be a
8282   //   non-template function declared in the member-specification of C that is
8283   //    -- a non-static const member of C having one parameter of type
8284   //       const C&, or
8285   //    -- a friend of C having two parameters of type const C& or two
8286   //       parameters of type C.
8287   QualType ExpectedParmType1 = Context.getRecordType(RD);
8288   QualType ExpectedParmType2 =
8289       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8290   if (isa<CXXMethodDecl>(FD))
8291     ExpectedParmType1 = ExpectedParmType2;
8292   for (const ParmVarDecl *Param : FD->parameters()) {
8293     if (!Param->getType()->isDependentType() &&
8294         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8295         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8296       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8297       // corresponding defaulted 'operator<=>' already.
8298       if (!FD->isImplicit()) {
8299         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8300             << (int)DCK << Param->getType() << ExpectedParmType1
8301             << !isa<CXXMethodDecl>(FD)
8302             << ExpectedParmType2 << Param->getSourceRange();
8303       }
8304       return true;
8305     }
8306   }
8307   if (FD->getNumParams() == 2 &&
8308       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8309                            FD->getParamDecl(1)->getType())) {
8310     if (!FD->isImplicit()) {
8311       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8312           << (int)DCK
8313           << FD->getParamDecl(0)->getType()
8314           << FD->getParamDecl(0)->getSourceRange()
8315           << FD->getParamDecl(1)->getType()
8316           << FD->getParamDecl(1)->getSourceRange();
8317     }
8318     return true;
8319   }
8320 
8321   // ... non-static const member ...
8322   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8323     assert(!MD->isStatic() && "comparison function cannot be a static member");
8324     if (!MD->isConst()) {
8325       SourceLocation InsertLoc;
8326       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8327         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8328       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8329       // corresponding defaulted 'operator<=>' already.
8330       if (!MD->isImplicit()) {
8331         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8332           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8333       }
8334 
8335       // Add the 'const' to the type to recover.
8336       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8337       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8338       EPI.TypeQuals.addConst();
8339       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8340                                           FPT->getParamTypes(), EPI));
8341     }
8342   } else {
8343     // A non-member function declared in a class must be a friend.
8344     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8345   }
8346 
8347   // C++2a [class.eq]p1, [class.rel]p1:
8348   //   A [defaulted comparison other than <=>] shall have a declared return
8349   //   type bool.
8350   if (DCK != DefaultedComparisonKind::ThreeWay &&
8351       !FD->getDeclaredReturnType()->isDependentType() &&
8352       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8353     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8354         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8355         << FD->getReturnTypeSourceRange();
8356     return true;
8357   }
8358   // C++2a [class.spaceship]p2 [P2002R0]:
8359   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8360   //   R shall not contain a placeholder type.
8361   if (DCK == DefaultedComparisonKind::ThreeWay &&
8362       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8363       !Context.hasSameType(FD->getDeclaredReturnType(),
8364                            Context.getAutoDeductType())) {
8365     Diag(FD->getLocation(),
8366          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8367         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8368         << FD->getReturnTypeSourceRange();
8369     return true;
8370   }
8371 
8372   // For a defaulted function in a dependent class, defer all remaining checks
8373   // until instantiation.
8374   if (RD->isDependentType())
8375     return false;
8376 
8377   // Determine whether the function should be defined as deleted.
8378   DefaultedComparisonInfo Info =
8379       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8380 
8381   bool First = FD == FD->getCanonicalDecl();
8382 
8383   // If we want to delete the function, then do so; there's nothing else to
8384   // check in that case.
8385   if (Info.Deleted) {
8386     if (!First) {
8387       // C++11 [dcl.fct.def.default]p4:
8388       //   [For a] user-provided explicitly-defaulted function [...] if such a
8389       //   function is implicitly defined as deleted, the program is ill-formed.
8390       //
8391       // This is really just a consequence of the general rule that you can
8392       // only delete a function on its first declaration.
8393       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8394           << FD->isImplicit() << (int)DCK;
8395       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8396                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8397           .visit();
8398       return true;
8399     }
8400 
8401     SetDeclDeleted(FD, FD->getLocation());
8402     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8403       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8404           << (int)DCK;
8405       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8406                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8407           .visit();
8408     }
8409     return false;
8410   }
8411 
8412   // C++2a [class.spaceship]p2:
8413   //   The return type is deduced as the common comparison type of R0, R1, ...
8414   if (DCK == DefaultedComparisonKind::ThreeWay &&
8415       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8416     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8417     if (RetLoc.isInvalid())
8418       RetLoc = FD->getBeginLoc();
8419     // FIXME: Should we really care whether we have the complete type and the
8420     // 'enumerator' constants here? A forward declaration seems sufficient.
8421     QualType Cat = CheckComparisonCategoryType(
8422         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8423     if (Cat.isNull())
8424       return true;
8425     Context.adjustDeducedFunctionResultType(
8426         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8427   }
8428 
8429   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8430   //   An explicitly-defaulted function that is not defined as deleted may be
8431   //   declared constexpr or consteval only if it is constexpr-compatible.
8432   // C++2a [class.compare.default]p3 [P2002R0]:
8433   //   A defaulted comparison function is constexpr-compatible if it satisfies
8434   //   the requirements for a constexpr function [...]
8435   // The only relevant requirements are that the parameter and return types are
8436   // literal types. The remaining conditions are checked by the analyzer.
8437   if (FD->isConstexpr()) {
8438     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8439         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8440         !Info.Constexpr) {
8441       Diag(FD->getBeginLoc(),
8442            diag::err_incorrect_defaulted_comparison_constexpr)
8443           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8444       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8445                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8446           .visit();
8447     }
8448   }
8449 
8450   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8451   //   If a constexpr-compatible function is explicitly defaulted on its first
8452   //   declaration, it is implicitly considered to be constexpr.
8453   // FIXME: Only applying this to the first declaration seems problematic, as
8454   // simple reorderings can affect the meaning of the program.
8455   if (First && !FD->isConstexpr() && Info.Constexpr)
8456     FD->setConstexprKind(CSK_constexpr);
8457 
8458   // C++2a [except.spec]p3:
8459   //   If a declaration of a function does not have a noexcept-specifier
8460   //   [and] is defaulted on its first declaration, [...] the exception
8461   //   specification is as specified below
8462   if (FD->getExceptionSpecType() == EST_None) {
8463     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8464     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8465     EPI.ExceptionSpec.Type = EST_Unevaluated;
8466     EPI.ExceptionSpec.SourceDecl = FD;
8467     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8468                                         FPT->getParamTypes(), EPI));
8469   }
8470 
8471   return false;
8472 }
8473 
8474 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8475                                              FunctionDecl *Spaceship) {
8476   Sema::CodeSynthesisContext Ctx;
8477   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8478   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8479   Ctx.Entity = Spaceship;
8480   pushCodeSynthesisContext(Ctx);
8481 
8482   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8483     EqualEqual->setImplicit();
8484 
8485   popCodeSynthesisContext();
8486 }
8487 
8488 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8489                                      DefaultedComparisonKind DCK) {
8490   assert(FD->isDefaulted() && !FD->isDeleted() &&
8491          !FD->doesThisDeclarationHaveABody());
8492   if (FD->willHaveBody() || FD->isInvalidDecl())
8493     return;
8494 
8495   SynthesizedFunctionScope Scope(*this, FD);
8496 
8497   // Add a context note for diagnostics produced after this point.
8498   Scope.addContextNote(UseLoc);
8499 
8500   {
8501     // Build and set up the function body.
8502     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8503     SourceLocation BodyLoc =
8504         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8505     StmtResult Body =
8506         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8507     if (Body.isInvalid()) {
8508       FD->setInvalidDecl();
8509       return;
8510     }
8511     FD->setBody(Body.get());
8512     FD->markUsed(Context);
8513   }
8514 
8515   // The exception specification is needed because we are defining the
8516   // function. Note that this will reuse the body we just built.
8517   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8518 
8519   if (ASTMutationListener *L = getASTMutationListener())
8520     L->CompletedImplicitDefinition(FD);
8521 }
8522 
8523 static Sema::ImplicitExceptionSpecification
8524 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8525                                         FunctionDecl *FD,
8526                                         Sema::DefaultedComparisonKind DCK) {
8527   ComputingExceptionSpec CES(S, FD, Loc);
8528   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8529 
8530   if (FD->isInvalidDecl())
8531     return ExceptSpec;
8532 
8533   // The common case is that we just defined the comparison function. In that
8534   // case, just look at whether the body can throw.
8535   if (FD->hasBody()) {
8536     ExceptSpec.CalledStmt(FD->getBody());
8537   } else {
8538     // Otherwise, build a body so we can check it. This should ideally only
8539     // happen when we're not actually marking the function referenced. (This is
8540     // only really important for efficiency: we don't want to build and throw
8541     // away bodies for comparison functions more than we strictly need to.)
8542 
8543     // Pretend to synthesize the function body in an unevaluated context.
8544     // Note that we can't actually just go ahead and define the function here:
8545     // we are not permitted to mark its callees as referenced.
8546     Sema::SynthesizedFunctionScope Scope(S, FD);
8547     EnterExpressionEvaluationContext Context(
8548         S, Sema::ExpressionEvaluationContext::Unevaluated);
8549 
8550     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8551     SourceLocation BodyLoc =
8552         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8553     StmtResult Body =
8554         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8555     if (!Body.isInvalid())
8556       ExceptSpec.CalledStmt(Body.get());
8557 
8558     // FIXME: Can we hold onto this body and just transform it to potentially
8559     // evaluated when we're asked to define the function rather than rebuilding
8560     // it? Either that, or we should only build the bits of the body that we
8561     // need (the expressions, not the statements).
8562   }
8563 
8564   return ExceptSpec;
8565 }
8566 
8567 void Sema::CheckDelayedMemberExceptionSpecs() {
8568   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8569   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8570 
8571   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8572   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8573 
8574   // Perform any deferred checking of exception specifications for virtual
8575   // destructors.
8576   for (auto &Check : Overriding)
8577     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8578 
8579   // Perform any deferred checking of exception specifications for befriended
8580   // special members.
8581   for (auto &Check : Equivalent)
8582     CheckEquivalentExceptionSpec(Check.second, Check.first);
8583 }
8584 
8585 namespace {
8586 /// CRTP base class for visiting operations performed by a special member
8587 /// function (or inherited constructor).
8588 template<typename Derived>
8589 struct SpecialMemberVisitor {
8590   Sema &S;
8591   CXXMethodDecl *MD;
8592   Sema::CXXSpecialMember CSM;
8593   Sema::InheritedConstructorInfo *ICI;
8594 
8595   // Properties of the special member, computed for convenience.
8596   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8597 
8598   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8599                        Sema::InheritedConstructorInfo *ICI)
8600       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8601     switch (CSM) {
8602     case Sema::CXXDefaultConstructor:
8603     case Sema::CXXCopyConstructor:
8604     case Sema::CXXMoveConstructor:
8605       IsConstructor = true;
8606       break;
8607     case Sema::CXXCopyAssignment:
8608     case Sema::CXXMoveAssignment:
8609       IsAssignment = true;
8610       break;
8611     case Sema::CXXDestructor:
8612       break;
8613     case Sema::CXXInvalid:
8614       llvm_unreachable("invalid special member kind");
8615     }
8616 
8617     if (MD->getNumParams()) {
8618       if (const ReferenceType *RT =
8619               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8620         ConstArg = RT->getPointeeType().isConstQualified();
8621     }
8622   }
8623 
8624   Derived &getDerived() { return static_cast<Derived&>(*this); }
8625 
8626   /// Is this a "move" special member?
8627   bool isMove() const {
8628     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8629   }
8630 
8631   /// Look up the corresponding special member in the given class.
8632   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8633                                              unsigned Quals, bool IsMutable) {
8634     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8635                                        ConstArg && !IsMutable);
8636   }
8637 
8638   /// Look up the constructor for the specified base class to see if it's
8639   /// overridden due to this being an inherited constructor.
8640   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8641     if (!ICI)
8642       return {};
8643     assert(CSM == Sema::CXXDefaultConstructor);
8644     auto *BaseCtor =
8645       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8646     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8647       return MD;
8648     return {};
8649   }
8650 
8651   /// A base or member subobject.
8652   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8653 
8654   /// Get the location to use for a subobject in diagnostics.
8655   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8656     // FIXME: For an indirect virtual base, the direct base leading to
8657     // the indirect virtual base would be a more useful choice.
8658     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8659       return B->getBaseTypeLoc();
8660     else
8661       return Subobj.get<FieldDecl*>()->getLocation();
8662   }
8663 
8664   enum BasesToVisit {
8665     /// Visit all non-virtual (direct) bases.
8666     VisitNonVirtualBases,
8667     /// Visit all direct bases, virtual or not.
8668     VisitDirectBases,
8669     /// Visit all non-virtual bases, and all virtual bases if the class
8670     /// is not abstract.
8671     VisitPotentiallyConstructedBases,
8672     /// Visit all direct or virtual bases.
8673     VisitAllBases
8674   };
8675 
8676   // Visit the bases and members of the class.
8677   bool visit(BasesToVisit Bases) {
8678     CXXRecordDecl *RD = MD->getParent();
8679 
8680     if (Bases == VisitPotentiallyConstructedBases)
8681       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8682 
8683     for (auto &B : RD->bases())
8684       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8685           getDerived().visitBase(&B))
8686         return true;
8687 
8688     if (Bases == VisitAllBases)
8689       for (auto &B : RD->vbases())
8690         if (getDerived().visitBase(&B))
8691           return true;
8692 
8693     for (auto *F : RD->fields())
8694       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8695           getDerived().visitField(F))
8696         return true;
8697 
8698     return false;
8699   }
8700 };
8701 }
8702 
8703 namespace {
8704 struct SpecialMemberDeletionInfo
8705     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8706   bool Diagnose;
8707 
8708   SourceLocation Loc;
8709 
8710   bool AllFieldsAreConst;
8711 
8712   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8713                             Sema::CXXSpecialMember CSM,
8714                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8715       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8716         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8717 
8718   bool inUnion() const { return MD->getParent()->isUnion(); }
8719 
8720   Sema::CXXSpecialMember getEffectiveCSM() {
8721     return ICI ? Sema::CXXInvalid : CSM;
8722   }
8723 
8724   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8725 
8726   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8727   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8728 
8729   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8730   bool shouldDeleteForField(FieldDecl *FD);
8731   bool shouldDeleteForAllConstMembers();
8732 
8733   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8734                                      unsigned Quals);
8735   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8736                                     Sema::SpecialMemberOverloadResult SMOR,
8737                                     bool IsDtorCallInCtor);
8738 
8739   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8740 };
8741 }
8742 
8743 /// Is the given special member inaccessible when used on the given
8744 /// sub-object.
8745 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8746                                              CXXMethodDecl *target) {
8747   /// If we're operating on a base class, the object type is the
8748   /// type of this special member.
8749   QualType objectTy;
8750   AccessSpecifier access = target->getAccess();
8751   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8752     objectTy = S.Context.getTypeDeclType(MD->getParent());
8753     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8754 
8755   // If we're operating on a field, the object type is the type of the field.
8756   } else {
8757     objectTy = S.Context.getTypeDeclType(target->getParent());
8758   }
8759 
8760   return S.isMemberAccessibleForDeletion(
8761       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8762 }
8763 
8764 /// Check whether we should delete a special member due to the implicit
8765 /// definition containing a call to a special member of a subobject.
8766 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8767     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8768     bool IsDtorCallInCtor) {
8769   CXXMethodDecl *Decl = SMOR.getMethod();
8770   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8771 
8772   int DiagKind = -1;
8773 
8774   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8775     DiagKind = !Decl ? 0 : 1;
8776   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8777     DiagKind = 2;
8778   else if (!isAccessible(Subobj, Decl))
8779     DiagKind = 3;
8780   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8781            !Decl->isTrivial()) {
8782     // A member of a union must have a trivial corresponding special member.
8783     // As a weird special case, a destructor call from a union's constructor
8784     // must be accessible and non-deleted, but need not be trivial. Such a
8785     // destructor is never actually called, but is semantically checked as
8786     // if it were.
8787     DiagKind = 4;
8788   }
8789 
8790   if (DiagKind == -1)
8791     return false;
8792 
8793   if (Diagnose) {
8794     if (Field) {
8795       S.Diag(Field->getLocation(),
8796              diag::note_deleted_special_member_class_subobject)
8797         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8798         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8799     } else {
8800       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8801       S.Diag(Base->getBeginLoc(),
8802              diag::note_deleted_special_member_class_subobject)
8803           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8804           << Base->getType() << DiagKind << IsDtorCallInCtor
8805           << /*IsObjCPtr*/false;
8806     }
8807 
8808     if (DiagKind == 1)
8809       S.NoteDeletedFunction(Decl);
8810     // FIXME: Explain inaccessibility if DiagKind == 3.
8811   }
8812 
8813   return true;
8814 }
8815 
8816 /// Check whether we should delete a special member function due to having a
8817 /// direct or virtual base class or non-static data member of class type M.
8818 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8819     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8820   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8821   bool IsMutable = Field && Field->isMutable();
8822 
8823   // C++11 [class.ctor]p5:
8824   // -- any direct or virtual base class, or non-static data member with no
8825   //    brace-or-equal-initializer, has class type M (or array thereof) and
8826   //    either M has no default constructor or overload resolution as applied
8827   //    to M's default constructor results in an ambiguity or in a function
8828   //    that is deleted or inaccessible
8829   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8830   // -- a direct or virtual base class B that cannot be copied/moved because
8831   //    overload resolution, as applied to B's corresponding special member,
8832   //    results in an ambiguity or a function that is deleted or inaccessible
8833   //    from the defaulted special member
8834   // C++11 [class.dtor]p5:
8835   // -- any direct or virtual base class [...] has a type with a destructor
8836   //    that is deleted or inaccessible
8837   if (!(CSM == Sema::CXXDefaultConstructor &&
8838         Field && Field->hasInClassInitializer()) &&
8839       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8840                                    false))
8841     return true;
8842 
8843   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8844   // -- any direct or virtual base class or non-static data member has a
8845   //    type with a destructor that is deleted or inaccessible
8846   if (IsConstructor) {
8847     Sema::SpecialMemberOverloadResult SMOR =
8848         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8849                               false, false, false, false, false);
8850     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8851       return true;
8852   }
8853 
8854   return false;
8855 }
8856 
8857 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8858     FieldDecl *FD, QualType FieldType) {
8859   // The defaulted special functions are defined as deleted if this is a variant
8860   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8861   // type under ARC.
8862   if (!FieldType.hasNonTrivialObjCLifetime())
8863     return false;
8864 
8865   // Don't make the defaulted default constructor defined as deleted if the
8866   // member has an in-class initializer.
8867   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8868     return false;
8869 
8870   if (Diagnose) {
8871     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8872     S.Diag(FD->getLocation(),
8873            diag::note_deleted_special_member_class_subobject)
8874         << getEffectiveCSM() << ParentClass << /*IsField*/true
8875         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8876   }
8877 
8878   return true;
8879 }
8880 
8881 /// Check whether we should delete a special member function due to the class
8882 /// having a particular direct or virtual base class.
8883 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8884   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8885   // If program is correct, BaseClass cannot be null, but if it is, the error
8886   // must be reported elsewhere.
8887   if (!BaseClass)
8888     return false;
8889   // If we have an inheriting constructor, check whether we're calling an
8890   // inherited constructor instead of a default constructor.
8891   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8892   if (auto *BaseCtor = SMOR.getMethod()) {
8893     // Note that we do not check access along this path; other than that,
8894     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8895     // FIXME: Check that the base has a usable destructor! Sink this into
8896     // shouldDeleteForClassSubobject.
8897     if (BaseCtor->isDeleted() && Diagnose) {
8898       S.Diag(Base->getBeginLoc(),
8899              diag::note_deleted_special_member_class_subobject)
8900           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8901           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8902           << /*IsObjCPtr*/false;
8903       S.NoteDeletedFunction(BaseCtor);
8904     }
8905     return BaseCtor->isDeleted();
8906   }
8907   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8908 }
8909 
8910 /// Check whether we should delete a special member function due to the class
8911 /// having a particular non-static data member.
8912 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8913   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8914   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8915 
8916   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8917     return true;
8918 
8919   if (CSM == Sema::CXXDefaultConstructor) {
8920     // For a default constructor, all references must be initialized in-class
8921     // and, if a union, it must have a non-const member.
8922     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8923       if (Diagnose)
8924         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8925           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8926       return true;
8927     }
8928     // C++11 [class.ctor]p5: any non-variant non-static data member of
8929     // const-qualified type (or array thereof) with no
8930     // brace-or-equal-initializer does not have a user-provided default
8931     // constructor.
8932     if (!inUnion() && FieldType.isConstQualified() &&
8933         !FD->hasInClassInitializer() &&
8934         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8935       if (Diagnose)
8936         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8937           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8938       return true;
8939     }
8940 
8941     if (inUnion() && !FieldType.isConstQualified())
8942       AllFieldsAreConst = false;
8943   } else if (CSM == Sema::CXXCopyConstructor) {
8944     // For a copy constructor, data members must not be of rvalue reference
8945     // type.
8946     if (FieldType->isRValueReferenceType()) {
8947       if (Diagnose)
8948         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8949           << MD->getParent() << FD << FieldType;
8950       return true;
8951     }
8952   } else if (IsAssignment) {
8953     // For an assignment operator, data members must not be of reference type.
8954     if (FieldType->isReferenceType()) {
8955       if (Diagnose)
8956         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8957           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8958       return true;
8959     }
8960     if (!FieldRecord && FieldType.isConstQualified()) {
8961       // C++11 [class.copy]p23:
8962       // -- a non-static data member of const non-class type (or array thereof)
8963       if (Diagnose)
8964         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8965           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8966       return true;
8967     }
8968   }
8969 
8970   if (FieldRecord) {
8971     // Some additional restrictions exist on the variant members.
8972     if (!inUnion() && FieldRecord->isUnion() &&
8973         FieldRecord->isAnonymousStructOrUnion()) {
8974       bool AllVariantFieldsAreConst = true;
8975 
8976       // FIXME: Handle anonymous unions declared within anonymous unions.
8977       for (auto *UI : FieldRecord->fields()) {
8978         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8979 
8980         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8981           return true;
8982 
8983         if (!UnionFieldType.isConstQualified())
8984           AllVariantFieldsAreConst = false;
8985 
8986         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8987         if (UnionFieldRecord &&
8988             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8989                                           UnionFieldType.getCVRQualifiers()))
8990           return true;
8991       }
8992 
8993       // At least one member in each anonymous union must be non-const
8994       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8995           !FieldRecord->field_empty()) {
8996         if (Diagnose)
8997           S.Diag(FieldRecord->getLocation(),
8998                  diag::note_deleted_default_ctor_all_const)
8999             << !!ICI << MD->getParent() << /*anonymous union*/1;
9000         return true;
9001       }
9002 
9003       // Don't check the implicit member of the anonymous union type.
9004       // This is technically non-conformant, but sanity demands it.
9005       return false;
9006     }
9007 
9008     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9009                                       FieldType.getCVRQualifiers()))
9010       return true;
9011   }
9012 
9013   return false;
9014 }
9015 
9016 /// C++11 [class.ctor] p5:
9017 ///   A defaulted default constructor for a class X is defined as deleted if
9018 /// X is a union and all of its variant members are of const-qualified type.
9019 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9020   // This is a silly definition, because it gives an empty union a deleted
9021   // default constructor. Don't do that.
9022   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9023     bool AnyFields = false;
9024     for (auto *F : MD->getParent()->fields())
9025       if ((AnyFields = !F->isUnnamedBitfield()))
9026         break;
9027     if (!AnyFields)
9028       return false;
9029     if (Diagnose)
9030       S.Diag(MD->getParent()->getLocation(),
9031              diag::note_deleted_default_ctor_all_const)
9032         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9033     return true;
9034   }
9035   return false;
9036 }
9037 
9038 /// Determine whether a defaulted special member function should be defined as
9039 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9040 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9041 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9042                                      InheritedConstructorInfo *ICI,
9043                                      bool Diagnose) {
9044   if (MD->isInvalidDecl())
9045     return false;
9046   CXXRecordDecl *RD = MD->getParent();
9047   assert(!RD->isDependentType() && "do deletion after instantiation");
9048   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9049     return false;
9050 
9051   // C++11 [expr.lambda.prim]p19:
9052   //   The closure type associated with a lambda-expression has a
9053   //   deleted (8.4.3) default constructor and a deleted copy
9054   //   assignment operator.
9055   // C++2a adds back these operators if the lambda has no lambda-capture.
9056   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9057       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9058     if (Diagnose)
9059       Diag(RD->getLocation(), diag::note_lambda_decl);
9060     return true;
9061   }
9062 
9063   // For an anonymous struct or union, the copy and assignment special members
9064   // will never be used, so skip the check. For an anonymous union declared at
9065   // namespace scope, the constructor and destructor are used.
9066   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9067       RD->isAnonymousStructOrUnion())
9068     return false;
9069 
9070   // C++11 [class.copy]p7, p18:
9071   //   If the class definition declares a move constructor or move assignment
9072   //   operator, an implicitly declared copy constructor or copy assignment
9073   //   operator is defined as deleted.
9074   if (MD->isImplicit() &&
9075       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9076     CXXMethodDecl *UserDeclaredMove = nullptr;
9077 
9078     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9079     // deletion of the corresponding copy operation, not both copy operations.
9080     // MSVC 2015 has adopted the standards conforming behavior.
9081     bool DeletesOnlyMatchingCopy =
9082         getLangOpts().MSVCCompat &&
9083         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9084 
9085     if (RD->hasUserDeclaredMoveConstructor() &&
9086         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9087       if (!Diagnose) return true;
9088 
9089       // Find any user-declared move constructor.
9090       for (auto *I : RD->ctors()) {
9091         if (I->isMoveConstructor()) {
9092           UserDeclaredMove = I;
9093           break;
9094         }
9095       }
9096       assert(UserDeclaredMove);
9097     } else if (RD->hasUserDeclaredMoveAssignment() &&
9098                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9099       if (!Diagnose) return true;
9100 
9101       // Find any user-declared move assignment operator.
9102       for (auto *I : RD->methods()) {
9103         if (I->isMoveAssignmentOperator()) {
9104           UserDeclaredMove = I;
9105           break;
9106         }
9107       }
9108       assert(UserDeclaredMove);
9109     }
9110 
9111     if (UserDeclaredMove) {
9112       Diag(UserDeclaredMove->getLocation(),
9113            diag::note_deleted_copy_user_declared_move)
9114         << (CSM == CXXCopyAssignment) << RD
9115         << UserDeclaredMove->isMoveAssignmentOperator();
9116       return true;
9117     }
9118   }
9119 
9120   // Do access control from the special member function
9121   ContextRAII MethodContext(*this, MD);
9122 
9123   // C++11 [class.dtor]p5:
9124   // -- for a virtual destructor, lookup of the non-array deallocation function
9125   //    results in an ambiguity or in a function that is deleted or inaccessible
9126   if (CSM == CXXDestructor && MD->isVirtual()) {
9127     FunctionDecl *OperatorDelete = nullptr;
9128     DeclarationName Name =
9129       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9130     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9131                                  OperatorDelete, /*Diagnose*/false)) {
9132       if (Diagnose)
9133         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9134       return true;
9135     }
9136   }
9137 
9138   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9139 
9140   // Per DR1611, do not consider virtual bases of constructors of abstract
9141   // classes, since we are not going to construct them.
9142   // Per DR1658, do not consider virtual bases of destructors of abstract
9143   // classes either.
9144   // Per DR2180, for assignment operators we only assign (and thus only
9145   // consider) direct bases.
9146   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9147                                  : SMI.VisitPotentiallyConstructedBases))
9148     return true;
9149 
9150   if (SMI.shouldDeleteForAllConstMembers())
9151     return true;
9152 
9153   if (getLangOpts().CUDA) {
9154     // We should delete the special member in CUDA mode if target inference
9155     // failed.
9156     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9157     // is treated as certain special member, which may not reflect what special
9158     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9159     // expects CSM to match MD, therefore recalculate CSM.
9160     assert(ICI || CSM == getSpecialMember(MD));
9161     auto RealCSM = CSM;
9162     if (ICI)
9163       RealCSM = getSpecialMember(MD);
9164 
9165     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9166                                                    SMI.ConstArg, Diagnose);
9167   }
9168 
9169   return false;
9170 }
9171 
9172 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9173   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9174   assert(DFK && "not a defaultable function");
9175   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9176 
9177   if (DFK.isSpecialMember()) {
9178     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9179                               nullptr, /*Diagnose=*/true);
9180   } else {
9181     DefaultedComparisonAnalyzer(
9182         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9183         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9184         .visit();
9185   }
9186 }
9187 
9188 /// Perform lookup for a special member of the specified kind, and determine
9189 /// whether it is trivial. If the triviality can be determined without the
9190 /// lookup, skip it. This is intended for use when determining whether a
9191 /// special member of a containing object is trivial, and thus does not ever
9192 /// perform overload resolution for default constructors.
9193 ///
9194 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9195 /// member that was most likely to be intended to be trivial, if any.
9196 ///
9197 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9198 /// determine whether the special member is trivial.
9199 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9200                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9201                                      bool ConstRHS,
9202                                      Sema::TrivialABIHandling TAH,
9203                                      CXXMethodDecl **Selected) {
9204   if (Selected)
9205     *Selected = nullptr;
9206 
9207   switch (CSM) {
9208   case Sema::CXXInvalid:
9209     llvm_unreachable("not a special member");
9210 
9211   case Sema::CXXDefaultConstructor:
9212     // C++11 [class.ctor]p5:
9213     //   A default constructor is trivial if:
9214     //    - all the [direct subobjects] have trivial default constructors
9215     //
9216     // Note, no overload resolution is performed in this case.
9217     if (RD->hasTrivialDefaultConstructor())
9218       return true;
9219 
9220     if (Selected) {
9221       // If there's a default constructor which could have been trivial, dig it
9222       // out. Otherwise, if there's any user-provided default constructor, point
9223       // to that as an example of why there's not a trivial one.
9224       CXXConstructorDecl *DefCtor = nullptr;
9225       if (RD->needsImplicitDefaultConstructor())
9226         S.DeclareImplicitDefaultConstructor(RD);
9227       for (auto *CI : RD->ctors()) {
9228         if (!CI->isDefaultConstructor())
9229           continue;
9230         DefCtor = CI;
9231         if (!DefCtor->isUserProvided())
9232           break;
9233       }
9234 
9235       *Selected = DefCtor;
9236     }
9237 
9238     return false;
9239 
9240   case Sema::CXXDestructor:
9241     // C++11 [class.dtor]p5:
9242     //   A destructor is trivial if:
9243     //    - all the direct [subobjects] have trivial destructors
9244     if (RD->hasTrivialDestructor() ||
9245         (TAH == Sema::TAH_ConsiderTrivialABI &&
9246          RD->hasTrivialDestructorForCall()))
9247       return true;
9248 
9249     if (Selected) {
9250       if (RD->needsImplicitDestructor())
9251         S.DeclareImplicitDestructor(RD);
9252       *Selected = RD->getDestructor();
9253     }
9254 
9255     return false;
9256 
9257   case Sema::CXXCopyConstructor:
9258     // C++11 [class.copy]p12:
9259     //   A copy constructor is trivial if:
9260     //    - the constructor selected to copy each direct [subobject] is trivial
9261     if (RD->hasTrivialCopyConstructor() ||
9262         (TAH == Sema::TAH_ConsiderTrivialABI &&
9263          RD->hasTrivialCopyConstructorForCall())) {
9264       if (Quals == Qualifiers::Const)
9265         // We must either select the trivial copy constructor or reach an
9266         // ambiguity; no need to actually perform overload resolution.
9267         return true;
9268     } else if (!Selected) {
9269       return false;
9270     }
9271     // In C++98, we are not supposed to perform overload resolution here, but we
9272     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9273     // cases like B as having a non-trivial copy constructor:
9274     //   struct A { template<typename T> A(T&); };
9275     //   struct B { mutable A a; };
9276     goto NeedOverloadResolution;
9277 
9278   case Sema::CXXCopyAssignment:
9279     // C++11 [class.copy]p25:
9280     //   A copy assignment operator is trivial if:
9281     //    - the assignment operator selected to copy each direct [subobject] is
9282     //      trivial
9283     if (RD->hasTrivialCopyAssignment()) {
9284       if (Quals == Qualifiers::Const)
9285         return true;
9286     } else if (!Selected) {
9287       return false;
9288     }
9289     // In C++98, we are not supposed to perform overload resolution here, but we
9290     // treat that as a language defect.
9291     goto NeedOverloadResolution;
9292 
9293   case Sema::CXXMoveConstructor:
9294   case Sema::CXXMoveAssignment:
9295   NeedOverloadResolution:
9296     Sema::SpecialMemberOverloadResult SMOR =
9297         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9298 
9299     // The standard doesn't describe how to behave if the lookup is ambiguous.
9300     // We treat it as not making the member non-trivial, just like the standard
9301     // mandates for the default constructor. This should rarely matter, because
9302     // the member will also be deleted.
9303     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9304       return true;
9305 
9306     if (!SMOR.getMethod()) {
9307       assert(SMOR.getKind() ==
9308              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9309       return false;
9310     }
9311 
9312     // We deliberately don't check if we found a deleted special member. We're
9313     // not supposed to!
9314     if (Selected)
9315       *Selected = SMOR.getMethod();
9316 
9317     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9318         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9319       return SMOR.getMethod()->isTrivialForCall();
9320     return SMOR.getMethod()->isTrivial();
9321   }
9322 
9323   llvm_unreachable("unknown special method kind");
9324 }
9325 
9326 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9327   for (auto *CI : RD->ctors())
9328     if (!CI->isImplicit())
9329       return CI;
9330 
9331   // Look for constructor templates.
9332   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9333   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9334     if (CXXConstructorDecl *CD =
9335           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9336       return CD;
9337   }
9338 
9339   return nullptr;
9340 }
9341 
9342 /// The kind of subobject we are checking for triviality. The values of this
9343 /// enumeration are used in diagnostics.
9344 enum TrivialSubobjectKind {
9345   /// The subobject is a base class.
9346   TSK_BaseClass,
9347   /// The subobject is a non-static data member.
9348   TSK_Field,
9349   /// The object is actually the complete object.
9350   TSK_CompleteObject
9351 };
9352 
9353 /// Check whether the special member selected for a given type would be trivial.
9354 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9355                                       QualType SubType, bool ConstRHS,
9356                                       Sema::CXXSpecialMember CSM,
9357                                       TrivialSubobjectKind Kind,
9358                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9359   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9360   if (!SubRD)
9361     return true;
9362 
9363   CXXMethodDecl *Selected;
9364   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9365                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9366     return true;
9367 
9368   if (Diagnose) {
9369     if (ConstRHS)
9370       SubType.addConst();
9371 
9372     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9373       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9374         << Kind << SubType.getUnqualifiedType();
9375       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9376         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9377     } else if (!Selected)
9378       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9379         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9380     else if (Selected->isUserProvided()) {
9381       if (Kind == TSK_CompleteObject)
9382         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9383           << Kind << SubType.getUnqualifiedType() << CSM;
9384       else {
9385         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9386           << Kind << SubType.getUnqualifiedType() << CSM;
9387         S.Diag(Selected->getLocation(), diag::note_declared_at);
9388       }
9389     } else {
9390       if (Kind != TSK_CompleteObject)
9391         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9392           << Kind << SubType.getUnqualifiedType() << CSM;
9393 
9394       // Explain why the defaulted or deleted special member isn't trivial.
9395       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9396                                Diagnose);
9397     }
9398   }
9399 
9400   return false;
9401 }
9402 
9403 /// Check whether the members of a class type allow a special member to be
9404 /// trivial.
9405 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9406                                      Sema::CXXSpecialMember CSM,
9407                                      bool ConstArg,
9408                                      Sema::TrivialABIHandling TAH,
9409                                      bool Diagnose) {
9410   for (const auto *FI : RD->fields()) {
9411     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9412       continue;
9413 
9414     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9415 
9416     // Pretend anonymous struct or union members are members of this class.
9417     if (FI->isAnonymousStructOrUnion()) {
9418       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9419                                     CSM, ConstArg, TAH, Diagnose))
9420         return false;
9421       continue;
9422     }
9423 
9424     // C++11 [class.ctor]p5:
9425     //   A default constructor is trivial if [...]
9426     //    -- no non-static data member of its class has a
9427     //       brace-or-equal-initializer
9428     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9429       if (Diagnose)
9430         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9431             << FI;
9432       return false;
9433     }
9434 
9435     // Objective C ARC 4.3.5:
9436     //   [...] nontrivally ownership-qualified types are [...] not trivially
9437     //   default constructible, copy constructible, move constructible, copy
9438     //   assignable, move assignable, or destructible [...]
9439     if (FieldType.hasNonTrivialObjCLifetime()) {
9440       if (Diagnose)
9441         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9442           << RD << FieldType.getObjCLifetime();
9443       return false;
9444     }
9445 
9446     bool ConstRHS = ConstArg && !FI->isMutable();
9447     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9448                                    CSM, TSK_Field, TAH, Diagnose))
9449       return false;
9450   }
9451 
9452   return true;
9453 }
9454 
9455 /// Diagnose why the specified class does not have a trivial special member of
9456 /// the given kind.
9457 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9458   QualType Ty = Context.getRecordType(RD);
9459 
9460   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9461   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9462                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9463                             /*Diagnose*/true);
9464 }
9465 
9466 /// Determine whether a defaulted or deleted special member function is trivial,
9467 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9468 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9469 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9470                                   TrivialABIHandling TAH, bool Diagnose) {
9471   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9472 
9473   CXXRecordDecl *RD = MD->getParent();
9474 
9475   bool ConstArg = false;
9476 
9477   // C++11 [class.copy]p12, p25: [DR1593]
9478   //   A [special member] is trivial if [...] its parameter-type-list is
9479   //   equivalent to the parameter-type-list of an implicit declaration [...]
9480   switch (CSM) {
9481   case CXXDefaultConstructor:
9482   case CXXDestructor:
9483     // Trivial default constructors and destructors cannot have parameters.
9484     break;
9485 
9486   case CXXCopyConstructor:
9487   case CXXCopyAssignment: {
9488     // Trivial copy operations always have const, non-volatile parameter types.
9489     ConstArg = true;
9490     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9491     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9492     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9493       if (Diagnose)
9494         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9495           << Param0->getSourceRange() << Param0->getType()
9496           << Context.getLValueReferenceType(
9497                Context.getRecordType(RD).withConst());
9498       return false;
9499     }
9500     break;
9501   }
9502 
9503   case CXXMoveConstructor:
9504   case CXXMoveAssignment: {
9505     // Trivial move operations always have non-cv-qualified parameters.
9506     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9507     const RValueReferenceType *RT =
9508       Param0->getType()->getAs<RValueReferenceType>();
9509     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9510       if (Diagnose)
9511         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9512           << Param0->getSourceRange() << Param0->getType()
9513           << Context.getRValueReferenceType(Context.getRecordType(RD));
9514       return false;
9515     }
9516     break;
9517   }
9518 
9519   case CXXInvalid:
9520     llvm_unreachable("not a special member");
9521   }
9522 
9523   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9524     if (Diagnose)
9525       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9526            diag::note_nontrivial_default_arg)
9527         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9528     return false;
9529   }
9530   if (MD->isVariadic()) {
9531     if (Diagnose)
9532       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9533     return false;
9534   }
9535 
9536   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9537   //   A copy/move [constructor or assignment operator] is trivial if
9538   //    -- the [member] selected to copy/move each direct base class subobject
9539   //       is trivial
9540   //
9541   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9542   //   A [default constructor or destructor] is trivial if
9543   //    -- all the direct base classes have trivial [default constructors or
9544   //       destructors]
9545   for (const auto &BI : RD->bases())
9546     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9547                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9548       return false;
9549 
9550   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9551   //   A copy/move [constructor or assignment operator] for a class X is
9552   //   trivial if
9553   //    -- for each non-static data member of X that is of class type (or array
9554   //       thereof), the constructor selected to copy/move that member is
9555   //       trivial
9556   //
9557   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9558   //   A [default constructor or destructor] is trivial if
9559   //    -- for all of the non-static data members of its class that are of class
9560   //       type (or array thereof), each such class has a trivial [default
9561   //       constructor or destructor]
9562   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9563     return false;
9564 
9565   // C++11 [class.dtor]p5:
9566   //   A destructor is trivial if [...]
9567   //    -- the destructor is not virtual
9568   if (CSM == CXXDestructor && MD->isVirtual()) {
9569     if (Diagnose)
9570       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9571     return false;
9572   }
9573 
9574   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9575   //   A [special member] for class X is trivial if [...]
9576   //    -- class X has no virtual functions and no virtual base classes
9577   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9578     if (!Diagnose)
9579       return false;
9580 
9581     if (RD->getNumVBases()) {
9582       // Check for virtual bases. We already know that the corresponding
9583       // member in all bases is trivial, so vbases must all be direct.
9584       CXXBaseSpecifier &BS = *RD->vbases_begin();
9585       assert(BS.isVirtual());
9586       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9587       return false;
9588     }
9589 
9590     // Must have a virtual method.
9591     for (const auto *MI : RD->methods()) {
9592       if (MI->isVirtual()) {
9593         SourceLocation MLoc = MI->getBeginLoc();
9594         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9595         return false;
9596       }
9597     }
9598 
9599     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9600   }
9601 
9602   // Looks like it's trivial!
9603   return true;
9604 }
9605 
9606 namespace {
9607 struct FindHiddenVirtualMethod {
9608   Sema *S;
9609   CXXMethodDecl *Method;
9610   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9611   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9612 
9613 private:
9614   /// Check whether any most overridden method from MD in Methods
9615   static bool CheckMostOverridenMethods(
9616       const CXXMethodDecl *MD,
9617       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9618     if (MD->size_overridden_methods() == 0)
9619       return Methods.count(MD->getCanonicalDecl());
9620     for (const CXXMethodDecl *O : MD->overridden_methods())
9621       if (CheckMostOverridenMethods(O, Methods))
9622         return true;
9623     return false;
9624   }
9625 
9626 public:
9627   /// Member lookup function that determines whether a given C++
9628   /// method overloads virtual methods in a base class without overriding any,
9629   /// to be used with CXXRecordDecl::lookupInBases().
9630   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9631     RecordDecl *BaseRecord =
9632         Specifier->getType()->castAs<RecordType>()->getDecl();
9633 
9634     DeclarationName Name = Method->getDeclName();
9635     assert(Name.getNameKind() == DeclarationName::Identifier);
9636 
9637     bool foundSameNameMethod = false;
9638     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9639     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9640          Path.Decls = Path.Decls.slice(1)) {
9641       NamedDecl *D = Path.Decls.front();
9642       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9643         MD = MD->getCanonicalDecl();
9644         foundSameNameMethod = true;
9645         // Interested only in hidden virtual methods.
9646         if (!MD->isVirtual())
9647           continue;
9648         // If the method we are checking overrides a method from its base
9649         // don't warn about the other overloaded methods. Clang deviates from
9650         // GCC by only diagnosing overloads of inherited virtual functions that
9651         // do not override any other virtual functions in the base. GCC's
9652         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9653         // function from a base class. These cases may be better served by a
9654         // warning (not specific to virtual functions) on call sites when the
9655         // call would select a different function from the base class, were it
9656         // visible.
9657         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9658         if (!S->IsOverload(Method, MD, false))
9659           return true;
9660         // Collect the overload only if its hidden.
9661         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9662           overloadedMethods.push_back(MD);
9663       }
9664     }
9665 
9666     if (foundSameNameMethod)
9667       OverloadedMethods.append(overloadedMethods.begin(),
9668                                overloadedMethods.end());
9669     return foundSameNameMethod;
9670   }
9671 };
9672 } // end anonymous namespace
9673 
9674 /// Add the most overriden methods from MD to Methods
9675 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9676                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9677   if (MD->size_overridden_methods() == 0)
9678     Methods.insert(MD->getCanonicalDecl());
9679   else
9680     for (const CXXMethodDecl *O : MD->overridden_methods())
9681       AddMostOverridenMethods(O, Methods);
9682 }
9683 
9684 /// Check if a method overloads virtual methods in a base class without
9685 /// overriding any.
9686 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9687                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9688   if (!MD->getDeclName().isIdentifier())
9689     return;
9690 
9691   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9692                      /*bool RecordPaths=*/false,
9693                      /*bool DetectVirtual=*/false);
9694   FindHiddenVirtualMethod FHVM;
9695   FHVM.Method = MD;
9696   FHVM.S = this;
9697 
9698   // Keep the base methods that were overridden or introduced in the subclass
9699   // by 'using' in a set. A base method not in this set is hidden.
9700   CXXRecordDecl *DC = MD->getParent();
9701   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9702   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9703     NamedDecl *ND = *I;
9704     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9705       ND = shad->getTargetDecl();
9706     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9707       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9708   }
9709 
9710   if (DC->lookupInBases(FHVM, Paths))
9711     OverloadedMethods = FHVM.OverloadedMethods;
9712 }
9713 
9714 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9715                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9716   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9717     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9718     PartialDiagnostic PD = PDiag(
9719          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9720     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9721     Diag(overloadedMD->getLocation(), PD);
9722   }
9723 }
9724 
9725 /// Diagnose methods which overload virtual methods in a base class
9726 /// without overriding any.
9727 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9728   if (MD->isInvalidDecl())
9729     return;
9730 
9731   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9732     return;
9733 
9734   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9735   FindHiddenVirtualMethods(MD, OverloadedMethods);
9736   if (!OverloadedMethods.empty()) {
9737     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9738       << MD << (OverloadedMethods.size() > 1);
9739 
9740     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9741   }
9742 }
9743 
9744 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9745   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9746     // No diagnostics if this is a template instantiation.
9747     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9748       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9749            diag::ext_cannot_use_trivial_abi) << &RD;
9750       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9751            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9752     }
9753     RD.dropAttr<TrivialABIAttr>();
9754   };
9755 
9756   // Ill-formed if the copy and move constructors are deleted.
9757   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9758     // If the type is dependent, then assume it might have
9759     // implicit copy or move ctor because we won't know yet at this point.
9760     if (RD.isDependentType())
9761       return true;
9762     if (RD.needsImplicitCopyConstructor() &&
9763         !RD.defaultedCopyConstructorIsDeleted())
9764       return true;
9765     if (RD.needsImplicitMoveConstructor() &&
9766         !RD.defaultedMoveConstructorIsDeleted())
9767       return true;
9768     for (const CXXConstructorDecl *CD : RD.ctors())
9769       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9770         return true;
9771     return false;
9772   };
9773 
9774   if (!HasNonDeletedCopyOrMoveConstructor()) {
9775     PrintDiagAndRemoveAttr(0);
9776     return;
9777   }
9778 
9779   // Ill-formed if the struct has virtual functions.
9780   if (RD.isPolymorphic()) {
9781     PrintDiagAndRemoveAttr(1);
9782     return;
9783   }
9784 
9785   for (const auto &B : RD.bases()) {
9786     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9787     // virtual base.
9788     if (!B.getType()->isDependentType() &&
9789         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9790       PrintDiagAndRemoveAttr(2);
9791       return;
9792     }
9793 
9794     if (B.isVirtual()) {
9795       PrintDiagAndRemoveAttr(3);
9796       return;
9797     }
9798   }
9799 
9800   for (const auto *FD : RD.fields()) {
9801     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9802     // non-trivial for the purpose of calls.
9803     QualType FT = FD->getType();
9804     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9805       PrintDiagAndRemoveAttr(4);
9806       return;
9807     }
9808 
9809     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9810       if (!RT->isDependentType() &&
9811           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9812         PrintDiagAndRemoveAttr(5);
9813         return;
9814       }
9815   }
9816 }
9817 
9818 void Sema::ActOnFinishCXXMemberSpecification(
9819     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9820     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9821   if (!TagDecl)
9822     return;
9823 
9824   AdjustDeclIfTemplate(TagDecl);
9825 
9826   for (const ParsedAttr &AL : AttrList) {
9827     if (AL.getKind() != ParsedAttr::AT_Visibility)
9828       continue;
9829     AL.setInvalid();
9830     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9831   }
9832 
9833   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9834               // strict aliasing violation!
9835               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9836               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9837 
9838   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9839 }
9840 
9841 /// Find the equality comparison functions that should be implicitly declared
9842 /// in a given class definition, per C++2a [class.compare.default]p3.
9843 static void findImplicitlyDeclaredEqualityComparisons(
9844     ASTContext &Ctx, CXXRecordDecl *RD,
9845     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9846   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9847   if (!RD->lookup(EqEq).empty())
9848     // Member operator== explicitly declared: no implicit operator==s.
9849     return;
9850 
9851   // Traverse friends looking for an '==' or a '<=>'.
9852   for (FriendDecl *Friend : RD->friends()) {
9853     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9854     if (!FD) continue;
9855 
9856     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9857       // Friend operator== explicitly declared: no implicit operator==s.
9858       Spaceships.clear();
9859       return;
9860     }
9861 
9862     if (FD->getOverloadedOperator() == OO_Spaceship &&
9863         FD->isExplicitlyDefaulted())
9864       Spaceships.push_back(FD);
9865   }
9866 
9867   // Look for members named 'operator<=>'.
9868   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9869   for (NamedDecl *ND : RD->lookup(Cmp)) {
9870     // Note that we could find a non-function here (either a function template
9871     // or a using-declaration). Neither case results in an implicit
9872     // 'operator=='.
9873     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9874       if (FD->isExplicitlyDefaulted())
9875         Spaceships.push_back(FD);
9876   }
9877 }
9878 
9879 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9880 /// special functions, such as the default constructor, copy
9881 /// constructor, or destructor, to the given C++ class (C++
9882 /// [special]p1).  This routine can only be executed just before the
9883 /// definition of the class is complete.
9884 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9885   // Don't add implicit special members to templated classes.
9886   // FIXME: This means unqualified lookups for 'operator=' within a class
9887   // template don't work properly.
9888   if (!ClassDecl->isDependentType()) {
9889     if (ClassDecl->needsImplicitDefaultConstructor()) {
9890       ++getASTContext().NumImplicitDefaultConstructors;
9891 
9892       if (ClassDecl->hasInheritedConstructor())
9893         DeclareImplicitDefaultConstructor(ClassDecl);
9894     }
9895 
9896     if (ClassDecl->needsImplicitCopyConstructor()) {
9897       ++getASTContext().NumImplicitCopyConstructors;
9898 
9899       // If the properties or semantics of the copy constructor couldn't be
9900       // determined while the class was being declared, force a declaration
9901       // of it now.
9902       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9903           ClassDecl->hasInheritedConstructor())
9904         DeclareImplicitCopyConstructor(ClassDecl);
9905       // For the MS ABI we need to know whether the copy ctor is deleted. A
9906       // prerequisite for deleting the implicit copy ctor is that the class has
9907       // a move ctor or move assignment that is either user-declared or whose
9908       // semantics are inherited from a subobject. FIXME: We should provide a
9909       // more direct way for CodeGen to ask whether the constructor was deleted.
9910       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9911                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9912                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9913                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9914                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9915         DeclareImplicitCopyConstructor(ClassDecl);
9916     }
9917 
9918     if (getLangOpts().CPlusPlus11 &&
9919         ClassDecl->needsImplicitMoveConstructor()) {
9920       ++getASTContext().NumImplicitMoveConstructors;
9921 
9922       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9923           ClassDecl->hasInheritedConstructor())
9924         DeclareImplicitMoveConstructor(ClassDecl);
9925     }
9926 
9927     if (ClassDecl->needsImplicitCopyAssignment()) {
9928       ++getASTContext().NumImplicitCopyAssignmentOperators;
9929 
9930       // If we have a dynamic class, then the copy assignment operator may be
9931       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9932       // it shows up in the right place in the vtable and that we diagnose
9933       // problems with the implicit exception specification.
9934       if (ClassDecl->isDynamicClass() ||
9935           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9936           ClassDecl->hasInheritedAssignment())
9937         DeclareImplicitCopyAssignment(ClassDecl);
9938     }
9939 
9940     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9941       ++getASTContext().NumImplicitMoveAssignmentOperators;
9942 
9943       // Likewise for the move assignment operator.
9944       if (ClassDecl->isDynamicClass() ||
9945           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9946           ClassDecl->hasInheritedAssignment())
9947         DeclareImplicitMoveAssignment(ClassDecl);
9948     }
9949 
9950     if (ClassDecl->needsImplicitDestructor()) {
9951       ++getASTContext().NumImplicitDestructors;
9952 
9953       // If we have a dynamic class, then the destructor may be virtual, so we
9954       // have to declare the destructor immediately. This ensures that, e.g., it
9955       // shows up in the right place in the vtable and that we diagnose problems
9956       // with the implicit exception specification.
9957       if (ClassDecl->isDynamicClass() ||
9958           ClassDecl->needsOverloadResolutionForDestructor())
9959         DeclareImplicitDestructor(ClassDecl);
9960     }
9961   }
9962 
9963   // C++2a [class.compare.default]p3:
9964   //   If the member-specification does not explicitly declare any member or
9965   //   friend named operator==, an == operator function is declared implicitly
9966   //   for each defaulted three-way comparison operator function defined in
9967   //   the member-specification
9968   // FIXME: Consider doing this lazily.
9969   // We do this during the initial parse for a class template, not during
9970   // instantiation, so that we can handle unqualified lookups for 'operator=='
9971   // when parsing the template.
9972   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9973     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9974     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9975                                               DefaultedSpaceships);
9976     for (auto *FD : DefaultedSpaceships)
9977       DeclareImplicitEqualityComparison(ClassDecl, FD);
9978   }
9979 }
9980 
9981 unsigned
9982 Sema::ActOnReenterTemplateScope(Decl *D,
9983                                 llvm::function_ref<Scope *()> EnterScope) {
9984   if (!D)
9985     return 0;
9986   AdjustDeclIfTemplate(D);
9987 
9988   // In order to get name lookup right, reenter template scopes in order from
9989   // outermost to innermost.
9990   SmallVector<TemplateParameterList *, 4> ParameterLists;
9991   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9992 
9993   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9994     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9995       ParameterLists.push_back(DD->getTemplateParameterList(i));
9996 
9997     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9998       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9999         ParameterLists.push_back(FTD->getTemplateParameters());
10000     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10001       LookupDC = VD->getDeclContext();
10002 
10003       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10004         ParameterLists.push_back(VTD->getTemplateParameters());
10005       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10006         ParameterLists.push_back(PSD->getTemplateParameters());
10007     }
10008   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10009     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10010       ParameterLists.push_back(TD->getTemplateParameterList(i));
10011 
10012     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10013       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10014         ParameterLists.push_back(CTD->getTemplateParameters());
10015       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10016         ParameterLists.push_back(PSD->getTemplateParameters());
10017     }
10018   }
10019   // FIXME: Alias declarations and concepts.
10020 
10021   unsigned Count = 0;
10022   Scope *InnermostTemplateScope = nullptr;
10023   for (TemplateParameterList *Params : ParameterLists) {
10024     // Ignore explicit specializations; they don't contribute to the template
10025     // depth.
10026     if (Params->size() == 0)
10027       continue;
10028 
10029     InnermostTemplateScope = EnterScope();
10030     for (NamedDecl *Param : *Params) {
10031       if (Param->getDeclName()) {
10032         InnermostTemplateScope->AddDecl(Param);
10033         IdResolver.AddDecl(Param);
10034       }
10035     }
10036     ++Count;
10037   }
10038 
10039   // Associate the new template scopes with the corresponding entities.
10040   if (InnermostTemplateScope) {
10041     assert(LookupDC && "no enclosing DeclContext for template lookup");
10042     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10043   }
10044 
10045   return Count;
10046 }
10047 
10048 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10049   if (!RecordD) return;
10050   AdjustDeclIfTemplate(RecordD);
10051   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10052   PushDeclContext(S, Record);
10053 }
10054 
10055 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10056   if (!RecordD) return;
10057   PopDeclContext();
10058 }
10059 
10060 /// This is used to implement the constant expression evaluation part of the
10061 /// attribute enable_if extension. There is nothing in standard C++ which would
10062 /// require reentering parameters.
10063 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10064   if (!Param)
10065     return;
10066 
10067   S->AddDecl(Param);
10068   if (Param->getDeclName())
10069     IdResolver.AddDecl(Param);
10070 }
10071 
10072 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10073 /// parsing a top-level (non-nested) C++ class, and we are now
10074 /// parsing those parts of the given Method declaration that could
10075 /// not be parsed earlier (C++ [class.mem]p2), such as default
10076 /// arguments. This action should enter the scope of the given
10077 /// Method declaration as if we had just parsed the qualified method
10078 /// name. However, it should not bring the parameters into scope;
10079 /// that will be performed by ActOnDelayedCXXMethodParameter.
10080 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10081 }
10082 
10083 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10084 /// C++ method declaration. We're (re-)introducing the given
10085 /// function parameter into scope for use in parsing later parts of
10086 /// the method declaration. For example, we could see an
10087 /// ActOnParamDefaultArgument event for this parameter.
10088 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10089   if (!ParamD)
10090     return;
10091 
10092   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10093 
10094   S->AddDecl(Param);
10095   if (Param->getDeclName())
10096     IdResolver.AddDecl(Param);
10097 }
10098 
10099 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10100 /// processing the delayed method declaration for Method. The method
10101 /// declaration is now considered finished. There may be a separate
10102 /// ActOnStartOfFunctionDef action later (not necessarily
10103 /// immediately!) for this method, if it was also defined inside the
10104 /// class body.
10105 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10106   if (!MethodD)
10107     return;
10108 
10109   AdjustDeclIfTemplate(MethodD);
10110 
10111   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10112 
10113   // Now that we have our default arguments, check the constructor
10114   // again. It could produce additional diagnostics or affect whether
10115   // the class has implicitly-declared destructors, among other
10116   // things.
10117   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10118     CheckConstructor(Constructor);
10119 
10120   // Check the default arguments, which we may have added.
10121   if (!Method->isInvalidDecl())
10122     CheckCXXDefaultArguments(Method);
10123 }
10124 
10125 // Emit the given diagnostic for each non-address-space qualifier.
10126 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10127 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10128   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10129   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10130     bool DiagOccured = false;
10131     FTI.MethodQualifiers->forEachQualifier(
10132         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10133                                    SourceLocation SL) {
10134           // This diagnostic should be emitted on any qualifier except an addr
10135           // space qualifier. However, forEachQualifier currently doesn't visit
10136           // addr space qualifiers, so there's no way to write this condition
10137           // right now; we just diagnose on everything.
10138           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10139           DiagOccured = true;
10140         });
10141     if (DiagOccured)
10142       D.setInvalidType();
10143   }
10144 }
10145 
10146 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10147 /// the well-formedness of the constructor declarator @p D with type @p
10148 /// R. If there are any errors in the declarator, this routine will
10149 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10150 /// will be updated to reflect a well-formed type for the constructor and
10151 /// returned.
10152 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10153                                           StorageClass &SC) {
10154   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10155 
10156   // C++ [class.ctor]p3:
10157   //   A constructor shall not be virtual (10.3) or static (9.4). A
10158   //   constructor can be invoked for a const, volatile or const
10159   //   volatile object. A constructor shall not be declared const,
10160   //   volatile, or const volatile (9.3.2).
10161   if (isVirtual) {
10162     if (!D.isInvalidType())
10163       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10164         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10165         << SourceRange(D.getIdentifierLoc());
10166     D.setInvalidType();
10167   }
10168   if (SC == SC_Static) {
10169     if (!D.isInvalidType())
10170       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10171         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10172         << SourceRange(D.getIdentifierLoc());
10173     D.setInvalidType();
10174     SC = SC_None;
10175   }
10176 
10177   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10178     diagnoseIgnoredQualifiers(
10179         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10180         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10181         D.getDeclSpec().getRestrictSpecLoc(),
10182         D.getDeclSpec().getAtomicSpecLoc());
10183     D.setInvalidType();
10184   }
10185 
10186   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10187 
10188   // C++0x [class.ctor]p4:
10189   //   A constructor shall not be declared with a ref-qualifier.
10190   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10191   if (FTI.hasRefQualifier()) {
10192     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10193       << FTI.RefQualifierIsLValueRef
10194       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10195     D.setInvalidType();
10196   }
10197 
10198   // Rebuild the function type "R" without any type qualifiers (in
10199   // case any of the errors above fired) and with "void" as the
10200   // return type, since constructors don't have return types.
10201   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10202   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10203     return R;
10204 
10205   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10206   EPI.TypeQuals = Qualifiers();
10207   EPI.RefQualifier = RQ_None;
10208 
10209   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10210 }
10211 
10212 /// CheckConstructor - Checks a fully-formed constructor for
10213 /// well-formedness, issuing any diagnostics required. Returns true if
10214 /// the constructor declarator is invalid.
10215 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10216   CXXRecordDecl *ClassDecl
10217     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10218   if (!ClassDecl)
10219     return Constructor->setInvalidDecl();
10220 
10221   // C++ [class.copy]p3:
10222   //   A declaration of a constructor for a class X is ill-formed if
10223   //   its first parameter is of type (optionally cv-qualified) X and
10224   //   either there are no other parameters or else all other
10225   //   parameters have default arguments.
10226   if (!Constructor->isInvalidDecl() &&
10227       Constructor->hasOneParamOrDefaultArgs() &&
10228       Constructor->getTemplateSpecializationKind() !=
10229           TSK_ImplicitInstantiation) {
10230     QualType ParamType = Constructor->getParamDecl(0)->getType();
10231     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10232     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10233       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10234       const char *ConstRef
10235         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10236                                                         : " const &";
10237       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10238         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10239 
10240       // FIXME: Rather that making the constructor invalid, we should endeavor
10241       // to fix the type.
10242       Constructor->setInvalidDecl();
10243     }
10244   }
10245 }
10246 
10247 /// CheckDestructor - Checks a fully-formed destructor definition for
10248 /// well-formedness, issuing any diagnostics required.  Returns true
10249 /// on error.
10250 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10251   CXXRecordDecl *RD = Destructor->getParent();
10252 
10253   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10254     SourceLocation Loc;
10255 
10256     if (!Destructor->isImplicit())
10257       Loc = Destructor->getLocation();
10258     else
10259       Loc = RD->getLocation();
10260 
10261     // If we have a virtual destructor, look up the deallocation function
10262     if (FunctionDecl *OperatorDelete =
10263             FindDeallocationFunctionForDestructor(Loc, RD)) {
10264       Expr *ThisArg = nullptr;
10265 
10266       // If the notional 'delete this' expression requires a non-trivial
10267       // conversion from 'this' to the type of a destroying operator delete's
10268       // first parameter, perform that conversion now.
10269       if (OperatorDelete->isDestroyingOperatorDelete()) {
10270         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10271         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10272           // C++ [class.dtor]p13:
10273           //   ... as if for the expression 'delete this' appearing in a
10274           //   non-virtual destructor of the destructor's class.
10275           ContextRAII SwitchContext(*this, Destructor);
10276           ExprResult This =
10277               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10278           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10279           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10280           if (This.isInvalid()) {
10281             // FIXME: Register this as a context note so that it comes out
10282             // in the right order.
10283             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10284             return true;
10285           }
10286           ThisArg = This.get();
10287         }
10288       }
10289 
10290       DiagnoseUseOfDecl(OperatorDelete, Loc);
10291       MarkFunctionReferenced(Loc, OperatorDelete);
10292       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10293     }
10294   }
10295 
10296   return false;
10297 }
10298 
10299 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10300 /// the well-formednes of the destructor declarator @p D with type @p
10301 /// R. If there are any errors in the declarator, this routine will
10302 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10303 /// will be updated to reflect a well-formed type for the destructor and
10304 /// returned.
10305 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10306                                          StorageClass& SC) {
10307   // C++ [class.dtor]p1:
10308   //   [...] A typedef-name that names a class is a class-name
10309   //   (7.1.3); however, a typedef-name that names a class shall not
10310   //   be used as the identifier in the declarator for a destructor
10311   //   declaration.
10312   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10313   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10314     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10315       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10316   else if (const TemplateSpecializationType *TST =
10317              DeclaratorType->getAs<TemplateSpecializationType>())
10318     if (TST->isTypeAlias())
10319       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10320         << DeclaratorType << 1;
10321 
10322   // C++ [class.dtor]p2:
10323   //   A destructor is used to destroy objects of its class type. A
10324   //   destructor takes no parameters, and no return type can be
10325   //   specified for it (not even void). The address of a destructor
10326   //   shall not be taken. A destructor shall not be static. A
10327   //   destructor can be invoked for a const, volatile or const
10328   //   volatile object. A destructor shall not be declared const,
10329   //   volatile or const volatile (9.3.2).
10330   if (SC == SC_Static) {
10331     if (!D.isInvalidType())
10332       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10333         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10334         << SourceRange(D.getIdentifierLoc())
10335         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10336 
10337     SC = SC_None;
10338   }
10339   if (!D.isInvalidType()) {
10340     // Destructors don't have return types, but the parser will
10341     // happily parse something like:
10342     //
10343     //   class X {
10344     //     float ~X();
10345     //   };
10346     //
10347     // The return type will be eliminated later.
10348     if (D.getDeclSpec().hasTypeSpecifier())
10349       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10350         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10351         << SourceRange(D.getIdentifierLoc());
10352     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10353       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10354                                 SourceLocation(),
10355                                 D.getDeclSpec().getConstSpecLoc(),
10356                                 D.getDeclSpec().getVolatileSpecLoc(),
10357                                 D.getDeclSpec().getRestrictSpecLoc(),
10358                                 D.getDeclSpec().getAtomicSpecLoc());
10359       D.setInvalidType();
10360     }
10361   }
10362 
10363   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10364 
10365   // C++0x [class.dtor]p2:
10366   //   A destructor shall not be declared with a ref-qualifier.
10367   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10368   if (FTI.hasRefQualifier()) {
10369     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10370       << FTI.RefQualifierIsLValueRef
10371       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10372     D.setInvalidType();
10373   }
10374 
10375   // Make sure we don't have any parameters.
10376   if (FTIHasNonVoidParameters(FTI)) {
10377     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10378 
10379     // Delete the parameters.
10380     FTI.freeParams();
10381     D.setInvalidType();
10382   }
10383 
10384   // Make sure the destructor isn't variadic.
10385   if (FTI.isVariadic) {
10386     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10387     D.setInvalidType();
10388   }
10389 
10390   // Rebuild the function type "R" without any type qualifiers or
10391   // parameters (in case any of the errors above fired) and with
10392   // "void" as the return type, since destructors don't have return
10393   // types.
10394   if (!D.isInvalidType())
10395     return R;
10396 
10397   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10398   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10399   EPI.Variadic = false;
10400   EPI.TypeQuals = Qualifiers();
10401   EPI.RefQualifier = RQ_None;
10402   return Context.getFunctionType(Context.VoidTy, None, EPI);
10403 }
10404 
10405 static void extendLeft(SourceRange &R, SourceRange Before) {
10406   if (Before.isInvalid())
10407     return;
10408   R.setBegin(Before.getBegin());
10409   if (R.getEnd().isInvalid())
10410     R.setEnd(Before.getEnd());
10411 }
10412 
10413 static void extendRight(SourceRange &R, SourceRange After) {
10414   if (After.isInvalid())
10415     return;
10416   if (R.getBegin().isInvalid())
10417     R.setBegin(After.getBegin());
10418   R.setEnd(After.getEnd());
10419 }
10420 
10421 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10422 /// well-formednes of the conversion function declarator @p D with
10423 /// type @p R. If there are any errors in the declarator, this routine
10424 /// will emit diagnostics and return true. Otherwise, it will return
10425 /// false. Either way, the type @p R will be updated to reflect a
10426 /// well-formed type for the conversion operator.
10427 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10428                                      StorageClass& SC) {
10429   // C++ [class.conv.fct]p1:
10430   //   Neither parameter types nor return type can be specified. The
10431   //   type of a conversion function (8.3.5) is "function taking no
10432   //   parameter returning conversion-type-id."
10433   if (SC == SC_Static) {
10434     if (!D.isInvalidType())
10435       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10436         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10437         << D.getName().getSourceRange();
10438     D.setInvalidType();
10439     SC = SC_None;
10440   }
10441 
10442   TypeSourceInfo *ConvTSI = nullptr;
10443   QualType ConvType =
10444       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10445 
10446   const DeclSpec &DS = D.getDeclSpec();
10447   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10448     // Conversion functions don't have return types, but the parser will
10449     // happily parse something like:
10450     //
10451     //   class X {
10452     //     float operator bool();
10453     //   };
10454     //
10455     // The return type will be changed later anyway.
10456     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10457       << SourceRange(DS.getTypeSpecTypeLoc())
10458       << SourceRange(D.getIdentifierLoc());
10459     D.setInvalidType();
10460   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10461     // It's also plausible that the user writes type qualifiers in the wrong
10462     // place, such as:
10463     //   struct S { const operator int(); };
10464     // FIXME: we could provide a fixit to move the qualifiers onto the
10465     // conversion type.
10466     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10467         << SourceRange(D.getIdentifierLoc()) << 0;
10468     D.setInvalidType();
10469   }
10470 
10471   const auto *Proto = R->castAs<FunctionProtoType>();
10472 
10473   // Make sure we don't have any parameters.
10474   if (Proto->getNumParams() > 0) {
10475     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10476 
10477     // Delete the parameters.
10478     D.getFunctionTypeInfo().freeParams();
10479     D.setInvalidType();
10480   } else if (Proto->isVariadic()) {
10481     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10482     D.setInvalidType();
10483   }
10484 
10485   // Diagnose "&operator bool()" and other such nonsense.  This
10486   // is actually a gcc extension which we don't support.
10487   if (Proto->getReturnType() != ConvType) {
10488     bool NeedsTypedef = false;
10489     SourceRange Before, After;
10490 
10491     // Walk the chunks and extract information on them for our diagnostic.
10492     bool PastFunctionChunk = false;
10493     for (auto &Chunk : D.type_objects()) {
10494       switch (Chunk.Kind) {
10495       case DeclaratorChunk::Function:
10496         if (!PastFunctionChunk) {
10497           if (Chunk.Fun.HasTrailingReturnType) {
10498             TypeSourceInfo *TRT = nullptr;
10499             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10500             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10501           }
10502           PastFunctionChunk = true;
10503           break;
10504         }
10505         LLVM_FALLTHROUGH;
10506       case DeclaratorChunk::Array:
10507         NeedsTypedef = true;
10508         extendRight(After, Chunk.getSourceRange());
10509         break;
10510 
10511       case DeclaratorChunk::Pointer:
10512       case DeclaratorChunk::BlockPointer:
10513       case DeclaratorChunk::Reference:
10514       case DeclaratorChunk::MemberPointer:
10515       case DeclaratorChunk::Pipe:
10516         extendLeft(Before, Chunk.getSourceRange());
10517         break;
10518 
10519       case DeclaratorChunk::Paren:
10520         extendLeft(Before, Chunk.Loc);
10521         extendRight(After, Chunk.EndLoc);
10522         break;
10523       }
10524     }
10525 
10526     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10527                          After.isValid()  ? After.getBegin() :
10528                                             D.getIdentifierLoc();
10529     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10530     DB << Before << After;
10531 
10532     if (!NeedsTypedef) {
10533       DB << /*don't need a typedef*/0;
10534 
10535       // If we can provide a correct fix-it hint, do so.
10536       if (After.isInvalid() && ConvTSI) {
10537         SourceLocation InsertLoc =
10538             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10539         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10540            << FixItHint::CreateInsertionFromRange(
10541                   InsertLoc, CharSourceRange::getTokenRange(Before))
10542            << FixItHint::CreateRemoval(Before);
10543       }
10544     } else if (!Proto->getReturnType()->isDependentType()) {
10545       DB << /*typedef*/1 << Proto->getReturnType();
10546     } else if (getLangOpts().CPlusPlus11) {
10547       DB << /*alias template*/2 << Proto->getReturnType();
10548     } else {
10549       DB << /*might not be fixable*/3;
10550     }
10551 
10552     // Recover by incorporating the other type chunks into the result type.
10553     // Note, this does *not* change the name of the function. This is compatible
10554     // with the GCC extension:
10555     //   struct S { &operator int(); } s;
10556     //   int &r = s.operator int(); // ok in GCC
10557     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10558     ConvType = Proto->getReturnType();
10559   }
10560 
10561   // C++ [class.conv.fct]p4:
10562   //   The conversion-type-id shall not represent a function type nor
10563   //   an array type.
10564   if (ConvType->isArrayType()) {
10565     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10566     ConvType = Context.getPointerType(ConvType);
10567     D.setInvalidType();
10568   } else if (ConvType->isFunctionType()) {
10569     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10570     ConvType = Context.getPointerType(ConvType);
10571     D.setInvalidType();
10572   }
10573 
10574   // Rebuild the function type "R" without any parameters (in case any
10575   // of the errors above fired) and with the conversion type as the
10576   // return type.
10577   if (D.isInvalidType())
10578     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10579 
10580   // C++0x explicit conversion operators.
10581   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10582     Diag(DS.getExplicitSpecLoc(),
10583          getLangOpts().CPlusPlus11
10584              ? diag::warn_cxx98_compat_explicit_conversion_functions
10585              : diag::ext_explicit_conversion_functions)
10586         << SourceRange(DS.getExplicitSpecRange());
10587 }
10588 
10589 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10590 /// the declaration of the given C++ conversion function. This routine
10591 /// is responsible for recording the conversion function in the C++
10592 /// class, if possible.
10593 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10594   assert(Conversion && "Expected to receive a conversion function declaration");
10595 
10596   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10597 
10598   // Make sure we aren't redeclaring the conversion function.
10599   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10600   // C++ [class.conv.fct]p1:
10601   //   [...] A conversion function is never used to convert a
10602   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10603   //   same object type (or a reference to it), to a (possibly
10604   //   cv-qualified) base class of that type (or a reference to it),
10605   //   or to (possibly cv-qualified) void.
10606   QualType ClassType
10607     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10608   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10609     ConvType = ConvTypeRef->getPointeeType();
10610   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10611       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10612     /* Suppress diagnostics for instantiations. */;
10613   else if (Conversion->size_overridden_methods() != 0)
10614     /* Suppress diagnostics for overriding virtual function in a base class. */;
10615   else if (ConvType->isRecordType()) {
10616     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10617     if (ConvType == ClassType)
10618       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10619         << ClassType;
10620     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10621       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10622         <<  ClassType << ConvType;
10623   } else if (ConvType->isVoidType()) {
10624     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10625       << ClassType << ConvType;
10626   }
10627 
10628   if (FunctionTemplateDecl *ConversionTemplate
10629                                 = Conversion->getDescribedFunctionTemplate())
10630     return ConversionTemplate;
10631 
10632   return Conversion;
10633 }
10634 
10635 namespace {
10636 /// Utility class to accumulate and print a diagnostic listing the invalid
10637 /// specifier(s) on a declaration.
10638 struct BadSpecifierDiagnoser {
10639   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10640       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10641   ~BadSpecifierDiagnoser() {
10642     Diagnostic << Specifiers;
10643   }
10644 
10645   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10646     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10647   }
10648   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10649     return check(SpecLoc,
10650                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10651   }
10652   void check(SourceLocation SpecLoc, const char *Spec) {
10653     if (SpecLoc.isInvalid()) return;
10654     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10655     if (!Specifiers.empty()) Specifiers += " ";
10656     Specifiers += Spec;
10657   }
10658 
10659   Sema &S;
10660   Sema::SemaDiagnosticBuilder Diagnostic;
10661   std::string Specifiers;
10662 };
10663 }
10664 
10665 /// Check the validity of a declarator that we parsed for a deduction-guide.
10666 /// These aren't actually declarators in the grammar, so we need to check that
10667 /// the user didn't specify any pieces that are not part of the deduction-guide
10668 /// grammar.
10669 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10670                                          StorageClass &SC) {
10671   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10672   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10673   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10674 
10675   // C++ [temp.deduct.guide]p3:
10676   //   A deduction-gide shall be declared in the same scope as the
10677   //   corresponding class template.
10678   if (!CurContext->getRedeclContext()->Equals(
10679           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10680     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10681       << GuidedTemplateDecl;
10682     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10683   }
10684 
10685   auto &DS = D.getMutableDeclSpec();
10686   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10687   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10688       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10689       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10690     BadSpecifierDiagnoser Diagnoser(
10691         *this, D.getIdentifierLoc(),
10692         diag::err_deduction_guide_invalid_specifier);
10693 
10694     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10695     DS.ClearStorageClassSpecs();
10696     SC = SC_None;
10697 
10698     // 'explicit' is permitted.
10699     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10700     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10701     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10702     DS.ClearConstexprSpec();
10703 
10704     Diagnoser.check(DS.getConstSpecLoc(), "const");
10705     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10706     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10707     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10708     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10709     DS.ClearTypeQualifiers();
10710 
10711     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10712     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10713     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10714     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10715     DS.ClearTypeSpecType();
10716   }
10717 
10718   if (D.isInvalidType())
10719     return;
10720 
10721   // Check the declarator is simple enough.
10722   bool FoundFunction = false;
10723   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10724     if (Chunk.Kind == DeclaratorChunk::Paren)
10725       continue;
10726     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10727       Diag(D.getDeclSpec().getBeginLoc(),
10728            diag::err_deduction_guide_with_complex_decl)
10729           << D.getSourceRange();
10730       break;
10731     }
10732     if (!Chunk.Fun.hasTrailingReturnType()) {
10733       Diag(D.getName().getBeginLoc(),
10734            diag::err_deduction_guide_no_trailing_return_type);
10735       break;
10736     }
10737 
10738     // Check that the return type is written as a specialization of
10739     // the template specified as the deduction-guide's name.
10740     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10741     TypeSourceInfo *TSI = nullptr;
10742     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10743     assert(TSI && "deduction guide has valid type but invalid return type?");
10744     bool AcceptableReturnType = false;
10745     bool MightInstantiateToSpecialization = false;
10746     if (auto RetTST =
10747             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10748       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10749       bool TemplateMatches =
10750           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10751       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10752         AcceptableReturnType = true;
10753       else {
10754         // This could still instantiate to the right type, unless we know it
10755         // names the wrong class template.
10756         auto *TD = SpecifiedName.getAsTemplateDecl();
10757         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10758                                              !TemplateMatches);
10759       }
10760     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10761       MightInstantiateToSpecialization = true;
10762     }
10763 
10764     if (!AcceptableReturnType) {
10765       Diag(TSI->getTypeLoc().getBeginLoc(),
10766            diag::err_deduction_guide_bad_trailing_return_type)
10767           << GuidedTemplate << TSI->getType()
10768           << MightInstantiateToSpecialization
10769           << TSI->getTypeLoc().getSourceRange();
10770     }
10771 
10772     // Keep going to check that we don't have any inner declarator pieces (we
10773     // could still have a function returning a pointer to a function).
10774     FoundFunction = true;
10775   }
10776 
10777   if (D.isFunctionDefinition())
10778     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10779 }
10780 
10781 //===----------------------------------------------------------------------===//
10782 // Namespace Handling
10783 //===----------------------------------------------------------------------===//
10784 
10785 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10786 /// reopened.
10787 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10788                                             SourceLocation Loc,
10789                                             IdentifierInfo *II, bool *IsInline,
10790                                             NamespaceDecl *PrevNS) {
10791   assert(*IsInline != PrevNS->isInline());
10792 
10793   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10794   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10795   // inline namespaces, with the intention of bringing names into namespace std.
10796   //
10797   // We support this just well enough to get that case working; this is not
10798   // sufficient to support reopening namespaces as inline in general.
10799   if (*IsInline && II && II->getName().startswith("__atomic") &&
10800       S.getSourceManager().isInSystemHeader(Loc)) {
10801     // Mark all prior declarations of the namespace as inline.
10802     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10803          NS = NS->getPreviousDecl())
10804       NS->setInline(*IsInline);
10805     // Patch up the lookup table for the containing namespace. This isn't really
10806     // correct, but it's good enough for this particular case.
10807     for (auto *I : PrevNS->decls())
10808       if (auto *ND = dyn_cast<NamedDecl>(I))
10809         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10810     return;
10811   }
10812 
10813   if (PrevNS->isInline())
10814     // The user probably just forgot the 'inline', so suggest that it
10815     // be added back.
10816     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10817       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10818   else
10819     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10820 
10821   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10822   *IsInline = PrevNS->isInline();
10823 }
10824 
10825 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10826 /// definition.
10827 Decl *Sema::ActOnStartNamespaceDef(
10828     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10829     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10830     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10831   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10832   // For anonymous namespace, take the location of the left brace.
10833   SourceLocation Loc = II ? IdentLoc : LBrace;
10834   bool IsInline = InlineLoc.isValid();
10835   bool IsInvalid = false;
10836   bool IsStd = false;
10837   bool AddToKnown = false;
10838   Scope *DeclRegionScope = NamespcScope->getParent();
10839 
10840   NamespaceDecl *PrevNS = nullptr;
10841   if (II) {
10842     // C++ [namespace.def]p2:
10843     //   The identifier in an original-namespace-definition shall not
10844     //   have been previously defined in the declarative region in
10845     //   which the original-namespace-definition appears. The
10846     //   identifier in an original-namespace-definition is the name of
10847     //   the namespace. Subsequently in that declarative region, it is
10848     //   treated as an original-namespace-name.
10849     //
10850     // Since namespace names are unique in their scope, and we don't
10851     // look through using directives, just look for any ordinary names
10852     // as if by qualified name lookup.
10853     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10854                    ForExternalRedeclaration);
10855     LookupQualifiedName(R, CurContext->getRedeclContext());
10856     NamedDecl *PrevDecl =
10857         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10858     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10859 
10860     if (PrevNS) {
10861       // This is an extended namespace definition.
10862       if (IsInline != PrevNS->isInline())
10863         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10864                                         &IsInline, PrevNS);
10865     } else if (PrevDecl) {
10866       // This is an invalid name redefinition.
10867       Diag(Loc, diag::err_redefinition_different_kind)
10868         << II;
10869       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10870       IsInvalid = true;
10871       // Continue on to push Namespc as current DeclContext and return it.
10872     } else if (II->isStr("std") &&
10873                CurContext->getRedeclContext()->isTranslationUnit()) {
10874       // This is the first "real" definition of the namespace "std", so update
10875       // our cache of the "std" namespace to point at this definition.
10876       PrevNS = getStdNamespace();
10877       IsStd = true;
10878       AddToKnown = !IsInline;
10879     } else {
10880       // We've seen this namespace for the first time.
10881       AddToKnown = !IsInline;
10882     }
10883   } else {
10884     // Anonymous namespaces.
10885 
10886     // Determine whether the parent already has an anonymous namespace.
10887     DeclContext *Parent = CurContext->getRedeclContext();
10888     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10889       PrevNS = TU->getAnonymousNamespace();
10890     } else {
10891       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10892       PrevNS = ND->getAnonymousNamespace();
10893     }
10894 
10895     if (PrevNS && IsInline != PrevNS->isInline())
10896       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10897                                       &IsInline, PrevNS);
10898   }
10899 
10900   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10901                                                  StartLoc, Loc, II, PrevNS);
10902   if (IsInvalid)
10903     Namespc->setInvalidDecl();
10904 
10905   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10906   AddPragmaAttributes(DeclRegionScope, Namespc);
10907 
10908   // FIXME: Should we be merging attributes?
10909   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10910     PushNamespaceVisibilityAttr(Attr, Loc);
10911 
10912   if (IsStd)
10913     StdNamespace = Namespc;
10914   if (AddToKnown)
10915     KnownNamespaces[Namespc] = false;
10916 
10917   if (II) {
10918     PushOnScopeChains(Namespc, DeclRegionScope);
10919   } else {
10920     // Link the anonymous namespace into its parent.
10921     DeclContext *Parent = CurContext->getRedeclContext();
10922     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10923       TU->setAnonymousNamespace(Namespc);
10924     } else {
10925       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10926     }
10927 
10928     CurContext->addDecl(Namespc);
10929 
10930     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10931     //   behaves as if it were replaced by
10932     //     namespace unique { /* empty body */ }
10933     //     using namespace unique;
10934     //     namespace unique { namespace-body }
10935     //   where all occurrences of 'unique' in a translation unit are
10936     //   replaced by the same identifier and this identifier differs
10937     //   from all other identifiers in the entire program.
10938 
10939     // We just create the namespace with an empty name and then add an
10940     // implicit using declaration, just like the standard suggests.
10941     //
10942     // CodeGen enforces the "universally unique" aspect by giving all
10943     // declarations semantically contained within an anonymous
10944     // namespace internal linkage.
10945 
10946     if (!PrevNS) {
10947       UD = UsingDirectiveDecl::Create(Context, Parent,
10948                                       /* 'using' */ LBrace,
10949                                       /* 'namespace' */ SourceLocation(),
10950                                       /* qualifier */ NestedNameSpecifierLoc(),
10951                                       /* identifier */ SourceLocation(),
10952                                       Namespc,
10953                                       /* Ancestor */ Parent);
10954       UD->setImplicit();
10955       Parent->addDecl(UD);
10956     }
10957   }
10958 
10959   ActOnDocumentableDecl(Namespc);
10960 
10961   // Although we could have an invalid decl (i.e. the namespace name is a
10962   // redefinition), push it as current DeclContext and try to continue parsing.
10963   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10964   // for the namespace has the declarations that showed up in that particular
10965   // namespace definition.
10966   PushDeclContext(NamespcScope, Namespc);
10967   return Namespc;
10968 }
10969 
10970 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10971 /// is a namespace alias, returns the namespace it points to.
10972 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10973   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10974     return AD->getNamespace();
10975   return dyn_cast_or_null<NamespaceDecl>(D);
10976 }
10977 
10978 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10979 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10980 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10981   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10982   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10983   Namespc->setRBraceLoc(RBrace);
10984   PopDeclContext();
10985   if (Namespc->hasAttr<VisibilityAttr>())
10986     PopPragmaVisibility(true, RBrace);
10987   // If this namespace contains an export-declaration, export it now.
10988   if (DeferredExportedNamespaces.erase(Namespc))
10989     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10990 }
10991 
10992 CXXRecordDecl *Sema::getStdBadAlloc() const {
10993   return cast_or_null<CXXRecordDecl>(
10994                                   StdBadAlloc.get(Context.getExternalSource()));
10995 }
10996 
10997 EnumDecl *Sema::getStdAlignValT() const {
10998   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10999 }
11000 
11001 NamespaceDecl *Sema::getStdNamespace() const {
11002   return cast_or_null<NamespaceDecl>(
11003                                  StdNamespace.get(Context.getExternalSource()));
11004 }
11005 
11006 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11007   if (!StdExperimentalNamespaceCache) {
11008     if (auto Std = getStdNamespace()) {
11009       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11010                           SourceLocation(), LookupNamespaceName);
11011       if (!LookupQualifiedName(Result, Std) ||
11012           !(StdExperimentalNamespaceCache =
11013                 Result.getAsSingle<NamespaceDecl>()))
11014         Result.suppressDiagnostics();
11015     }
11016   }
11017   return StdExperimentalNamespaceCache;
11018 }
11019 
11020 namespace {
11021 
11022 enum UnsupportedSTLSelect {
11023   USS_InvalidMember,
11024   USS_MissingMember,
11025   USS_NonTrivial,
11026   USS_Other
11027 };
11028 
11029 struct InvalidSTLDiagnoser {
11030   Sema &S;
11031   SourceLocation Loc;
11032   QualType TyForDiags;
11033 
11034   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11035                       const VarDecl *VD = nullptr) {
11036     {
11037       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11038                << TyForDiags << ((int)Sel);
11039       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11040         assert(!Name.empty());
11041         D << Name;
11042       }
11043     }
11044     if (Sel == USS_InvalidMember) {
11045       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11046           << VD << VD->getSourceRange();
11047     }
11048     return QualType();
11049   }
11050 };
11051 } // namespace
11052 
11053 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11054                                            SourceLocation Loc,
11055                                            ComparisonCategoryUsage Usage) {
11056   assert(getLangOpts().CPlusPlus &&
11057          "Looking for comparison category type outside of C++.");
11058 
11059   // Use an elaborated type for diagnostics which has a name containing the
11060   // prepended 'std' namespace but not any inline namespace names.
11061   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11062     auto *NNS =
11063         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11064     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11065   };
11066 
11067   // Check if we've already successfully checked the comparison category type
11068   // before. If so, skip checking it again.
11069   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11070   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11071     // The only thing we need to check is that the type has a reachable
11072     // definition in the current context.
11073     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11074       return QualType();
11075 
11076     return Info->getType();
11077   }
11078 
11079   // If lookup failed
11080   if (!Info) {
11081     std::string NameForDiags = "std::";
11082     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11083     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11084         << NameForDiags << (int)Usage;
11085     return QualType();
11086   }
11087 
11088   assert(Info->Kind == Kind);
11089   assert(Info->Record);
11090 
11091   // Update the Record decl in case we encountered a forward declaration on our
11092   // first pass. FIXME: This is a bit of a hack.
11093   if (Info->Record->hasDefinition())
11094     Info->Record = Info->Record->getDefinition();
11095 
11096   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11097     return QualType();
11098 
11099   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11100 
11101   if (!Info->Record->isTriviallyCopyable())
11102     return UnsupportedSTLError(USS_NonTrivial);
11103 
11104   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11105     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11106     // Tolerate empty base classes.
11107     if (Base->isEmpty())
11108       continue;
11109     // Reject STL implementations which have at least one non-empty base.
11110     return UnsupportedSTLError();
11111   }
11112 
11113   // Check that the STL has implemented the types using a single integer field.
11114   // This expectation allows better codegen for builtin operators. We require:
11115   //   (1) The class has exactly one field.
11116   //   (2) The field is an integral or enumeration type.
11117   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11118   if (std::distance(FIt, FEnd) != 1 ||
11119       !FIt->getType()->isIntegralOrEnumerationType()) {
11120     return UnsupportedSTLError();
11121   }
11122 
11123   // Build each of the require values and store them in Info.
11124   for (ComparisonCategoryResult CCR :
11125        ComparisonCategories::getPossibleResultsForType(Kind)) {
11126     StringRef MemName = ComparisonCategories::getResultString(CCR);
11127     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11128 
11129     if (!ValInfo)
11130       return UnsupportedSTLError(USS_MissingMember, MemName);
11131 
11132     VarDecl *VD = ValInfo->VD;
11133     assert(VD && "should not be null!");
11134 
11135     // Attempt to diagnose reasons why the STL definition of this type
11136     // might be foobar, including it failing to be a constant expression.
11137     // TODO Handle more ways the lookup or result can be invalid.
11138     if (!VD->isStaticDataMember() ||
11139         !VD->isUsableInConstantExpressions(Context))
11140       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11141 
11142     // Attempt to evaluate the var decl as a constant expression and extract
11143     // the value of its first field as a ICE. If this fails, the STL
11144     // implementation is not supported.
11145     if (!ValInfo->hasValidIntValue())
11146       return UnsupportedSTLError();
11147 
11148     MarkVariableReferenced(Loc, VD);
11149   }
11150 
11151   // We've successfully built the required types and expressions. Update
11152   // the cache and return the newly cached value.
11153   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11154   return Info->getType();
11155 }
11156 
11157 /// Retrieve the special "std" namespace, which may require us to
11158 /// implicitly define the namespace.
11159 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11160   if (!StdNamespace) {
11161     // The "std" namespace has not yet been defined, so build one implicitly.
11162     StdNamespace = NamespaceDecl::Create(Context,
11163                                          Context.getTranslationUnitDecl(),
11164                                          /*Inline=*/false,
11165                                          SourceLocation(), SourceLocation(),
11166                                          &PP.getIdentifierTable().get("std"),
11167                                          /*PrevDecl=*/nullptr);
11168     getStdNamespace()->setImplicit(true);
11169   }
11170 
11171   return getStdNamespace();
11172 }
11173 
11174 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11175   assert(getLangOpts().CPlusPlus &&
11176          "Looking for std::initializer_list outside of C++.");
11177 
11178   // We're looking for implicit instantiations of
11179   // template <typename E> class std::initializer_list.
11180 
11181   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11182     return false;
11183 
11184   ClassTemplateDecl *Template = nullptr;
11185   const TemplateArgument *Arguments = nullptr;
11186 
11187   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11188 
11189     ClassTemplateSpecializationDecl *Specialization =
11190         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11191     if (!Specialization)
11192       return false;
11193 
11194     Template = Specialization->getSpecializedTemplate();
11195     Arguments = Specialization->getTemplateArgs().data();
11196   } else if (const TemplateSpecializationType *TST =
11197                  Ty->getAs<TemplateSpecializationType>()) {
11198     Template = dyn_cast_or_null<ClassTemplateDecl>(
11199         TST->getTemplateName().getAsTemplateDecl());
11200     Arguments = TST->getArgs();
11201   }
11202   if (!Template)
11203     return false;
11204 
11205   if (!StdInitializerList) {
11206     // Haven't recognized std::initializer_list yet, maybe this is it.
11207     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11208     if (TemplateClass->getIdentifier() !=
11209             &PP.getIdentifierTable().get("initializer_list") ||
11210         !getStdNamespace()->InEnclosingNamespaceSetOf(
11211             TemplateClass->getDeclContext()))
11212       return false;
11213     // This is a template called std::initializer_list, but is it the right
11214     // template?
11215     TemplateParameterList *Params = Template->getTemplateParameters();
11216     if (Params->getMinRequiredArguments() != 1)
11217       return false;
11218     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11219       return false;
11220 
11221     // It's the right template.
11222     StdInitializerList = Template;
11223   }
11224 
11225   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11226     return false;
11227 
11228   // This is an instance of std::initializer_list. Find the argument type.
11229   if (Element)
11230     *Element = Arguments[0].getAsType();
11231   return true;
11232 }
11233 
11234 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11235   NamespaceDecl *Std = S.getStdNamespace();
11236   if (!Std) {
11237     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11238     return nullptr;
11239   }
11240 
11241   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11242                       Loc, Sema::LookupOrdinaryName);
11243   if (!S.LookupQualifiedName(Result, Std)) {
11244     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11245     return nullptr;
11246   }
11247   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11248   if (!Template) {
11249     Result.suppressDiagnostics();
11250     // We found something weird. Complain about the first thing we found.
11251     NamedDecl *Found = *Result.begin();
11252     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11253     return nullptr;
11254   }
11255 
11256   // We found some template called std::initializer_list. Now verify that it's
11257   // correct.
11258   TemplateParameterList *Params = Template->getTemplateParameters();
11259   if (Params->getMinRequiredArguments() != 1 ||
11260       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11261     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11262     return nullptr;
11263   }
11264 
11265   return Template;
11266 }
11267 
11268 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11269   if (!StdInitializerList) {
11270     StdInitializerList = LookupStdInitializerList(*this, Loc);
11271     if (!StdInitializerList)
11272       return QualType();
11273   }
11274 
11275   TemplateArgumentListInfo Args(Loc, Loc);
11276   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11277                                        Context.getTrivialTypeSourceInfo(Element,
11278                                                                         Loc)));
11279   return Context.getCanonicalType(
11280       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11281 }
11282 
11283 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11284   // C++ [dcl.init.list]p2:
11285   //   A constructor is an initializer-list constructor if its first parameter
11286   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11287   //   std::initializer_list<E> for some type E, and either there are no other
11288   //   parameters or else all other parameters have default arguments.
11289   if (!Ctor->hasOneParamOrDefaultArgs())
11290     return false;
11291 
11292   QualType ArgType = Ctor->getParamDecl(0)->getType();
11293   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11294     ArgType = RT->getPointeeType().getUnqualifiedType();
11295 
11296   return isStdInitializerList(ArgType, nullptr);
11297 }
11298 
11299 /// Determine whether a using statement is in a context where it will be
11300 /// apply in all contexts.
11301 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11302   switch (CurContext->getDeclKind()) {
11303     case Decl::TranslationUnit:
11304       return true;
11305     case Decl::LinkageSpec:
11306       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11307     default:
11308       return false;
11309   }
11310 }
11311 
11312 namespace {
11313 
11314 // Callback to only accept typo corrections that are namespaces.
11315 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11316 public:
11317   bool ValidateCandidate(const TypoCorrection &candidate) override {
11318     if (NamedDecl *ND = candidate.getCorrectionDecl())
11319       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11320     return false;
11321   }
11322 
11323   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11324     return std::make_unique<NamespaceValidatorCCC>(*this);
11325   }
11326 };
11327 
11328 }
11329 
11330 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11331                                        CXXScopeSpec &SS,
11332                                        SourceLocation IdentLoc,
11333                                        IdentifierInfo *Ident) {
11334   R.clear();
11335   NamespaceValidatorCCC CCC{};
11336   if (TypoCorrection Corrected =
11337           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11338                         Sema::CTK_ErrorRecovery)) {
11339     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11340       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11341       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11342                               Ident->getName().equals(CorrectedStr);
11343       S.diagnoseTypo(Corrected,
11344                      S.PDiag(diag::err_using_directive_member_suggest)
11345                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11346                      S.PDiag(diag::note_namespace_defined_here));
11347     } else {
11348       S.diagnoseTypo(Corrected,
11349                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11350                      S.PDiag(diag::note_namespace_defined_here));
11351     }
11352     R.addDecl(Corrected.getFoundDecl());
11353     return true;
11354   }
11355   return false;
11356 }
11357 
11358 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11359                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11360                                 SourceLocation IdentLoc,
11361                                 IdentifierInfo *NamespcName,
11362                                 const ParsedAttributesView &AttrList) {
11363   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11364   assert(NamespcName && "Invalid NamespcName.");
11365   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11366 
11367   // This can only happen along a recovery path.
11368   while (S->isTemplateParamScope())
11369     S = S->getParent();
11370   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11371 
11372   UsingDirectiveDecl *UDir = nullptr;
11373   NestedNameSpecifier *Qualifier = nullptr;
11374   if (SS.isSet())
11375     Qualifier = SS.getScopeRep();
11376 
11377   // Lookup namespace name.
11378   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11379   LookupParsedName(R, S, &SS);
11380   if (R.isAmbiguous())
11381     return nullptr;
11382 
11383   if (R.empty()) {
11384     R.clear();
11385     // Allow "using namespace std;" or "using namespace ::std;" even if
11386     // "std" hasn't been defined yet, for GCC compatibility.
11387     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11388         NamespcName->isStr("std")) {
11389       Diag(IdentLoc, diag::ext_using_undefined_std);
11390       R.addDecl(getOrCreateStdNamespace());
11391       R.resolveKind();
11392     }
11393     // Otherwise, attempt typo correction.
11394     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11395   }
11396 
11397   if (!R.empty()) {
11398     NamedDecl *Named = R.getRepresentativeDecl();
11399     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11400     assert(NS && "expected namespace decl");
11401 
11402     // The use of a nested name specifier may trigger deprecation warnings.
11403     DiagnoseUseOfDecl(Named, IdentLoc);
11404 
11405     // C++ [namespace.udir]p1:
11406     //   A using-directive specifies that the names in the nominated
11407     //   namespace can be used in the scope in which the
11408     //   using-directive appears after the using-directive. During
11409     //   unqualified name lookup (3.4.1), the names appear as if they
11410     //   were declared in the nearest enclosing namespace which
11411     //   contains both the using-directive and the nominated
11412     //   namespace. [Note: in this context, "contains" means "contains
11413     //   directly or indirectly". ]
11414 
11415     // Find enclosing context containing both using-directive and
11416     // nominated namespace.
11417     DeclContext *CommonAncestor = NS;
11418     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11419       CommonAncestor = CommonAncestor->getParent();
11420 
11421     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11422                                       SS.getWithLocInContext(Context),
11423                                       IdentLoc, Named, CommonAncestor);
11424 
11425     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11426         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11427       Diag(IdentLoc, diag::warn_using_directive_in_header);
11428     }
11429 
11430     PushUsingDirective(S, UDir);
11431   } else {
11432     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11433   }
11434 
11435   if (UDir)
11436     ProcessDeclAttributeList(S, UDir, AttrList);
11437 
11438   return UDir;
11439 }
11440 
11441 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11442   // If the scope has an associated entity and the using directive is at
11443   // namespace or translation unit scope, add the UsingDirectiveDecl into
11444   // its lookup structure so qualified name lookup can find it.
11445   DeclContext *Ctx = S->getEntity();
11446   if (Ctx && !Ctx->isFunctionOrMethod())
11447     Ctx->addDecl(UDir);
11448   else
11449     // Otherwise, it is at block scope. The using-directives will affect lookup
11450     // only to the end of the scope.
11451     S->PushUsingDirective(UDir);
11452 }
11453 
11454 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11455                                   SourceLocation UsingLoc,
11456                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11457                                   UnqualifiedId &Name,
11458                                   SourceLocation EllipsisLoc,
11459                                   const ParsedAttributesView &AttrList) {
11460   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11461 
11462   if (SS.isEmpty()) {
11463     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11464     return nullptr;
11465   }
11466 
11467   switch (Name.getKind()) {
11468   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11469   case UnqualifiedIdKind::IK_Identifier:
11470   case UnqualifiedIdKind::IK_OperatorFunctionId:
11471   case UnqualifiedIdKind::IK_LiteralOperatorId:
11472   case UnqualifiedIdKind::IK_ConversionFunctionId:
11473     break;
11474 
11475   case UnqualifiedIdKind::IK_ConstructorName:
11476   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11477     // C++11 inheriting constructors.
11478     Diag(Name.getBeginLoc(),
11479          getLangOpts().CPlusPlus11
11480              ? diag::warn_cxx98_compat_using_decl_constructor
11481              : diag::err_using_decl_constructor)
11482         << SS.getRange();
11483 
11484     if (getLangOpts().CPlusPlus11) break;
11485 
11486     return nullptr;
11487 
11488   case UnqualifiedIdKind::IK_DestructorName:
11489     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11490     return nullptr;
11491 
11492   case UnqualifiedIdKind::IK_TemplateId:
11493     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11494         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11495     return nullptr;
11496 
11497   case UnqualifiedIdKind::IK_DeductionGuideName:
11498     llvm_unreachable("cannot parse qualified deduction guide name");
11499   }
11500 
11501   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11502   DeclarationName TargetName = TargetNameInfo.getName();
11503   if (!TargetName)
11504     return nullptr;
11505 
11506   // Warn about access declarations.
11507   if (UsingLoc.isInvalid()) {
11508     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11509                                  ? diag::err_access_decl
11510                                  : diag::warn_access_decl_deprecated)
11511         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11512   }
11513 
11514   if (EllipsisLoc.isInvalid()) {
11515     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11516         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11517       return nullptr;
11518   } else {
11519     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11520         !TargetNameInfo.containsUnexpandedParameterPack()) {
11521       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11522         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11523       EllipsisLoc = SourceLocation();
11524     }
11525   }
11526 
11527   NamedDecl *UD =
11528       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11529                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11530                             /*IsInstantiation*/false);
11531   if (UD)
11532     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11533 
11534   return UD;
11535 }
11536 
11537 /// Determine whether a using declaration considers the given
11538 /// declarations as "equivalent", e.g., if they are redeclarations of
11539 /// the same entity or are both typedefs of the same type.
11540 static bool
11541 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11542   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11543     return true;
11544 
11545   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11546     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11547       return Context.hasSameType(TD1->getUnderlyingType(),
11548                                  TD2->getUnderlyingType());
11549 
11550   return false;
11551 }
11552 
11553 
11554 /// Determines whether to create a using shadow decl for a particular
11555 /// decl, given the set of decls existing prior to this using lookup.
11556 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11557                                 const LookupResult &Previous,
11558                                 UsingShadowDecl *&PrevShadow) {
11559   // Diagnose finding a decl which is not from a base class of the
11560   // current class.  We do this now because there are cases where this
11561   // function will silently decide not to build a shadow decl, which
11562   // will pre-empt further diagnostics.
11563   //
11564   // We don't need to do this in C++11 because we do the check once on
11565   // the qualifier.
11566   //
11567   // FIXME: diagnose the following if we care enough:
11568   //   struct A { int foo; };
11569   //   struct B : A { using A::foo; };
11570   //   template <class T> struct C : A {};
11571   //   template <class T> struct D : C<T> { using B::foo; } // <---
11572   // This is invalid (during instantiation) in C++03 because B::foo
11573   // resolves to the using decl in B, which is not a base class of D<T>.
11574   // We can't diagnose it immediately because C<T> is an unknown
11575   // specialization.  The UsingShadowDecl in D<T> then points directly
11576   // to A::foo, which will look well-formed when we instantiate.
11577   // The right solution is to not collapse the shadow-decl chain.
11578   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11579     DeclContext *OrigDC = Orig->getDeclContext();
11580 
11581     // Handle enums and anonymous structs.
11582     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11583     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11584     while (OrigRec->isAnonymousStructOrUnion())
11585       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11586 
11587     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11588       if (OrigDC == CurContext) {
11589         Diag(Using->getLocation(),
11590              diag::err_using_decl_nested_name_specifier_is_current_class)
11591           << Using->getQualifierLoc().getSourceRange();
11592         Diag(Orig->getLocation(), diag::note_using_decl_target);
11593         Using->setInvalidDecl();
11594         return true;
11595       }
11596 
11597       Diag(Using->getQualifierLoc().getBeginLoc(),
11598            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11599         << Using->getQualifier()
11600         << cast<CXXRecordDecl>(CurContext)
11601         << Using->getQualifierLoc().getSourceRange();
11602       Diag(Orig->getLocation(), diag::note_using_decl_target);
11603       Using->setInvalidDecl();
11604       return true;
11605     }
11606   }
11607 
11608   if (Previous.empty()) return false;
11609 
11610   NamedDecl *Target = Orig;
11611   if (isa<UsingShadowDecl>(Target))
11612     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11613 
11614   // If the target happens to be one of the previous declarations, we
11615   // don't have a conflict.
11616   //
11617   // FIXME: but we might be increasing its access, in which case we
11618   // should redeclare it.
11619   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11620   bool FoundEquivalentDecl = false;
11621   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11622          I != E; ++I) {
11623     NamedDecl *D = (*I)->getUnderlyingDecl();
11624     // We can have UsingDecls in our Previous results because we use the same
11625     // LookupResult for checking whether the UsingDecl itself is a valid
11626     // redeclaration.
11627     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11628       continue;
11629 
11630     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11631       // C++ [class.mem]p19:
11632       //   If T is the name of a class, then [every named member other than
11633       //   a non-static data member] shall have a name different from T
11634       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11635           !isa<IndirectFieldDecl>(Target) &&
11636           !isa<UnresolvedUsingValueDecl>(Target) &&
11637           DiagnoseClassNameShadow(
11638               CurContext,
11639               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11640         return true;
11641     }
11642 
11643     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11644       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11645         PrevShadow = Shadow;
11646       FoundEquivalentDecl = true;
11647     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11648       // We don't conflict with an existing using shadow decl of an equivalent
11649       // declaration, but we're not a redeclaration of it.
11650       FoundEquivalentDecl = true;
11651     }
11652 
11653     if (isVisible(D))
11654       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11655   }
11656 
11657   if (FoundEquivalentDecl)
11658     return false;
11659 
11660   if (FunctionDecl *FD = Target->getAsFunction()) {
11661     NamedDecl *OldDecl = nullptr;
11662     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11663                           /*IsForUsingDecl*/ true)) {
11664     case Ovl_Overload:
11665       return false;
11666 
11667     case Ovl_NonFunction:
11668       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11669       break;
11670 
11671     // We found a decl with the exact signature.
11672     case Ovl_Match:
11673       // If we're in a record, we want to hide the target, so we
11674       // return true (without a diagnostic) to tell the caller not to
11675       // build a shadow decl.
11676       if (CurContext->isRecord())
11677         return true;
11678 
11679       // If we're not in a record, this is an error.
11680       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11681       break;
11682     }
11683 
11684     Diag(Target->getLocation(), diag::note_using_decl_target);
11685     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11686     Using->setInvalidDecl();
11687     return true;
11688   }
11689 
11690   // Target is not a function.
11691 
11692   if (isa<TagDecl>(Target)) {
11693     // No conflict between a tag and a non-tag.
11694     if (!Tag) return false;
11695 
11696     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11697     Diag(Target->getLocation(), diag::note_using_decl_target);
11698     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11699     Using->setInvalidDecl();
11700     return true;
11701   }
11702 
11703   // No conflict between a tag and a non-tag.
11704   if (!NonTag) return false;
11705 
11706   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11707   Diag(Target->getLocation(), diag::note_using_decl_target);
11708   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11709   Using->setInvalidDecl();
11710   return true;
11711 }
11712 
11713 /// Determine whether a direct base class is a virtual base class.
11714 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11715   if (!Derived->getNumVBases())
11716     return false;
11717   for (auto &B : Derived->bases())
11718     if (B.getType()->getAsCXXRecordDecl() == Base)
11719       return B.isVirtual();
11720   llvm_unreachable("not a direct base class");
11721 }
11722 
11723 /// Builds a shadow declaration corresponding to a 'using' declaration.
11724 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11725                                             UsingDecl *UD,
11726                                             NamedDecl *Orig,
11727                                             UsingShadowDecl *PrevDecl) {
11728   // If we resolved to another shadow declaration, just coalesce them.
11729   NamedDecl *Target = Orig;
11730   if (isa<UsingShadowDecl>(Target)) {
11731     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11732     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11733   }
11734 
11735   NamedDecl *NonTemplateTarget = Target;
11736   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11737     NonTemplateTarget = TargetTD->getTemplatedDecl();
11738 
11739   UsingShadowDecl *Shadow;
11740   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11741     bool IsVirtualBase =
11742         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11743                             UD->getQualifier()->getAsRecordDecl());
11744     Shadow = ConstructorUsingShadowDecl::Create(
11745         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11746   } else {
11747     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11748                                      Target);
11749   }
11750   UD->addShadowDecl(Shadow);
11751 
11752   Shadow->setAccess(UD->getAccess());
11753   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11754     Shadow->setInvalidDecl();
11755 
11756   Shadow->setPreviousDecl(PrevDecl);
11757 
11758   if (S)
11759     PushOnScopeChains(Shadow, S);
11760   else
11761     CurContext->addDecl(Shadow);
11762 
11763 
11764   return Shadow;
11765 }
11766 
11767 /// Hides a using shadow declaration.  This is required by the current
11768 /// using-decl implementation when a resolvable using declaration in a
11769 /// class is followed by a declaration which would hide or override
11770 /// one or more of the using decl's targets; for example:
11771 ///
11772 ///   struct Base { void foo(int); };
11773 ///   struct Derived : Base {
11774 ///     using Base::foo;
11775 ///     void foo(int);
11776 ///   };
11777 ///
11778 /// The governing language is C++03 [namespace.udecl]p12:
11779 ///
11780 ///   When a using-declaration brings names from a base class into a
11781 ///   derived class scope, member functions in the derived class
11782 ///   override and/or hide member functions with the same name and
11783 ///   parameter types in a base class (rather than conflicting).
11784 ///
11785 /// There are two ways to implement this:
11786 ///   (1) optimistically create shadow decls when they're not hidden
11787 ///       by existing declarations, or
11788 ///   (2) don't create any shadow decls (or at least don't make them
11789 ///       visible) until we've fully parsed/instantiated the class.
11790 /// The problem with (1) is that we might have to retroactively remove
11791 /// a shadow decl, which requires several O(n) operations because the
11792 /// decl structures are (very reasonably) not designed for removal.
11793 /// (2) avoids this but is very fiddly and phase-dependent.
11794 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11795   if (Shadow->getDeclName().getNameKind() ==
11796         DeclarationName::CXXConversionFunctionName)
11797     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11798 
11799   // Remove it from the DeclContext...
11800   Shadow->getDeclContext()->removeDecl(Shadow);
11801 
11802   // ...and the scope, if applicable...
11803   if (S) {
11804     S->RemoveDecl(Shadow);
11805     IdResolver.RemoveDecl(Shadow);
11806   }
11807 
11808   // ...and the using decl.
11809   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11810 
11811   // TODO: complain somehow if Shadow was used.  It shouldn't
11812   // be possible for this to happen, because...?
11813 }
11814 
11815 /// Find the base specifier for a base class with the given type.
11816 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11817                                                 QualType DesiredBase,
11818                                                 bool &AnyDependentBases) {
11819   // Check whether the named type is a direct base class.
11820   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11821     .getUnqualifiedType();
11822   for (auto &Base : Derived->bases()) {
11823     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11824     if (CanonicalDesiredBase == BaseType)
11825       return &Base;
11826     if (BaseType->isDependentType())
11827       AnyDependentBases = true;
11828   }
11829   return nullptr;
11830 }
11831 
11832 namespace {
11833 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11834 public:
11835   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11836                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11837       : HasTypenameKeyword(HasTypenameKeyword),
11838         IsInstantiation(IsInstantiation), OldNNS(NNS),
11839         RequireMemberOf(RequireMemberOf) {}
11840 
11841   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11842     NamedDecl *ND = Candidate.getCorrectionDecl();
11843 
11844     // Keywords are not valid here.
11845     if (!ND || isa<NamespaceDecl>(ND))
11846       return false;
11847 
11848     // Completely unqualified names are invalid for a 'using' declaration.
11849     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11850       return false;
11851 
11852     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11853     // reject.
11854 
11855     if (RequireMemberOf) {
11856       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11857       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11858         // No-one ever wants a using-declaration to name an injected-class-name
11859         // of a base class, unless they're declaring an inheriting constructor.
11860         ASTContext &Ctx = ND->getASTContext();
11861         if (!Ctx.getLangOpts().CPlusPlus11)
11862           return false;
11863         QualType FoundType = Ctx.getRecordType(FoundRecord);
11864 
11865         // Check that the injected-class-name is named as a member of its own
11866         // type; we don't want to suggest 'using Derived::Base;', since that
11867         // means something else.
11868         NestedNameSpecifier *Specifier =
11869             Candidate.WillReplaceSpecifier()
11870                 ? Candidate.getCorrectionSpecifier()
11871                 : OldNNS;
11872         if (!Specifier->getAsType() ||
11873             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11874           return false;
11875 
11876         // Check that this inheriting constructor declaration actually names a
11877         // direct base class of the current class.
11878         bool AnyDependentBases = false;
11879         if (!findDirectBaseWithType(RequireMemberOf,
11880                                     Ctx.getRecordType(FoundRecord),
11881                                     AnyDependentBases) &&
11882             !AnyDependentBases)
11883           return false;
11884       } else {
11885         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11886         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11887           return false;
11888 
11889         // FIXME: Check that the base class member is accessible?
11890       }
11891     } else {
11892       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11893       if (FoundRecord && FoundRecord->isInjectedClassName())
11894         return false;
11895     }
11896 
11897     if (isa<TypeDecl>(ND))
11898       return HasTypenameKeyword || !IsInstantiation;
11899 
11900     return !HasTypenameKeyword;
11901   }
11902 
11903   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11904     return std::make_unique<UsingValidatorCCC>(*this);
11905   }
11906 
11907 private:
11908   bool HasTypenameKeyword;
11909   bool IsInstantiation;
11910   NestedNameSpecifier *OldNNS;
11911   CXXRecordDecl *RequireMemberOf;
11912 };
11913 } // end anonymous namespace
11914 
11915 /// Builds a using declaration.
11916 ///
11917 /// \param IsInstantiation - Whether this call arises from an
11918 ///   instantiation of an unresolved using declaration.  We treat
11919 ///   the lookup differently for these declarations.
11920 NamedDecl *Sema::BuildUsingDeclaration(
11921     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11922     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11923     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11924     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11925   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11926   SourceLocation IdentLoc = NameInfo.getLoc();
11927   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11928 
11929   // FIXME: We ignore attributes for now.
11930 
11931   // For an inheriting constructor declaration, the name of the using
11932   // declaration is the name of a constructor in this class, not in the
11933   // base class.
11934   DeclarationNameInfo UsingName = NameInfo;
11935   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11936     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11937       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11938           Context.getCanonicalType(Context.getRecordType(RD))));
11939 
11940   // Do the redeclaration lookup in the current scope.
11941   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11942                         ForVisibleRedeclaration);
11943   Previous.setHideTags(false);
11944   if (S) {
11945     LookupName(Previous, S);
11946 
11947     // It is really dumb that we have to do this.
11948     LookupResult::Filter F = Previous.makeFilter();
11949     while (F.hasNext()) {
11950       NamedDecl *D = F.next();
11951       if (!isDeclInScope(D, CurContext, S))
11952         F.erase();
11953       // If we found a local extern declaration that's not ordinarily visible,
11954       // and this declaration is being added to a non-block scope, ignore it.
11955       // We're only checking for scope conflicts here, not also for violations
11956       // of the linkage rules.
11957       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11958                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11959         F.erase();
11960     }
11961     F.done();
11962   } else {
11963     assert(IsInstantiation && "no scope in non-instantiation");
11964     if (CurContext->isRecord())
11965       LookupQualifiedName(Previous, CurContext);
11966     else {
11967       // No redeclaration check is needed here; in non-member contexts we
11968       // diagnosed all possible conflicts with other using-declarations when
11969       // building the template:
11970       //
11971       // For a dependent non-type using declaration, the only valid case is
11972       // if we instantiate to a single enumerator. We check for conflicts
11973       // between shadow declarations we introduce, and we check in the template
11974       // definition for conflicts between a non-type using declaration and any
11975       // other declaration, which together covers all cases.
11976       //
11977       // A dependent typename using declaration will never successfully
11978       // instantiate, since it will always name a class member, so we reject
11979       // that in the template definition.
11980     }
11981   }
11982 
11983   // Check for invalid redeclarations.
11984   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11985                                   SS, IdentLoc, Previous))
11986     return nullptr;
11987 
11988   // Check for bad qualifiers.
11989   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11990                               IdentLoc))
11991     return nullptr;
11992 
11993   DeclContext *LookupContext = computeDeclContext(SS);
11994   NamedDecl *D;
11995   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11996   if (!LookupContext || EllipsisLoc.isValid()) {
11997     if (HasTypenameKeyword) {
11998       // FIXME: not all declaration name kinds are legal here
11999       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12000                                               UsingLoc, TypenameLoc,
12001                                               QualifierLoc,
12002                                               IdentLoc, NameInfo.getName(),
12003                                               EllipsisLoc);
12004     } else {
12005       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12006                                            QualifierLoc, NameInfo, EllipsisLoc);
12007     }
12008     D->setAccess(AS);
12009     CurContext->addDecl(D);
12010     return D;
12011   }
12012 
12013   auto Build = [&](bool Invalid) {
12014     UsingDecl *UD =
12015         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12016                           UsingName, HasTypenameKeyword);
12017     UD->setAccess(AS);
12018     CurContext->addDecl(UD);
12019     UD->setInvalidDecl(Invalid);
12020     return UD;
12021   };
12022   auto BuildInvalid = [&]{ return Build(true); };
12023   auto BuildValid = [&]{ return Build(false); };
12024 
12025   if (RequireCompleteDeclContext(SS, LookupContext))
12026     return BuildInvalid();
12027 
12028   // Look up the target name.
12029   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12030 
12031   // Unlike most lookups, we don't always want to hide tag
12032   // declarations: tag names are visible through the using declaration
12033   // even if hidden by ordinary names, *except* in a dependent context
12034   // where it's important for the sanity of two-phase lookup.
12035   if (!IsInstantiation)
12036     R.setHideTags(false);
12037 
12038   // For the purposes of this lookup, we have a base object type
12039   // equal to that of the current context.
12040   if (CurContext->isRecord()) {
12041     R.setBaseObjectType(
12042                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12043   }
12044 
12045   LookupQualifiedName(R, LookupContext);
12046 
12047   // Try to correct typos if possible. If constructor name lookup finds no
12048   // results, that means the named class has no explicit constructors, and we
12049   // suppressed declaring implicit ones (probably because it's dependent or
12050   // invalid).
12051   if (R.empty() &&
12052       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12053     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12054     // it will believe that glibc provides a ::gets in cases where it does not,
12055     // and will try to pull it into namespace std with a using-declaration.
12056     // Just ignore the using-declaration in that case.
12057     auto *II = NameInfo.getName().getAsIdentifierInfo();
12058     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12059         CurContext->isStdNamespace() &&
12060         isa<TranslationUnitDecl>(LookupContext) &&
12061         getSourceManager().isInSystemHeader(UsingLoc))
12062       return nullptr;
12063     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12064                           dyn_cast<CXXRecordDecl>(CurContext));
12065     if (TypoCorrection Corrected =
12066             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12067                         CTK_ErrorRecovery)) {
12068       // We reject candidates where DroppedSpecifier == true, hence the
12069       // literal '0' below.
12070       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12071                                 << NameInfo.getName() << LookupContext << 0
12072                                 << SS.getRange());
12073 
12074       // If we picked a correction with no attached Decl we can't do anything
12075       // useful with it, bail out.
12076       NamedDecl *ND = Corrected.getCorrectionDecl();
12077       if (!ND)
12078         return BuildInvalid();
12079 
12080       // If we corrected to an inheriting constructor, handle it as one.
12081       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12082       if (RD && RD->isInjectedClassName()) {
12083         // The parent of the injected class name is the class itself.
12084         RD = cast<CXXRecordDecl>(RD->getParent());
12085 
12086         // Fix up the information we'll use to build the using declaration.
12087         if (Corrected.WillReplaceSpecifier()) {
12088           NestedNameSpecifierLocBuilder Builder;
12089           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12090                               QualifierLoc.getSourceRange());
12091           QualifierLoc = Builder.getWithLocInContext(Context);
12092         }
12093 
12094         // In this case, the name we introduce is the name of a derived class
12095         // constructor.
12096         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12097         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12098             Context.getCanonicalType(Context.getRecordType(CurClass))));
12099         UsingName.setNamedTypeInfo(nullptr);
12100         for (auto *Ctor : LookupConstructors(RD))
12101           R.addDecl(Ctor);
12102         R.resolveKind();
12103       } else {
12104         // FIXME: Pick up all the declarations if we found an overloaded
12105         // function.
12106         UsingName.setName(ND->getDeclName());
12107         R.addDecl(ND);
12108       }
12109     } else {
12110       Diag(IdentLoc, diag::err_no_member)
12111         << NameInfo.getName() << LookupContext << SS.getRange();
12112       return BuildInvalid();
12113     }
12114   }
12115 
12116   if (R.isAmbiguous())
12117     return BuildInvalid();
12118 
12119   if (HasTypenameKeyword) {
12120     // If we asked for a typename and got a non-type decl, error out.
12121     if (!R.getAsSingle<TypeDecl>()) {
12122       Diag(IdentLoc, diag::err_using_typename_non_type);
12123       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12124         Diag((*I)->getUnderlyingDecl()->getLocation(),
12125              diag::note_using_decl_target);
12126       return BuildInvalid();
12127     }
12128   } else {
12129     // If we asked for a non-typename and we got a type, error out,
12130     // but only if this is an instantiation of an unresolved using
12131     // decl.  Otherwise just silently find the type name.
12132     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12133       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12134       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12135       return BuildInvalid();
12136     }
12137   }
12138 
12139   // C++14 [namespace.udecl]p6:
12140   // A using-declaration shall not name a namespace.
12141   if (R.getAsSingle<NamespaceDecl>()) {
12142     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12143       << SS.getRange();
12144     return BuildInvalid();
12145   }
12146 
12147   // C++14 [namespace.udecl]p7:
12148   // A using-declaration shall not name a scoped enumerator.
12149   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12150     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12151       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12152         << SS.getRange();
12153       return BuildInvalid();
12154     }
12155   }
12156 
12157   UsingDecl *UD = BuildValid();
12158 
12159   // Some additional rules apply to inheriting constructors.
12160   if (UsingName.getName().getNameKind() ==
12161         DeclarationName::CXXConstructorName) {
12162     // Suppress access diagnostics; the access check is instead performed at the
12163     // point of use for an inheriting constructor.
12164     R.suppressDiagnostics();
12165     if (CheckInheritingConstructorUsingDecl(UD))
12166       return UD;
12167   }
12168 
12169   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12170     UsingShadowDecl *PrevDecl = nullptr;
12171     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12172       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12173   }
12174 
12175   return UD;
12176 }
12177 
12178 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12179                                     ArrayRef<NamedDecl *> Expansions) {
12180   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12181          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12182          isa<UsingPackDecl>(InstantiatedFrom));
12183 
12184   auto *UPD =
12185       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12186   UPD->setAccess(InstantiatedFrom->getAccess());
12187   CurContext->addDecl(UPD);
12188   return UPD;
12189 }
12190 
12191 /// Additional checks for a using declaration referring to a constructor name.
12192 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12193   assert(!UD->hasTypename() && "expecting a constructor name");
12194 
12195   const Type *SourceType = UD->getQualifier()->getAsType();
12196   assert(SourceType &&
12197          "Using decl naming constructor doesn't have type in scope spec.");
12198   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12199 
12200   // Check whether the named type is a direct base class.
12201   bool AnyDependentBases = false;
12202   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12203                                       AnyDependentBases);
12204   if (!Base && !AnyDependentBases) {
12205     Diag(UD->getUsingLoc(),
12206          diag::err_using_decl_constructor_not_in_direct_base)
12207       << UD->getNameInfo().getSourceRange()
12208       << QualType(SourceType, 0) << TargetClass;
12209     UD->setInvalidDecl();
12210     return true;
12211   }
12212 
12213   if (Base)
12214     Base->setInheritConstructors();
12215 
12216   return false;
12217 }
12218 
12219 /// Checks that the given using declaration is not an invalid
12220 /// redeclaration.  Note that this is checking only for the using decl
12221 /// itself, not for any ill-formedness among the UsingShadowDecls.
12222 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12223                                        bool HasTypenameKeyword,
12224                                        const CXXScopeSpec &SS,
12225                                        SourceLocation NameLoc,
12226                                        const LookupResult &Prev) {
12227   NestedNameSpecifier *Qual = SS.getScopeRep();
12228 
12229   // C++03 [namespace.udecl]p8:
12230   // C++0x [namespace.udecl]p10:
12231   //   A using-declaration is a declaration and can therefore be used
12232   //   repeatedly where (and only where) multiple declarations are
12233   //   allowed.
12234   //
12235   // That's in non-member contexts.
12236   if (!CurContext->getRedeclContext()->isRecord()) {
12237     // A dependent qualifier outside a class can only ever resolve to an
12238     // enumeration type. Therefore it conflicts with any other non-type
12239     // declaration in the same scope.
12240     // FIXME: How should we check for dependent type-type conflicts at block
12241     // scope?
12242     if (Qual->isDependent() && !HasTypenameKeyword) {
12243       for (auto *D : Prev) {
12244         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12245           bool OldCouldBeEnumerator =
12246               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12247           Diag(NameLoc,
12248                OldCouldBeEnumerator ? diag::err_redefinition
12249                                     : diag::err_redefinition_different_kind)
12250               << Prev.getLookupName();
12251           Diag(D->getLocation(), diag::note_previous_definition);
12252           return true;
12253         }
12254       }
12255     }
12256     return false;
12257   }
12258 
12259   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12260     NamedDecl *D = *I;
12261 
12262     bool DTypename;
12263     NestedNameSpecifier *DQual;
12264     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12265       DTypename = UD->hasTypename();
12266       DQual = UD->getQualifier();
12267     } else if (UnresolvedUsingValueDecl *UD
12268                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12269       DTypename = false;
12270       DQual = UD->getQualifier();
12271     } else if (UnresolvedUsingTypenameDecl *UD
12272                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12273       DTypename = true;
12274       DQual = UD->getQualifier();
12275     } else continue;
12276 
12277     // using decls differ if one says 'typename' and the other doesn't.
12278     // FIXME: non-dependent using decls?
12279     if (HasTypenameKeyword != DTypename) continue;
12280 
12281     // using decls differ if they name different scopes (but note that
12282     // template instantiation can cause this check to trigger when it
12283     // didn't before instantiation).
12284     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12285         Context.getCanonicalNestedNameSpecifier(DQual))
12286       continue;
12287 
12288     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12289     Diag(D->getLocation(), diag::note_using_decl) << 1;
12290     return true;
12291   }
12292 
12293   return false;
12294 }
12295 
12296 
12297 /// Checks that the given nested-name qualifier used in a using decl
12298 /// in the current context is appropriately related to the current
12299 /// scope.  If an error is found, diagnoses it and returns true.
12300 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12301                                    bool HasTypename,
12302                                    const CXXScopeSpec &SS,
12303                                    const DeclarationNameInfo &NameInfo,
12304                                    SourceLocation NameLoc) {
12305   DeclContext *NamedContext = computeDeclContext(SS);
12306 
12307   if (!CurContext->isRecord()) {
12308     // C++03 [namespace.udecl]p3:
12309     // C++0x [namespace.udecl]p8:
12310     //   A using-declaration for a class member shall be a member-declaration.
12311 
12312     // If we weren't able to compute a valid scope, it might validly be a
12313     // dependent class scope or a dependent enumeration unscoped scope. If
12314     // we have a 'typename' keyword, the scope must resolve to a class type.
12315     if ((HasTypename && !NamedContext) ||
12316         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12317       auto *RD = NamedContext
12318                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12319                      : nullptr;
12320       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12321         RD = nullptr;
12322 
12323       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12324         << SS.getRange();
12325 
12326       // If we have a complete, non-dependent source type, try to suggest a
12327       // way to get the same effect.
12328       if (!RD)
12329         return true;
12330 
12331       // Find what this using-declaration was referring to.
12332       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12333       R.setHideTags(false);
12334       R.suppressDiagnostics();
12335       LookupQualifiedName(R, RD);
12336 
12337       if (R.getAsSingle<TypeDecl>()) {
12338         if (getLangOpts().CPlusPlus11) {
12339           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12340           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12341             << 0 // alias declaration
12342             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12343                                           NameInfo.getName().getAsString() +
12344                                               " = ");
12345         } else {
12346           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12347           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12348           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12349             << 1 // typedef declaration
12350             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12351             << FixItHint::CreateInsertion(
12352                    InsertLoc, " " + NameInfo.getName().getAsString());
12353         }
12354       } else if (R.getAsSingle<VarDecl>()) {
12355         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12356         // repeating the type of the static data member here.
12357         FixItHint FixIt;
12358         if (getLangOpts().CPlusPlus11) {
12359           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12360           FixIt = FixItHint::CreateReplacement(
12361               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12362         }
12363 
12364         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12365           << 2 // reference declaration
12366           << FixIt;
12367       } else if (R.getAsSingle<EnumConstantDecl>()) {
12368         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12369         // repeating the type of the enumeration here, and we can't do so if
12370         // the type is anonymous.
12371         FixItHint FixIt;
12372         if (getLangOpts().CPlusPlus11) {
12373           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12374           FixIt = FixItHint::CreateReplacement(
12375               UsingLoc,
12376               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12377         }
12378 
12379         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12380           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12381           << FixIt;
12382       }
12383       return true;
12384     }
12385 
12386     // Otherwise, this might be valid.
12387     return false;
12388   }
12389 
12390   // The current scope is a record.
12391 
12392   // If the named context is dependent, we can't decide much.
12393   if (!NamedContext) {
12394     // FIXME: in C++0x, we can diagnose if we can prove that the
12395     // nested-name-specifier does not refer to a base class, which is
12396     // still possible in some cases.
12397 
12398     // Otherwise we have to conservatively report that things might be
12399     // okay.
12400     return false;
12401   }
12402 
12403   if (!NamedContext->isRecord()) {
12404     // Ideally this would point at the last name in the specifier,
12405     // but we don't have that level of source info.
12406     Diag(SS.getRange().getBegin(),
12407          diag::err_using_decl_nested_name_specifier_is_not_class)
12408       << SS.getScopeRep() << SS.getRange();
12409     return true;
12410   }
12411 
12412   if (!NamedContext->isDependentContext() &&
12413       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12414     return true;
12415 
12416   if (getLangOpts().CPlusPlus11) {
12417     // C++11 [namespace.udecl]p3:
12418     //   In a using-declaration used as a member-declaration, the
12419     //   nested-name-specifier shall name a base class of the class
12420     //   being defined.
12421 
12422     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12423                                  cast<CXXRecordDecl>(NamedContext))) {
12424       if (CurContext == NamedContext) {
12425         Diag(NameLoc,
12426              diag::err_using_decl_nested_name_specifier_is_current_class)
12427           << SS.getRange();
12428         return true;
12429       }
12430 
12431       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12432         Diag(SS.getRange().getBegin(),
12433              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12434           << SS.getScopeRep()
12435           << cast<CXXRecordDecl>(CurContext)
12436           << SS.getRange();
12437       }
12438       return true;
12439     }
12440 
12441     return false;
12442   }
12443 
12444   // C++03 [namespace.udecl]p4:
12445   //   A using-declaration used as a member-declaration shall refer
12446   //   to a member of a base class of the class being defined [etc.].
12447 
12448   // Salient point: SS doesn't have to name a base class as long as
12449   // lookup only finds members from base classes.  Therefore we can
12450   // diagnose here only if we can prove that that can't happen,
12451   // i.e. if the class hierarchies provably don't intersect.
12452 
12453   // TODO: it would be nice if "definitely valid" results were cached
12454   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12455   // need to be repeated.
12456 
12457   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12458   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12459     Bases.insert(Base);
12460     return true;
12461   };
12462 
12463   // Collect all bases. Return false if we find a dependent base.
12464   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12465     return false;
12466 
12467   // Returns true if the base is dependent or is one of the accumulated base
12468   // classes.
12469   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12470     return !Bases.count(Base);
12471   };
12472 
12473   // Return false if the class has a dependent base or if it or one
12474   // of its bases is present in the base set of the current context.
12475   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12476       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12477     return false;
12478 
12479   Diag(SS.getRange().getBegin(),
12480        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12481     << SS.getScopeRep()
12482     << cast<CXXRecordDecl>(CurContext)
12483     << SS.getRange();
12484 
12485   return true;
12486 }
12487 
12488 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12489                                   MultiTemplateParamsArg TemplateParamLists,
12490                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12491                                   const ParsedAttributesView &AttrList,
12492                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12493   // Skip up to the relevant declaration scope.
12494   while (S->isTemplateParamScope())
12495     S = S->getParent();
12496   assert((S->getFlags() & Scope::DeclScope) &&
12497          "got alias-declaration outside of declaration scope");
12498 
12499   if (Type.isInvalid())
12500     return nullptr;
12501 
12502   bool Invalid = false;
12503   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12504   TypeSourceInfo *TInfo = nullptr;
12505   GetTypeFromParser(Type.get(), &TInfo);
12506 
12507   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12508     return nullptr;
12509 
12510   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12511                                       UPPC_DeclarationType)) {
12512     Invalid = true;
12513     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12514                                              TInfo->getTypeLoc().getBeginLoc());
12515   }
12516 
12517   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12518                         TemplateParamLists.size()
12519                             ? forRedeclarationInCurContext()
12520                             : ForVisibleRedeclaration);
12521   LookupName(Previous, S);
12522 
12523   // Warn about shadowing the name of a template parameter.
12524   if (Previous.isSingleResult() &&
12525       Previous.getFoundDecl()->isTemplateParameter()) {
12526     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12527     Previous.clear();
12528   }
12529 
12530   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12531          "name in alias declaration must be an identifier");
12532   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12533                                                Name.StartLocation,
12534                                                Name.Identifier, TInfo);
12535 
12536   NewTD->setAccess(AS);
12537 
12538   if (Invalid)
12539     NewTD->setInvalidDecl();
12540 
12541   ProcessDeclAttributeList(S, NewTD, AttrList);
12542   AddPragmaAttributes(S, NewTD);
12543 
12544   CheckTypedefForVariablyModifiedType(S, NewTD);
12545   Invalid |= NewTD->isInvalidDecl();
12546 
12547   bool Redeclaration = false;
12548 
12549   NamedDecl *NewND;
12550   if (TemplateParamLists.size()) {
12551     TypeAliasTemplateDecl *OldDecl = nullptr;
12552     TemplateParameterList *OldTemplateParams = nullptr;
12553 
12554     if (TemplateParamLists.size() != 1) {
12555       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12556         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12557          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12558     }
12559     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12560 
12561     // Check that we can declare a template here.
12562     if (CheckTemplateDeclScope(S, TemplateParams))
12563       return nullptr;
12564 
12565     // Only consider previous declarations in the same scope.
12566     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12567                          /*ExplicitInstantiationOrSpecialization*/false);
12568     if (!Previous.empty()) {
12569       Redeclaration = true;
12570 
12571       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12572       if (!OldDecl && !Invalid) {
12573         Diag(UsingLoc, diag::err_redefinition_different_kind)
12574           << Name.Identifier;
12575 
12576         NamedDecl *OldD = Previous.getRepresentativeDecl();
12577         if (OldD->getLocation().isValid())
12578           Diag(OldD->getLocation(), diag::note_previous_definition);
12579 
12580         Invalid = true;
12581       }
12582 
12583       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12584         if (TemplateParameterListsAreEqual(TemplateParams,
12585                                            OldDecl->getTemplateParameters(),
12586                                            /*Complain=*/true,
12587                                            TPL_TemplateMatch))
12588           OldTemplateParams =
12589               OldDecl->getMostRecentDecl()->getTemplateParameters();
12590         else
12591           Invalid = true;
12592 
12593         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12594         if (!Invalid &&
12595             !Context.hasSameType(OldTD->getUnderlyingType(),
12596                                  NewTD->getUnderlyingType())) {
12597           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12598           // but we can't reasonably accept it.
12599           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12600             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12601           if (OldTD->getLocation().isValid())
12602             Diag(OldTD->getLocation(), diag::note_previous_definition);
12603           Invalid = true;
12604         }
12605       }
12606     }
12607 
12608     // Merge any previous default template arguments into our parameters,
12609     // and check the parameter list.
12610     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12611                                    TPC_TypeAliasTemplate))
12612       return nullptr;
12613 
12614     TypeAliasTemplateDecl *NewDecl =
12615       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12616                                     Name.Identifier, TemplateParams,
12617                                     NewTD);
12618     NewTD->setDescribedAliasTemplate(NewDecl);
12619 
12620     NewDecl->setAccess(AS);
12621 
12622     if (Invalid)
12623       NewDecl->setInvalidDecl();
12624     else if (OldDecl) {
12625       NewDecl->setPreviousDecl(OldDecl);
12626       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12627     }
12628 
12629     NewND = NewDecl;
12630   } else {
12631     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12632       setTagNameForLinkagePurposes(TD, NewTD);
12633       handleTagNumbering(TD, S);
12634     }
12635     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12636     NewND = NewTD;
12637   }
12638 
12639   PushOnScopeChains(NewND, S);
12640   ActOnDocumentableDecl(NewND);
12641   return NewND;
12642 }
12643 
12644 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12645                                    SourceLocation AliasLoc,
12646                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12647                                    SourceLocation IdentLoc,
12648                                    IdentifierInfo *Ident) {
12649 
12650   // Lookup the namespace name.
12651   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12652   LookupParsedName(R, S, &SS);
12653 
12654   if (R.isAmbiguous())
12655     return nullptr;
12656 
12657   if (R.empty()) {
12658     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12659       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12660       return nullptr;
12661     }
12662   }
12663   assert(!R.isAmbiguous() && !R.empty());
12664   NamedDecl *ND = R.getRepresentativeDecl();
12665 
12666   // Check if we have a previous declaration with the same name.
12667   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12668                      ForVisibleRedeclaration);
12669   LookupName(PrevR, S);
12670 
12671   // Check we're not shadowing a template parameter.
12672   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12673     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12674     PrevR.clear();
12675   }
12676 
12677   // Filter out any other lookup result from an enclosing scope.
12678   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12679                        /*AllowInlineNamespace*/false);
12680 
12681   // Find the previous declaration and check that we can redeclare it.
12682   NamespaceAliasDecl *Prev = nullptr;
12683   if (PrevR.isSingleResult()) {
12684     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12685     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12686       // We already have an alias with the same name that points to the same
12687       // namespace; check that it matches.
12688       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12689         Prev = AD;
12690       } else if (isVisible(PrevDecl)) {
12691         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12692           << Alias;
12693         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12694           << AD->getNamespace();
12695         return nullptr;
12696       }
12697     } else if (isVisible(PrevDecl)) {
12698       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12699                             ? diag::err_redefinition
12700                             : diag::err_redefinition_different_kind;
12701       Diag(AliasLoc, DiagID) << Alias;
12702       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12703       return nullptr;
12704     }
12705   }
12706 
12707   // The use of a nested name specifier may trigger deprecation warnings.
12708   DiagnoseUseOfDecl(ND, IdentLoc);
12709 
12710   NamespaceAliasDecl *AliasDecl =
12711     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12712                                Alias, SS.getWithLocInContext(Context),
12713                                IdentLoc, ND);
12714   if (Prev)
12715     AliasDecl->setPreviousDecl(Prev);
12716 
12717   PushOnScopeChains(AliasDecl, S);
12718   return AliasDecl;
12719 }
12720 
12721 namespace {
12722 struct SpecialMemberExceptionSpecInfo
12723     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12724   SourceLocation Loc;
12725   Sema::ImplicitExceptionSpecification ExceptSpec;
12726 
12727   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12728                                  Sema::CXXSpecialMember CSM,
12729                                  Sema::InheritedConstructorInfo *ICI,
12730                                  SourceLocation Loc)
12731       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12732 
12733   bool visitBase(CXXBaseSpecifier *Base);
12734   bool visitField(FieldDecl *FD);
12735 
12736   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12737                            unsigned Quals);
12738 
12739   void visitSubobjectCall(Subobject Subobj,
12740                           Sema::SpecialMemberOverloadResult SMOR);
12741 };
12742 }
12743 
12744 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12745   auto *RT = Base->getType()->getAs<RecordType>();
12746   if (!RT)
12747     return false;
12748 
12749   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12750   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12751   if (auto *BaseCtor = SMOR.getMethod()) {
12752     visitSubobjectCall(Base, BaseCtor);
12753     return false;
12754   }
12755 
12756   visitClassSubobject(BaseClass, Base, 0);
12757   return false;
12758 }
12759 
12760 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12761   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12762     Expr *E = FD->getInClassInitializer();
12763     if (!E)
12764       // FIXME: It's a little wasteful to build and throw away a
12765       // CXXDefaultInitExpr here.
12766       // FIXME: We should have a single context note pointing at Loc, and
12767       // this location should be MD->getLocation() instead, since that's
12768       // the location where we actually use the default init expression.
12769       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12770     if (E)
12771       ExceptSpec.CalledExpr(E);
12772   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12773                             ->getAs<RecordType>()) {
12774     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12775                         FD->getType().getCVRQualifiers());
12776   }
12777   return false;
12778 }
12779 
12780 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12781                                                          Subobject Subobj,
12782                                                          unsigned Quals) {
12783   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12784   bool IsMutable = Field && Field->isMutable();
12785   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12786 }
12787 
12788 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12789     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12790   // Note, if lookup fails, it doesn't matter what exception specification we
12791   // choose because the special member will be deleted.
12792   if (CXXMethodDecl *MD = SMOR.getMethod())
12793     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12794 }
12795 
12796 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12797   llvm::APSInt Result;
12798   ExprResult Converted = CheckConvertedConstantExpression(
12799       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12800   ExplicitSpec.setExpr(Converted.get());
12801   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12802     ExplicitSpec.setKind(Result.getBoolValue()
12803                              ? ExplicitSpecKind::ResolvedTrue
12804                              : ExplicitSpecKind::ResolvedFalse);
12805     return true;
12806   }
12807   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12808   return false;
12809 }
12810 
12811 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12812   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12813   if (!ExplicitExpr->isTypeDependent())
12814     tryResolveExplicitSpecifier(ES);
12815   return ES;
12816 }
12817 
12818 static Sema::ImplicitExceptionSpecification
12819 ComputeDefaultedSpecialMemberExceptionSpec(
12820     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12821     Sema::InheritedConstructorInfo *ICI) {
12822   ComputingExceptionSpec CES(S, MD, Loc);
12823 
12824   CXXRecordDecl *ClassDecl = MD->getParent();
12825 
12826   // C++ [except.spec]p14:
12827   //   An implicitly declared special member function (Clause 12) shall have an
12828   //   exception-specification. [...]
12829   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12830   if (ClassDecl->isInvalidDecl())
12831     return Info.ExceptSpec;
12832 
12833   // FIXME: If this diagnostic fires, we're probably missing a check for
12834   // attempting to resolve an exception specification before it's known
12835   // at a higher level.
12836   if (S.RequireCompleteType(MD->getLocation(),
12837                             S.Context.getRecordType(ClassDecl),
12838                             diag::err_exception_spec_incomplete_type))
12839     return Info.ExceptSpec;
12840 
12841   // C++1z [except.spec]p7:
12842   //   [Look for exceptions thrown by] a constructor selected [...] to
12843   //   initialize a potentially constructed subobject,
12844   // C++1z [except.spec]p8:
12845   //   The exception specification for an implicitly-declared destructor, or a
12846   //   destructor without a noexcept-specifier, is potentially-throwing if and
12847   //   only if any of the destructors for any of its potentially constructed
12848   //   subojects is potentially throwing.
12849   // FIXME: We respect the first rule but ignore the "potentially constructed"
12850   // in the second rule to resolve a core issue (no number yet) that would have
12851   // us reject:
12852   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12853   //   struct B : A {};
12854   //   struct C : B { void f(); };
12855   // ... due to giving B::~B() a non-throwing exception specification.
12856   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12857                                 : Info.VisitAllBases);
12858 
12859   return Info.ExceptSpec;
12860 }
12861 
12862 namespace {
12863 /// RAII object to register a special member as being currently declared.
12864 struct DeclaringSpecialMember {
12865   Sema &S;
12866   Sema::SpecialMemberDecl D;
12867   Sema::ContextRAII SavedContext;
12868   bool WasAlreadyBeingDeclared;
12869 
12870   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12871       : S(S), D(RD, CSM), SavedContext(S, RD) {
12872     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12873     if (WasAlreadyBeingDeclared)
12874       // This almost never happens, but if it does, ensure that our cache
12875       // doesn't contain a stale result.
12876       S.SpecialMemberCache.clear();
12877     else {
12878       // Register a note to be produced if we encounter an error while
12879       // declaring the special member.
12880       Sema::CodeSynthesisContext Ctx;
12881       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12882       // FIXME: We don't have a location to use here. Using the class's
12883       // location maintains the fiction that we declare all special members
12884       // with the class, but (1) it's not clear that lying about that helps our
12885       // users understand what's going on, and (2) there may be outer contexts
12886       // on the stack (some of which are relevant) and printing them exposes
12887       // our lies.
12888       Ctx.PointOfInstantiation = RD->getLocation();
12889       Ctx.Entity = RD;
12890       Ctx.SpecialMember = CSM;
12891       S.pushCodeSynthesisContext(Ctx);
12892     }
12893   }
12894   ~DeclaringSpecialMember() {
12895     if (!WasAlreadyBeingDeclared) {
12896       S.SpecialMembersBeingDeclared.erase(D);
12897       S.popCodeSynthesisContext();
12898     }
12899   }
12900 
12901   /// Are we already trying to declare this special member?
12902   bool isAlreadyBeingDeclared() const {
12903     return WasAlreadyBeingDeclared;
12904   }
12905 };
12906 }
12907 
12908 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12909   // Look up any existing declarations, but don't trigger declaration of all
12910   // implicit special members with this name.
12911   DeclarationName Name = FD->getDeclName();
12912   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12913                  ForExternalRedeclaration);
12914   for (auto *D : FD->getParent()->lookup(Name))
12915     if (auto *Acceptable = R.getAcceptableDecl(D))
12916       R.addDecl(Acceptable);
12917   R.resolveKind();
12918   R.suppressDiagnostics();
12919 
12920   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12921 }
12922 
12923 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12924                                           QualType ResultTy,
12925                                           ArrayRef<QualType> Args) {
12926   // Build an exception specification pointing back at this constructor.
12927   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12928 
12929   LangAS AS = getDefaultCXXMethodAddrSpace();
12930   if (AS != LangAS::Default) {
12931     EPI.TypeQuals.addAddressSpace(AS);
12932   }
12933 
12934   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12935   SpecialMem->setType(QT);
12936 }
12937 
12938 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12939                                                      CXXRecordDecl *ClassDecl) {
12940   // C++ [class.ctor]p5:
12941   //   A default constructor for a class X is a constructor of class X
12942   //   that can be called without an argument. If there is no
12943   //   user-declared constructor for class X, a default constructor is
12944   //   implicitly declared. An implicitly-declared default constructor
12945   //   is an inline public member of its class.
12946   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12947          "Should not build implicit default constructor!");
12948 
12949   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12950   if (DSM.isAlreadyBeingDeclared())
12951     return nullptr;
12952 
12953   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12954                                                      CXXDefaultConstructor,
12955                                                      false);
12956 
12957   // Create the actual constructor declaration.
12958   CanQualType ClassType
12959     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12960   SourceLocation ClassLoc = ClassDecl->getLocation();
12961   DeclarationName Name
12962     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12963   DeclarationNameInfo NameInfo(Name, ClassLoc);
12964   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12965       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12966       /*TInfo=*/nullptr, ExplicitSpecifier(),
12967       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12968       Constexpr ? CSK_constexpr : CSK_unspecified);
12969   DefaultCon->setAccess(AS_public);
12970   DefaultCon->setDefaulted();
12971 
12972   if (getLangOpts().CUDA) {
12973     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12974                                             DefaultCon,
12975                                             /* ConstRHS */ false,
12976                                             /* Diagnose */ false);
12977   }
12978 
12979   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12980 
12981   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12982   // constructors is easy to compute.
12983   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12984 
12985   // Note that we have declared this constructor.
12986   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12987 
12988   Scope *S = getScopeForContext(ClassDecl);
12989   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12990 
12991   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12992     SetDeclDeleted(DefaultCon, ClassLoc);
12993 
12994   if (S)
12995     PushOnScopeChains(DefaultCon, S, false);
12996   ClassDecl->addDecl(DefaultCon);
12997 
12998   return DefaultCon;
12999 }
13000 
13001 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13002                                             CXXConstructorDecl *Constructor) {
13003   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13004           !Constructor->doesThisDeclarationHaveABody() &&
13005           !Constructor->isDeleted()) &&
13006     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13007   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13008     return;
13009 
13010   CXXRecordDecl *ClassDecl = Constructor->getParent();
13011   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13012 
13013   SynthesizedFunctionScope Scope(*this, Constructor);
13014 
13015   // The exception specification is needed because we are defining the
13016   // function.
13017   ResolveExceptionSpec(CurrentLocation,
13018                        Constructor->getType()->castAs<FunctionProtoType>());
13019   MarkVTableUsed(CurrentLocation, ClassDecl);
13020 
13021   // Add a context note for diagnostics produced after this point.
13022   Scope.addContextNote(CurrentLocation);
13023 
13024   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13025     Constructor->setInvalidDecl();
13026     return;
13027   }
13028 
13029   SourceLocation Loc = Constructor->getEndLoc().isValid()
13030                            ? Constructor->getEndLoc()
13031                            : Constructor->getLocation();
13032   Constructor->setBody(new (Context) CompoundStmt(Loc));
13033   Constructor->markUsed(Context);
13034 
13035   if (ASTMutationListener *L = getASTMutationListener()) {
13036     L->CompletedImplicitDefinition(Constructor);
13037   }
13038 
13039   DiagnoseUninitializedFields(*this, Constructor);
13040 }
13041 
13042 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13043   // Perform any delayed checks on exception specifications.
13044   CheckDelayedMemberExceptionSpecs();
13045 }
13046 
13047 /// Find or create the fake constructor we synthesize to model constructing an
13048 /// object of a derived class via a constructor of a base class.
13049 CXXConstructorDecl *
13050 Sema::findInheritingConstructor(SourceLocation Loc,
13051                                 CXXConstructorDecl *BaseCtor,
13052                                 ConstructorUsingShadowDecl *Shadow) {
13053   CXXRecordDecl *Derived = Shadow->getParent();
13054   SourceLocation UsingLoc = Shadow->getLocation();
13055 
13056   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13057   // For now we use the name of the base class constructor as a member of the
13058   // derived class to indicate a (fake) inherited constructor name.
13059   DeclarationName Name = BaseCtor->getDeclName();
13060 
13061   // Check to see if we already have a fake constructor for this inherited
13062   // constructor call.
13063   for (NamedDecl *Ctor : Derived->lookup(Name))
13064     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13065                                ->getInheritedConstructor()
13066                                .getConstructor(),
13067                            BaseCtor))
13068       return cast<CXXConstructorDecl>(Ctor);
13069 
13070   DeclarationNameInfo NameInfo(Name, UsingLoc);
13071   TypeSourceInfo *TInfo =
13072       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13073   FunctionProtoTypeLoc ProtoLoc =
13074       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13075 
13076   // Check the inherited constructor is valid and find the list of base classes
13077   // from which it was inherited.
13078   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13079 
13080   bool Constexpr =
13081       BaseCtor->isConstexpr() &&
13082       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13083                                         false, BaseCtor, &ICI);
13084 
13085   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13086       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13087       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13088       /*isImplicitlyDeclared=*/true,
13089       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13090       InheritedConstructor(Shadow, BaseCtor),
13091       BaseCtor->getTrailingRequiresClause());
13092   if (Shadow->isInvalidDecl())
13093     DerivedCtor->setInvalidDecl();
13094 
13095   // Build an unevaluated exception specification for this fake constructor.
13096   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13097   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13098   EPI.ExceptionSpec.Type = EST_Unevaluated;
13099   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13100   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13101                                                FPT->getParamTypes(), EPI));
13102 
13103   // Build the parameter declarations.
13104   SmallVector<ParmVarDecl *, 16> ParamDecls;
13105   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13106     TypeSourceInfo *TInfo =
13107         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13108     ParmVarDecl *PD = ParmVarDecl::Create(
13109         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13110         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13111     PD->setScopeInfo(0, I);
13112     PD->setImplicit();
13113     // Ensure attributes are propagated onto parameters (this matters for
13114     // format, pass_object_size, ...).
13115     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13116     ParamDecls.push_back(PD);
13117     ProtoLoc.setParam(I, PD);
13118   }
13119 
13120   // Set up the new constructor.
13121   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13122   DerivedCtor->setAccess(BaseCtor->getAccess());
13123   DerivedCtor->setParams(ParamDecls);
13124   Derived->addDecl(DerivedCtor);
13125 
13126   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13127     SetDeclDeleted(DerivedCtor, UsingLoc);
13128 
13129   return DerivedCtor;
13130 }
13131 
13132 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13133   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13134                                Ctor->getInheritedConstructor().getShadowDecl());
13135   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13136                             /*Diagnose*/true);
13137 }
13138 
13139 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13140                                        CXXConstructorDecl *Constructor) {
13141   CXXRecordDecl *ClassDecl = Constructor->getParent();
13142   assert(Constructor->getInheritedConstructor() &&
13143          !Constructor->doesThisDeclarationHaveABody() &&
13144          !Constructor->isDeleted());
13145   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13146     return;
13147 
13148   // Initializations are performed "as if by a defaulted default constructor",
13149   // so enter the appropriate scope.
13150   SynthesizedFunctionScope Scope(*this, Constructor);
13151 
13152   // The exception specification is needed because we are defining the
13153   // function.
13154   ResolveExceptionSpec(CurrentLocation,
13155                        Constructor->getType()->castAs<FunctionProtoType>());
13156   MarkVTableUsed(CurrentLocation, ClassDecl);
13157 
13158   // Add a context note for diagnostics produced after this point.
13159   Scope.addContextNote(CurrentLocation);
13160 
13161   ConstructorUsingShadowDecl *Shadow =
13162       Constructor->getInheritedConstructor().getShadowDecl();
13163   CXXConstructorDecl *InheritedCtor =
13164       Constructor->getInheritedConstructor().getConstructor();
13165 
13166   // [class.inhctor.init]p1:
13167   //   initialization proceeds as if a defaulted default constructor is used to
13168   //   initialize the D object and each base class subobject from which the
13169   //   constructor was inherited
13170 
13171   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13172   CXXRecordDecl *RD = Shadow->getParent();
13173   SourceLocation InitLoc = Shadow->getLocation();
13174 
13175   // Build explicit initializers for all base classes from which the
13176   // constructor was inherited.
13177   SmallVector<CXXCtorInitializer*, 8> Inits;
13178   for (bool VBase : {false, true}) {
13179     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13180       if (B.isVirtual() != VBase)
13181         continue;
13182 
13183       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13184       if (!BaseRD)
13185         continue;
13186 
13187       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13188       if (!BaseCtor.first)
13189         continue;
13190 
13191       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13192       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13193           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13194 
13195       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13196       Inits.push_back(new (Context) CXXCtorInitializer(
13197           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13198           SourceLocation()));
13199     }
13200   }
13201 
13202   // We now proceed as if for a defaulted default constructor, with the relevant
13203   // initializers replaced.
13204 
13205   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13206     Constructor->setInvalidDecl();
13207     return;
13208   }
13209 
13210   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13211   Constructor->markUsed(Context);
13212 
13213   if (ASTMutationListener *L = getASTMutationListener()) {
13214     L->CompletedImplicitDefinition(Constructor);
13215   }
13216 
13217   DiagnoseUninitializedFields(*this, Constructor);
13218 }
13219 
13220 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13221   // C++ [class.dtor]p2:
13222   //   If a class has no user-declared destructor, a destructor is
13223   //   declared implicitly. An implicitly-declared destructor is an
13224   //   inline public member of its class.
13225   assert(ClassDecl->needsImplicitDestructor());
13226 
13227   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13228   if (DSM.isAlreadyBeingDeclared())
13229     return nullptr;
13230 
13231   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13232                                                      CXXDestructor,
13233                                                      false);
13234 
13235   // Create the actual destructor declaration.
13236   CanQualType ClassType
13237     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13238   SourceLocation ClassLoc = ClassDecl->getLocation();
13239   DeclarationName Name
13240     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13241   DeclarationNameInfo NameInfo(Name, ClassLoc);
13242   CXXDestructorDecl *Destructor =
13243       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13244                                 QualType(), nullptr, /*isInline=*/true,
13245                                 /*isImplicitlyDeclared=*/true,
13246                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13247   Destructor->setAccess(AS_public);
13248   Destructor->setDefaulted();
13249 
13250   if (getLangOpts().CUDA) {
13251     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13252                                             Destructor,
13253                                             /* ConstRHS */ false,
13254                                             /* Diagnose */ false);
13255   }
13256 
13257   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13258 
13259   // We don't need to use SpecialMemberIsTrivial here; triviality for
13260   // destructors is easy to compute.
13261   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13262   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13263                                 ClassDecl->hasTrivialDestructorForCall());
13264 
13265   // Note that we have declared this destructor.
13266   ++getASTContext().NumImplicitDestructorsDeclared;
13267 
13268   Scope *S = getScopeForContext(ClassDecl);
13269   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13270 
13271   // We can't check whether an implicit destructor is deleted before we complete
13272   // the definition of the class, because its validity depends on the alignment
13273   // of the class. We'll check this from ActOnFields once the class is complete.
13274   if (ClassDecl->isCompleteDefinition() &&
13275       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13276     SetDeclDeleted(Destructor, ClassLoc);
13277 
13278   // Introduce this destructor into its scope.
13279   if (S)
13280     PushOnScopeChains(Destructor, S, false);
13281   ClassDecl->addDecl(Destructor);
13282 
13283   return Destructor;
13284 }
13285 
13286 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13287                                     CXXDestructorDecl *Destructor) {
13288   assert((Destructor->isDefaulted() &&
13289           !Destructor->doesThisDeclarationHaveABody() &&
13290           !Destructor->isDeleted()) &&
13291          "DefineImplicitDestructor - call it for implicit default dtor");
13292   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13293     return;
13294 
13295   CXXRecordDecl *ClassDecl = Destructor->getParent();
13296   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13297 
13298   SynthesizedFunctionScope Scope(*this, Destructor);
13299 
13300   // The exception specification is needed because we are defining the
13301   // function.
13302   ResolveExceptionSpec(CurrentLocation,
13303                        Destructor->getType()->castAs<FunctionProtoType>());
13304   MarkVTableUsed(CurrentLocation, ClassDecl);
13305 
13306   // Add a context note for diagnostics produced after this point.
13307   Scope.addContextNote(CurrentLocation);
13308 
13309   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13310                                          Destructor->getParent());
13311 
13312   if (CheckDestructor(Destructor)) {
13313     Destructor->setInvalidDecl();
13314     return;
13315   }
13316 
13317   SourceLocation Loc = Destructor->getEndLoc().isValid()
13318                            ? Destructor->getEndLoc()
13319                            : Destructor->getLocation();
13320   Destructor->setBody(new (Context) CompoundStmt(Loc));
13321   Destructor->markUsed(Context);
13322 
13323   if (ASTMutationListener *L = getASTMutationListener()) {
13324     L->CompletedImplicitDefinition(Destructor);
13325   }
13326 }
13327 
13328 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13329                                           CXXDestructorDecl *Destructor) {
13330   if (Destructor->isInvalidDecl())
13331     return;
13332 
13333   CXXRecordDecl *ClassDecl = Destructor->getParent();
13334   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13335          "implicit complete dtors unneeded outside MS ABI");
13336   assert(ClassDecl->getNumVBases() > 0 &&
13337          "complete dtor only exists for classes with vbases");
13338 
13339   SynthesizedFunctionScope Scope(*this, Destructor);
13340 
13341   // Add a context note for diagnostics produced after this point.
13342   Scope.addContextNote(CurrentLocation);
13343 
13344   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13345 }
13346 
13347 /// Perform any semantic analysis which needs to be delayed until all
13348 /// pending class member declarations have been parsed.
13349 void Sema::ActOnFinishCXXMemberDecls() {
13350   // If the context is an invalid C++ class, just suppress these checks.
13351   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13352     if (Record->isInvalidDecl()) {
13353       DelayedOverridingExceptionSpecChecks.clear();
13354       DelayedEquivalentExceptionSpecChecks.clear();
13355       return;
13356     }
13357     checkForMultipleExportedDefaultConstructors(*this, Record);
13358   }
13359 }
13360 
13361 void Sema::ActOnFinishCXXNonNestedClass() {
13362   referenceDLLExportedClassMethods();
13363 
13364   if (!DelayedDllExportMemberFunctions.empty()) {
13365     SmallVector<CXXMethodDecl*, 4> WorkList;
13366     std::swap(DelayedDllExportMemberFunctions, WorkList);
13367     for (CXXMethodDecl *M : WorkList) {
13368       DefineDefaultedFunction(*this, M, M->getLocation());
13369 
13370       // Pass the method to the consumer to get emitted. This is not necessary
13371       // for explicit instantiation definitions, as they will get emitted
13372       // anyway.
13373       if (M->getParent()->getTemplateSpecializationKind() !=
13374           TSK_ExplicitInstantiationDefinition)
13375         ActOnFinishInlineFunctionDef(M);
13376     }
13377   }
13378 }
13379 
13380 void Sema::referenceDLLExportedClassMethods() {
13381   if (!DelayedDllExportClasses.empty()) {
13382     // Calling ReferenceDllExportedMembers might cause the current function to
13383     // be called again, so use a local copy of DelayedDllExportClasses.
13384     SmallVector<CXXRecordDecl *, 4> WorkList;
13385     std::swap(DelayedDllExportClasses, WorkList);
13386     for (CXXRecordDecl *Class : WorkList)
13387       ReferenceDllExportedMembers(*this, Class);
13388   }
13389 }
13390 
13391 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13392   assert(getLangOpts().CPlusPlus11 &&
13393          "adjusting dtor exception specs was introduced in c++11");
13394 
13395   if (Destructor->isDependentContext())
13396     return;
13397 
13398   // C++11 [class.dtor]p3:
13399   //   A declaration of a destructor that does not have an exception-
13400   //   specification is implicitly considered to have the same exception-
13401   //   specification as an implicit declaration.
13402   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13403   if (DtorType->hasExceptionSpec())
13404     return;
13405 
13406   // Replace the destructor's type, building off the existing one. Fortunately,
13407   // the only thing of interest in the destructor type is its extended info.
13408   // The return and arguments are fixed.
13409   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13410   EPI.ExceptionSpec.Type = EST_Unevaluated;
13411   EPI.ExceptionSpec.SourceDecl = Destructor;
13412   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13413 
13414   // FIXME: If the destructor has a body that could throw, and the newly created
13415   // spec doesn't allow exceptions, we should emit a warning, because this
13416   // change in behavior can break conforming C++03 programs at runtime.
13417   // However, we don't have a body or an exception specification yet, so it
13418   // needs to be done somewhere else.
13419 }
13420 
13421 namespace {
13422 /// An abstract base class for all helper classes used in building the
13423 //  copy/move operators. These classes serve as factory functions and help us
13424 //  avoid using the same Expr* in the AST twice.
13425 class ExprBuilder {
13426   ExprBuilder(const ExprBuilder&) = delete;
13427   ExprBuilder &operator=(const ExprBuilder&) = delete;
13428 
13429 protected:
13430   static Expr *assertNotNull(Expr *E) {
13431     assert(E && "Expression construction must not fail.");
13432     return E;
13433   }
13434 
13435 public:
13436   ExprBuilder() {}
13437   virtual ~ExprBuilder() {}
13438 
13439   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13440 };
13441 
13442 class RefBuilder: public ExprBuilder {
13443   VarDecl *Var;
13444   QualType VarType;
13445 
13446 public:
13447   Expr *build(Sema &S, SourceLocation Loc) const override {
13448     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13449   }
13450 
13451   RefBuilder(VarDecl *Var, QualType VarType)
13452       : Var(Var), VarType(VarType) {}
13453 };
13454 
13455 class ThisBuilder: public ExprBuilder {
13456 public:
13457   Expr *build(Sema &S, SourceLocation Loc) const override {
13458     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13459   }
13460 };
13461 
13462 class CastBuilder: public ExprBuilder {
13463   const ExprBuilder &Builder;
13464   QualType Type;
13465   ExprValueKind Kind;
13466   const CXXCastPath &Path;
13467 
13468 public:
13469   Expr *build(Sema &S, SourceLocation Loc) const override {
13470     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13471                                              CK_UncheckedDerivedToBase, Kind,
13472                                              &Path).get());
13473   }
13474 
13475   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13476               const CXXCastPath &Path)
13477       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13478 };
13479 
13480 class DerefBuilder: public ExprBuilder {
13481   const ExprBuilder &Builder;
13482 
13483 public:
13484   Expr *build(Sema &S, SourceLocation Loc) const override {
13485     return assertNotNull(
13486         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13487   }
13488 
13489   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13490 };
13491 
13492 class MemberBuilder: public ExprBuilder {
13493   const ExprBuilder &Builder;
13494   QualType Type;
13495   CXXScopeSpec SS;
13496   bool IsArrow;
13497   LookupResult &MemberLookup;
13498 
13499 public:
13500   Expr *build(Sema &S, SourceLocation Loc) const override {
13501     return assertNotNull(S.BuildMemberReferenceExpr(
13502         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13503         nullptr, MemberLookup, nullptr, nullptr).get());
13504   }
13505 
13506   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13507                 LookupResult &MemberLookup)
13508       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13509         MemberLookup(MemberLookup) {}
13510 };
13511 
13512 class MoveCastBuilder: public ExprBuilder {
13513   const ExprBuilder &Builder;
13514 
13515 public:
13516   Expr *build(Sema &S, SourceLocation Loc) const override {
13517     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13518   }
13519 
13520   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13521 };
13522 
13523 class LvalueConvBuilder: public ExprBuilder {
13524   const ExprBuilder &Builder;
13525 
13526 public:
13527   Expr *build(Sema &S, SourceLocation Loc) const override {
13528     return assertNotNull(
13529         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13530   }
13531 
13532   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13533 };
13534 
13535 class SubscriptBuilder: public ExprBuilder {
13536   const ExprBuilder &Base;
13537   const ExprBuilder &Index;
13538 
13539 public:
13540   Expr *build(Sema &S, SourceLocation Loc) const override {
13541     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13542         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13543   }
13544 
13545   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13546       : Base(Base), Index(Index) {}
13547 };
13548 
13549 } // end anonymous namespace
13550 
13551 /// When generating a defaulted copy or move assignment operator, if a field
13552 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13553 /// do so. This optimization only applies for arrays of scalars, and for arrays
13554 /// of class type where the selected copy/move-assignment operator is trivial.
13555 static StmtResult
13556 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13557                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13558   // Compute the size of the memory buffer to be copied.
13559   QualType SizeType = S.Context.getSizeType();
13560   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13561                    S.Context.getTypeSizeInChars(T).getQuantity());
13562 
13563   // Take the address of the field references for "from" and "to". We
13564   // directly construct UnaryOperators here because semantic analysis
13565   // does not permit us to take the address of an xvalue.
13566   Expr *From = FromB.build(S, Loc);
13567   From = UnaryOperator::Create(
13568       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13569       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13570   Expr *To = ToB.build(S, Loc);
13571   To = UnaryOperator::Create(
13572       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13573       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13574 
13575   const Type *E = T->getBaseElementTypeUnsafe();
13576   bool NeedsCollectableMemCpy =
13577       E->isRecordType() &&
13578       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13579 
13580   // Create a reference to the __builtin_objc_memmove_collectable function
13581   StringRef MemCpyName = NeedsCollectableMemCpy ?
13582     "__builtin_objc_memmove_collectable" :
13583     "__builtin_memcpy";
13584   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13585                  Sema::LookupOrdinaryName);
13586   S.LookupName(R, S.TUScope, true);
13587 
13588   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13589   if (!MemCpy)
13590     // Something went horribly wrong earlier, and we will have complained
13591     // about it.
13592     return StmtError();
13593 
13594   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13595                                             VK_RValue, Loc, nullptr);
13596   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13597 
13598   Expr *CallArgs[] = {
13599     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13600   };
13601   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13602                                     Loc, CallArgs, Loc);
13603 
13604   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13605   return Call.getAs<Stmt>();
13606 }
13607 
13608 /// Builds a statement that copies/moves the given entity from \p From to
13609 /// \c To.
13610 ///
13611 /// This routine is used to copy/move the members of a class with an
13612 /// implicitly-declared copy/move assignment operator. When the entities being
13613 /// copied are arrays, this routine builds for loops to copy them.
13614 ///
13615 /// \param S The Sema object used for type-checking.
13616 ///
13617 /// \param Loc The location where the implicit copy/move is being generated.
13618 ///
13619 /// \param T The type of the expressions being copied/moved. Both expressions
13620 /// must have this type.
13621 ///
13622 /// \param To The expression we are copying/moving to.
13623 ///
13624 /// \param From The expression we are copying/moving from.
13625 ///
13626 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13627 /// Otherwise, it's a non-static member subobject.
13628 ///
13629 /// \param Copying Whether we're copying or moving.
13630 ///
13631 /// \param Depth Internal parameter recording the depth of the recursion.
13632 ///
13633 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13634 /// if a memcpy should be used instead.
13635 static StmtResult
13636 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13637                                  const ExprBuilder &To, const ExprBuilder &From,
13638                                  bool CopyingBaseSubobject, bool Copying,
13639                                  unsigned Depth = 0) {
13640   // C++11 [class.copy]p28:
13641   //   Each subobject is assigned in the manner appropriate to its type:
13642   //
13643   //     - if the subobject is of class type, as if by a call to operator= with
13644   //       the subobject as the object expression and the corresponding
13645   //       subobject of x as a single function argument (as if by explicit
13646   //       qualification; that is, ignoring any possible virtual overriding
13647   //       functions in more derived classes);
13648   //
13649   // C++03 [class.copy]p13:
13650   //     - if the subobject is of class type, the copy assignment operator for
13651   //       the class is used (as if by explicit qualification; that is,
13652   //       ignoring any possible virtual overriding functions in more derived
13653   //       classes);
13654   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13655     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13656 
13657     // Look for operator=.
13658     DeclarationName Name
13659       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13660     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13661     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13662 
13663     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13664     // operator.
13665     if (!S.getLangOpts().CPlusPlus11) {
13666       LookupResult::Filter F = OpLookup.makeFilter();
13667       while (F.hasNext()) {
13668         NamedDecl *D = F.next();
13669         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13670           if (Method->isCopyAssignmentOperator() ||
13671               (!Copying && Method->isMoveAssignmentOperator()))
13672             continue;
13673 
13674         F.erase();
13675       }
13676       F.done();
13677     }
13678 
13679     // Suppress the protected check (C++ [class.protected]) for each of the
13680     // assignment operators we found. This strange dance is required when
13681     // we're assigning via a base classes's copy-assignment operator. To
13682     // ensure that we're getting the right base class subobject (without
13683     // ambiguities), we need to cast "this" to that subobject type; to
13684     // ensure that we don't go through the virtual call mechanism, we need
13685     // to qualify the operator= name with the base class (see below). However,
13686     // this means that if the base class has a protected copy assignment
13687     // operator, the protected member access check will fail. So, we
13688     // rewrite "protected" access to "public" access in this case, since we
13689     // know by construction that we're calling from a derived class.
13690     if (CopyingBaseSubobject) {
13691       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13692            L != LEnd; ++L) {
13693         if (L.getAccess() == AS_protected)
13694           L.setAccess(AS_public);
13695       }
13696     }
13697 
13698     // Create the nested-name-specifier that will be used to qualify the
13699     // reference to operator=; this is required to suppress the virtual
13700     // call mechanism.
13701     CXXScopeSpec SS;
13702     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13703     SS.MakeTrivial(S.Context,
13704                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13705                                                CanonicalT),
13706                    Loc);
13707 
13708     // Create the reference to operator=.
13709     ExprResult OpEqualRef
13710       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13711                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13712                                    /*FirstQualifierInScope=*/nullptr,
13713                                    OpLookup,
13714                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13715                                    /*SuppressQualifierCheck=*/true);
13716     if (OpEqualRef.isInvalid())
13717       return StmtError();
13718 
13719     // Build the call to the assignment operator.
13720 
13721     Expr *FromInst = From.build(S, Loc);
13722     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13723                                                   OpEqualRef.getAs<Expr>(),
13724                                                   Loc, FromInst, Loc);
13725     if (Call.isInvalid())
13726       return StmtError();
13727 
13728     // If we built a call to a trivial 'operator=' while copying an array,
13729     // bail out. We'll replace the whole shebang with a memcpy.
13730     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13731     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13732       return StmtResult((Stmt*)nullptr);
13733 
13734     // Convert to an expression-statement, and clean up any produced
13735     // temporaries.
13736     return S.ActOnExprStmt(Call);
13737   }
13738 
13739   //     - if the subobject is of scalar type, the built-in assignment
13740   //       operator is used.
13741   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13742   if (!ArrayTy) {
13743     ExprResult Assignment = S.CreateBuiltinBinOp(
13744         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13745     if (Assignment.isInvalid())
13746       return StmtError();
13747     return S.ActOnExprStmt(Assignment);
13748   }
13749 
13750   //     - if the subobject is an array, each element is assigned, in the
13751   //       manner appropriate to the element type;
13752 
13753   // Construct a loop over the array bounds, e.g.,
13754   //
13755   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13756   //
13757   // that will copy each of the array elements.
13758   QualType SizeType = S.Context.getSizeType();
13759 
13760   // Create the iteration variable.
13761   IdentifierInfo *IterationVarName = nullptr;
13762   {
13763     SmallString<8> Str;
13764     llvm::raw_svector_ostream OS(Str);
13765     OS << "__i" << Depth;
13766     IterationVarName = &S.Context.Idents.get(OS.str());
13767   }
13768   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13769                                           IterationVarName, SizeType,
13770                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13771                                           SC_None);
13772 
13773   // Initialize the iteration variable to zero.
13774   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13775   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13776 
13777   // Creates a reference to the iteration variable.
13778   RefBuilder IterationVarRef(IterationVar, SizeType);
13779   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13780 
13781   // Create the DeclStmt that holds the iteration variable.
13782   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13783 
13784   // Subscript the "from" and "to" expressions with the iteration variable.
13785   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13786   MoveCastBuilder FromIndexMove(FromIndexCopy);
13787   const ExprBuilder *FromIndex;
13788   if (Copying)
13789     FromIndex = &FromIndexCopy;
13790   else
13791     FromIndex = &FromIndexMove;
13792 
13793   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13794 
13795   // Build the copy/move for an individual element of the array.
13796   StmtResult Copy =
13797     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13798                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13799                                      Copying, Depth + 1);
13800   // Bail out if copying fails or if we determined that we should use memcpy.
13801   if (Copy.isInvalid() || !Copy.get())
13802     return Copy;
13803 
13804   // Create the comparison against the array bound.
13805   llvm::APInt Upper
13806     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13807   Expr *Comparison = BinaryOperator::Create(
13808       S.Context, IterationVarRefRVal.build(S, Loc),
13809       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13810       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13811 
13812   // Create the pre-increment of the iteration variable. We can determine
13813   // whether the increment will overflow based on the value of the array
13814   // bound.
13815   Expr *Increment = UnaryOperator::Create(
13816       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13817       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13818 
13819   // Construct the loop that copies all elements of this array.
13820   return S.ActOnForStmt(
13821       Loc, Loc, InitStmt,
13822       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13823       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13824 }
13825 
13826 static StmtResult
13827 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13828                       const ExprBuilder &To, const ExprBuilder &From,
13829                       bool CopyingBaseSubobject, bool Copying) {
13830   // Maybe we should use a memcpy?
13831   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13832       T.isTriviallyCopyableType(S.Context))
13833     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13834 
13835   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13836                                                      CopyingBaseSubobject,
13837                                                      Copying, 0));
13838 
13839   // If we ended up picking a trivial assignment operator for an array of a
13840   // non-trivially-copyable class type, just emit a memcpy.
13841   if (!Result.isInvalid() && !Result.get())
13842     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13843 
13844   return Result;
13845 }
13846 
13847 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13848   // Note: The following rules are largely analoguous to the copy
13849   // constructor rules. Note that virtual bases are not taken into account
13850   // for determining the argument type of the operator. Note also that
13851   // operators taking an object instead of a reference are allowed.
13852   assert(ClassDecl->needsImplicitCopyAssignment());
13853 
13854   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13855   if (DSM.isAlreadyBeingDeclared())
13856     return nullptr;
13857 
13858   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13859   LangAS AS = getDefaultCXXMethodAddrSpace();
13860   if (AS != LangAS::Default)
13861     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13862   QualType RetType = Context.getLValueReferenceType(ArgType);
13863   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13864   if (Const)
13865     ArgType = ArgType.withConst();
13866 
13867   ArgType = Context.getLValueReferenceType(ArgType);
13868 
13869   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13870                                                      CXXCopyAssignment,
13871                                                      Const);
13872 
13873   //   An implicitly-declared copy assignment operator is an inline public
13874   //   member of its class.
13875   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13876   SourceLocation ClassLoc = ClassDecl->getLocation();
13877   DeclarationNameInfo NameInfo(Name, ClassLoc);
13878   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13879       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13880       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13881       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13882       SourceLocation());
13883   CopyAssignment->setAccess(AS_public);
13884   CopyAssignment->setDefaulted();
13885   CopyAssignment->setImplicit();
13886 
13887   if (getLangOpts().CUDA) {
13888     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13889                                             CopyAssignment,
13890                                             /* ConstRHS */ Const,
13891                                             /* Diagnose */ false);
13892   }
13893 
13894   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13895 
13896   // Add the parameter to the operator.
13897   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13898                                                ClassLoc, ClassLoc,
13899                                                /*Id=*/nullptr, ArgType,
13900                                                /*TInfo=*/nullptr, SC_None,
13901                                                nullptr);
13902   CopyAssignment->setParams(FromParam);
13903 
13904   CopyAssignment->setTrivial(
13905     ClassDecl->needsOverloadResolutionForCopyAssignment()
13906       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13907       : ClassDecl->hasTrivialCopyAssignment());
13908 
13909   // Note that we have added this copy-assignment operator.
13910   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13911 
13912   Scope *S = getScopeForContext(ClassDecl);
13913   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13914 
13915   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13916     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13917     SetDeclDeleted(CopyAssignment, ClassLoc);
13918   }
13919 
13920   if (S)
13921     PushOnScopeChains(CopyAssignment, S, false);
13922   ClassDecl->addDecl(CopyAssignment);
13923 
13924   return CopyAssignment;
13925 }
13926 
13927 /// Diagnose an implicit copy operation for a class which is odr-used, but
13928 /// which is deprecated because the class has a user-declared copy constructor,
13929 /// copy assignment operator, or destructor.
13930 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13931   assert(CopyOp->isImplicit());
13932 
13933   CXXRecordDecl *RD = CopyOp->getParent();
13934   CXXMethodDecl *UserDeclaredOperation = nullptr;
13935 
13936   // In Microsoft mode, assignment operations don't affect constructors and
13937   // vice versa.
13938   if (RD->hasUserDeclaredDestructor()) {
13939     UserDeclaredOperation = RD->getDestructor();
13940   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13941              RD->hasUserDeclaredCopyConstructor() &&
13942              !S.getLangOpts().MSVCCompat) {
13943     // Find any user-declared copy constructor.
13944     for (auto *I : RD->ctors()) {
13945       if (I->isCopyConstructor()) {
13946         UserDeclaredOperation = I;
13947         break;
13948       }
13949     }
13950     assert(UserDeclaredOperation);
13951   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13952              RD->hasUserDeclaredCopyAssignment() &&
13953              !S.getLangOpts().MSVCCompat) {
13954     // Find any user-declared move assignment operator.
13955     for (auto *I : RD->methods()) {
13956       if (I->isCopyAssignmentOperator()) {
13957         UserDeclaredOperation = I;
13958         break;
13959       }
13960     }
13961     assert(UserDeclaredOperation);
13962   }
13963 
13964   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13965     S.Diag(UserDeclaredOperation->getLocation(),
13966            isa<CXXDestructorDecl>(UserDeclaredOperation)
13967                ? diag::warn_deprecated_copy_dtor_operation
13968                : diag::warn_deprecated_copy_operation)
13969         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13970   }
13971 }
13972 
13973 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13974                                         CXXMethodDecl *CopyAssignOperator) {
13975   assert((CopyAssignOperator->isDefaulted() &&
13976           CopyAssignOperator->isOverloadedOperator() &&
13977           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13978           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13979           !CopyAssignOperator->isDeleted()) &&
13980          "DefineImplicitCopyAssignment called for wrong function");
13981   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13982     return;
13983 
13984   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13985   if (ClassDecl->isInvalidDecl()) {
13986     CopyAssignOperator->setInvalidDecl();
13987     return;
13988   }
13989 
13990   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13991 
13992   // The exception specification is needed because we are defining the
13993   // function.
13994   ResolveExceptionSpec(CurrentLocation,
13995                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13996 
13997   // Add a context note for diagnostics produced after this point.
13998   Scope.addContextNote(CurrentLocation);
13999 
14000   // C++11 [class.copy]p18:
14001   //   The [definition of an implicitly declared copy assignment operator] is
14002   //   deprecated if the class has a user-declared copy constructor or a
14003   //   user-declared destructor.
14004   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14005     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14006 
14007   // C++0x [class.copy]p30:
14008   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14009   //   for a non-union class X performs memberwise copy assignment of its
14010   //   subobjects. The direct base classes of X are assigned first, in the
14011   //   order of their declaration in the base-specifier-list, and then the
14012   //   immediate non-static data members of X are assigned, in the order in
14013   //   which they were declared in the class definition.
14014 
14015   // The statements that form the synthesized function body.
14016   SmallVector<Stmt*, 8> Statements;
14017 
14018   // The parameter for the "other" object, which we are copying from.
14019   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14020   Qualifiers OtherQuals = Other->getType().getQualifiers();
14021   QualType OtherRefType = Other->getType();
14022   if (const LValueReferenceType *OtherRef
14023                                 = OtherRefType->getAs<LValueReferenceType>()) {
14024     OtherRefType = OtherRef->getPointeeType();
14025     OtherQuals = OtherRefType.getQualifiers();
14026   }
14027 
14028   // Our location for everything implicitly-generated.
14029   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14030                            ? CopyAssignOperator->getEndLoc()
14031                            : CopyAssignOperator->getLocation();
14032 
14033   // Builds a DeclRefExpr for the "other" object.
14034   RefBuilder OtherRef(Other, OtherRefType);
14035 
14036   // Builds the "this" pointer.
14037   ThisBuilder This;
14038 
14039   // Assign base classes.
14040   bool Invalid = false;
14041   for (auto &Base : ClassDecl->bases()) {
14042     // Form the assignment:
14043     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14044     QualType BaseType = Base.getType().getUnqualifiedType();
14045     if (!BaseType->isRecordType()) {
14046       Invalid = true;
14047       continue;
14048     }
14049 
14050     CXXCastPath BasePath;
14051     BasePath.push_back(&Base);
14052 
14053     // Construct the "from" expression, which is an implicit cast to the
14054     // appropriately-qualified base type.
14055     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14056                      VK_LValue, BasePath);
14057 
14058     // Dereference "this".
14059     DerefBuilder DerefThis(This);
14060     CastBuilder To(DerefThis,
14061                    Context.getQualifiedType(
14062                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14063                    VK_LValue, BasePath);
14064 
14065     // Build the copy.
14066     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14067                                             To, From,
14068                                             /*CopyingBaseSubobject=*/true,
14069                                             /*Copying=*/true);
14070     if (Copy.isInvalid()) {
14071       CopyAssignOperator->setInvalidDecl();
14072       return;
14073     }
14074 
14075     // Success! Record the copy.
14076     Statements.push_back(Copy.getAs<Expr>());
14077   }
14078 
14079   // Assign non-static members.
14080   for (auto *Field : ClassDecl->fields()) {
14081     // FIXME: We should form some kind of AST representation for the implied
14082     // memcpy in a union copy operation.
14083     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14084       continue;
14085 
14086     if (Field->isInvalidDecl()) {
14087       Invalid = true;
14088       continue;
14089     }
14090 
14091     // Check for members of reference type; we can't copy those.
14092     if (Field->getType()->isReferenceType()) {
14093       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14094         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14095       Diag(Field->getLocation(), diag::note_declared_at);
14096       Invalid = true;
14097       continue;
14098     }
14099 
14100     // Check for members of const-qualified, non-class type.
14101     QualType BaseType = Context.getBaseElementType(Field->getType());
14102     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14103       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14104         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14105       Diag(Field->getLocation(), diag::note_declared_at);
14106       Invalid = true;
14107       continue;
14108     }
14109 
14110     // Suppress assigning zero-width bitfields.
14111     if (Field->isZeroLengthBitField(Context))
14112       continue;
14113 
14114     QualType FieldType = Field->getType().getNonReferenceType();
14115     if (FieldType->isIncompleteArrayType()) {
14116       assert(ClassDecl->hasFlexibleArrayMember() &&
14117              "Incomplete array type is not valid");
14118       continue;
14119     }
14120 
14121     // Build references to the field in the object we're copying from and to.
14122     CXXScopeSpec SS; // Intentionally empty
14123     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14124                               LookupMemberName);
14125     MemberLookup.addDecl(Field);
14126     MemberLookup.resolveKind();
14127 
14128     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14129 
14130     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14131 
14132     // Build the copy of this field.
14133     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14134                                             To, From,
14135                                             /*CopyingBaseSubobject=*/false,
14136                                             /*Copying=*/true);
14137     if (Copy.isInvalid()) {
14138       CopyAssignOperator->setInvalidDecl();
14139       return;
14140     }
14141 
14142     // Success! Record the copy.
14143     Statements.push_back(Copy.getAs<Stmt>());
14144   }
14145 
14146   if (!Invalid) {
14147     // Add a "return *this;"
14148     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14149 
14150     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14151     if (Return.isInvalid())
14152       Invalid = true;
14153     else
14154       Statements.push_back(Return.getAs<Stmt>());
14155   }
14156 
14157   if (Invalid) {
14158     CopyAssignOperator->setInvalidDecl();
14159     return;
14160   }
14161 
14162   StmtResult Body;
14163   {
14164     CompoundScopeRAII CompoundScope(*this);
14165     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14166                              /*isStmtExpr=*/false);
14167     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14168   }
14169   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14170   CopyAssignOperator->markUsed(Context);
14171 
14172   if (ASTMutationListener *L = getASTMutationListener()) {
14173     L->CompletedImplicitDefinition(CopyAssignOperator);
14174   }
14175 }
14176 
14177 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14178   assert(ClassDecl->needsImplicitMoveAssignment());
14179 
14180   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14181   if (DSM.isAlreadyBeingDeclared())
14182     return nullptr;
14183 
14184   // Note: The following rules are largely analoguous to the move
14185   // constructor rules.
14186 
14187   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14188   LangAS AS = getDefaultCXXMethodAddrSpace();
14189   if (AS != LangAS::Default)
14190     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14191   QualType RetType = Context.getLValueReferenceType(ArgType);
14192   ArgType = Context.getRValueReferenceType(ArgType);
14193 
14194   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14195                                                      CXXMoveAssignment,
14196                                                      false);
14197 
14198   //   An implicitly-declared move assignment operator is an inline public
14199   //   member of its class.
14200   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14201   SourceLocation ClassLoc = ClassDecl->getLocation();
14202   DeclarationNameInfo NameInfo(Name, ClassLoc);
14203   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14204       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14205       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14206       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14207       SourceLocation());
14208   MoveAssignment->setAccess(AS_public);
14209   MoveAssignment->setDefaulted();
14210   MoveAssignment->setImplicit();
14211 
14212   if (getLangOpts().CUDA) {
14213     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14214                                             MoveAssignment,
14215                                             /* ConstRHS */ false,
14216                                             /* Diagnose */ false);
14217   }
14218 
14219   // Build an exception specification pointing back at this member.
14220   FunctionProtoType::ExtProtoInfo EPI =
14221       getImplicitMethodEPI(*this, MoveAssignment);
14222   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14223 
14224   // Add the parameter to the operator.
14225   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14226                                                ClassLoc, ClassLoc,
14227                                                /*Id=*/nullptr, ArgType,
14228                                                /*TInfo=*/nullptr, SC_None,
14229                                                nullptr);
14230   MoveAssignment->setParams(FromParam);
14231 
14232   MoveAssignment->setTrivial(
14233     ClassDecl->needsOverloadResolutionForMoveAssignment()
14234       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14235       : ClassDecl->hasTrivialMoveAssignment());
14236 
14237   // Note that we have added this copy-assignment operator.
14238   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14239 
14240   Scope *S = getScopeForContext(ClassDecl);
14241   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14242 
14243   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14244     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14245     SetDeclDeleted(MoveAssignment, ClassLoc);
14246   }
14247 
14248   if (S)
14249     PushOnScopeChains(MoveAssignment, S, false);
14250   ClassDecl->addDecl(MoveAssignment);
14251 
14252   return MoveAssignment;
14253 }
14254 
14255 /// Check if we're implicitly defining a move assignment operator for a class
14256 /// with virtual bases. Such a move assignment might move-assign the virtual
14257 /// base multiple times.
14258 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14259                                                SourceLocation CurrentLocation) {
14260   assert(!Class->isDependentContext() && "should not define dependent move");
14261 
14262   // Only a virtual base could get implicitly move-assigned multiple times.
14263   // Only a non-trivial move assignment can observe this. We only want to
14264   // diagnose if we implicitly define an assignment operator that assigns
14265   // two base classes, both of which move-assign the same virtual base.
14266   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14267       Class->getNumBases() < 2)
14268     return;
14269 
14270   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14271   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14272   VBaseMap VBases;
14273 
14274   for (auto &BI : Class->bases()) {
14275     Worklist.push_back(&BI);
14276     while (!Worklist.empty()) {
14277       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14278       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14279 
14280       // If the base has no non-trivial move assignment operators,
14281       // we don't care about moves from it.
14282       if (!Base->hasNonTrivialMoveAssignment())
14283         continue;
14284 
14285       // If there's nothing virtual here, skip it.
14286       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14287         continue;
14288 
14289       // If we're not actually going to call a move assignment for this base,
14290       // or the selected move assignment is trivial, skip it.
14291       Sema::SpecialMemberOverloadResult SMOR =
14292         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14293                               /*ConstArg*/false, /*VolatileArg*/false,
14294                               /*RValueThis*/true, /*ConstThis*/false,
14295                               /*VolatileThis*/false);
14296       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14297           !SMOR.getMethod()->isMoveAssignmentOperator())
14298         continue;
14299 
14300       if (BaseSpec->isVirtual()) {
14301         // We're going to move-assign this virtual base, and its move
14302         // assignment operator is not trivial. If this can happen for
14303         // multiple distinct direct bases of Class, diagnose it. (If it
14304         // only happens in one base, we'll diagnose it when synthesizing
14305         // that base class's move assignment operator.)
14306         CXXBaseSpecifier *&Existing =
14307             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14308                 .first->second;
14309         if (Existing && Existing != &BI) {
14310           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14311             << Class << Base;
14312           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14313               << (Base->getCanonicalDecl() ==
14314                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14315               << Base << Existing->getType() << Existing->getSourceRange();
14316           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14317               << (Base->getCanonicalDecl() ==
14318                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14319               << Base << BI.getType() << BaseSpec->getSourceRange();
14320 
14321           // Only diagnose each vbase once.
14322           Existing = nullptr;
14323         }
14324       } else {
14325         // Only walk over bases that have defaulted move assignment operators.
14326         // We assume that any user-provided move assignment operator handles
14327         // the multiple-moves-of-vbase case itself somehow.
14328         if (!SMOR.getMethod()->isDefaulted())
14329           continue;
14330 
14331         // We're going to move the base classes of Base. Add them to the list.
14332         for (auto &BI : Base->bases())
14333           Worklist.push_back(&BI);
14334       }
14335     }
14336   }
14337 }
14338 
14339 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14340                                         CXXMethodDecl *MoveAssignOperator) {
14341   assert((MoveAssignOperator->isDefaulted() &&
14342           MoveAssignOperator->isOverloadedOperator() &&
14343           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14344           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14345           !MoveAssignOperator->isDeleted()) &&
14346          "DefineImplicitMoveAssignment called for wrong function");
14347   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14348     return;
14349 
14350   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14351   if (ClassDecl->isInvalidDecl()) {
14352     MoveAssignOperator->setInvalidDecl();
14353     return;
14354   }
14355 
14356   // C++0x [class.copy]p28:
14357   //   The implicitly-defined or move assignment operator for a non-union class
14358   //   X performs memberwise move assignment of its subobjects. The direct base
14359   //   classes of X are assigned first, in the order of their declaration in the
14360   //   base-specifier-list, and then the immediate non-static data members of X
14361   //   are assigned, in the order in which they were declared in the class
14362   //   definition.
14363 
14364   // Issue a warning if our implicit move assignment operator will move
14365   // from a virtual base more than once.
14366   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14367 
14368   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14369 
14370   // The exception specification is needed because we are defining the
14371   // function.
14372   ResolveExceptionSpec(CurrentLocation,
14373                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14374 
14375   // Add a context note for diagnostics produced after this point.
14376   Scope.addContextNote(CurrentLocation);
14377 
14378   // The statements that form the synthesized function body.
14379   SmallVector<Stmt*, 8> Statements;
14380 
14381   // The parameter for the "other" object, which we are move from.
14382   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14383   QualType OtherRefType =
14384       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14385 
14386   // Our location for everything implicitly-generated.
14387   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14388                            ? MoveAssignOperator->getEndLoc()
14389                            : MoveAssignOperator->getLocation();
14390 
14391   // Builds a reference to the "other" object.
14392   RefBuilder OtherRef(Other, OtherRefType);
14393   // Cast to rvalue.
14394   MoveCastBuilder MoveOther(OtherRef);
14395 
14396   // Builds the "this" pointer.
14397   ThisBuilder This;
14398 
14399   // Assign base classes.
14400   bool Invalid = false;
14401   for (auto &Base : ClassDecl->bases()) {
14402     // C++11 [class.copy]p28:
14403     //   It is unspecified whether subobjects representing virtual base classes
14404     //   are assigned more than once by the implicitly-defined copy assignment
14405     //   operator.
14406     // FIXME: Do not assign to a vbase that will be assigned by some other base
14407     // class. For a move-assignment, this can result in the vbase being moved
14408     // multiple times.
14409 
14410     // Form the assignment:
14411     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14412     QualType BaseType = Base.getType().getUnqualifiedType();
14413     if (!BaseType->isRecordType()) {
14414       Invalid = true;
14415       continue;
14416     }
14417 
14418     CXXCastPath BasePath;
14419     BasePath.push_back(&Base);
14420 
14421     // Construct the "from" expression, which is an implicit cast to the
14422     // appropriately-qualified base type.
14423     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14424 
14425     // Dereference "this".
14426     DerefBuilder DerefThis(This);
14427 
14428     // Implicitly cast "this" to the appropriately-qualified base type.
14429     CastBuilder To(DerefThis,
14430                    Context.getQualifiedType(
14431                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14432                    VK_LValue, BasePath);
14433 
14434     // Build the move.
14435     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14436                                             To, From,
14437                                             /*CopyingBaseSubobject=*/true,
14438                                             /*Copying=*/false);
14439     if (Move.isInvalid()) {
14440       MoveAssignOperator->setInvalidDecl();
14441       return;
14442     }
14443 
14444     // Success! Record the move.
14445     Statements.push_back(Move.getAs<Expr>());
14446   }
14447 
14448   // Assign non-static members.
14449   for (auto *Field : ClassDecl->fields()) {
14450     // FIXME: We should form some kind of AST representation for the implied
14451     // memcpy in a union copy operation.
14452     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14453       continue;
14454 
14455     if (Field->isInvalidDecl()) {
14456       Invalid = true;
14457       continue;
14458     }
14459 
14460     // Check for members of reference type; we can't move those.
14461     if (Field->getType()->isReferenceType()) {
14462       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14463         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14464       Diag(Field->getLocation(), diag::note_declared_at);
14465       Invalid = true;
14466       continue;
14467     }
14468 
14469     // Check for members of const-qualified, non-class type.
14470     QualType BaseType = Context.getBaseElementType(Field->getType());
14471     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14472       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14473         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14474       Diag(Field->getLocation(), diag::note_declared_at);
14475       Invalid = true;
14476       continue;
14477     }
14478 
14479     // Suppress assigning zero-width bitfields.
14480     if (Field->isZeroLengthBitField(Context))
14481       continue;
14482 
14483     QualType FieldType = Field->getType().getNonReferenceType();
14484     if (FieldType->isIncompleteArrayType()) {
14485       assert(ClassDecl->hasFlexibleArrayMember() &&
14486              "Incomplete array type is not valid");
14487       continue;
14488     }
14489 
14490     // Build references to the field in the object we're copying from and to.
14491     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14492                               LookupMemberName);
14493     MemberLookup.addDecl(Field);
14494     MemberLookup.resolveKind();
14495     MemberBuilder From(MoveOther, OtherRefType,
14496                        /*IsArrow=*/false, MemberLookup);
14497     MemberBuilder To(This, getCurrentThisType(),
14498                      /*IsArrow=*/true, MemberLookup);
14499 
14500     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14501         "Member reference with rvalue base must be rvalue except for reference "
14502         "members, which aren't allowed for move assignment.");
14503 
14504     // Build the move of this field.
14505     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14506                                             To, From,
14507                                             /*CopyingBaseSubobject=*/false,
14508                                             /*Copying=*/false);
14509     if (Move.isInvalid()) {
14510       MoveAssignOperator->setInvalidDecl();
14511       return;
14512     }
14513 
14514     // Success! Record the copy.
14515     Statements.push_back(Move.getAs<Stmt>());
14516   }
14517 
14518   if (!Invalid) {
14519     // Add a "return *this;"
14520     ExprResult ThisObj =
14521         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14522 
14523     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14524     if (Return.isInvalid())
14525       Invalid = true;
14526     else
14527       Statements.push_back(Return.getAs<Stmt>());
14528   }
14529 
14530   if (Invalid) {
14531     MoveAssignOperator->setInvalidDecl();
14532     return;
14533   }
14534 
14535   StmtResult Body;
14536   {
14537     CompoundScopeRAII CompoundScope(*this);
14538     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14539                              /*isStmtExpr=*/false);
14540     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14541   }
14542   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14543   MoveAssignOperator->markUsed(Context);
14544 
14545   if (ASTMutationListener *L = getASTMutationListener()) {
14546     L->CompletedImplicitDefinition(MoveAssignOperator);
14547   }
14548 }
14549 
14550 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14551                                                     CXXRecordDecl *ClassDecl) {
14552   // C++ [class.copy]p4:
14553   //   If the class definition does not explicitly declare a copy
14554   //   constructor, one is declared implicitly.
14555   assert(ClassDecl->needsImplicitCopyConstructor());
14556 
14557   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14558   if (DSM.isAlreadyBeingDeclared())
14559     return nullptr;
14560 
14561   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14562   QualType ArgType = ClassType;
14563   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14564   if (Const)
14565     ArgType = ArgType.withConst();
14566 
14567   LangAS AS = getDefaultCXXMethodAddrSpace();
14568   if (AS != LangAS::Default)
14569     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14570 
14571   ArgType = Context.getLValueReferenceType(ArgType);
14572 
14573   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14574                                                      CXXCopyConstructor,
14575                                                      Const);
14576 
14577   DeclarationName Name
14578     = Context.DeclarationNames.getCXXConstructorName(
14579                                            Context.getCanonicalType(ClassType));
14580   SourceLocation ClassLoc = ClassDecl->getLocation();
14581   DeclarationNameInfo NameInfo(Name, ClassLoc);
14582 
14583   //   An implicitly-declared copy constructor is an inline public
14584   //   member of its class.
14585   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14586       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14587       ExplicitSpecifier(),
14588       /*isInline=*/true,
14589       /*isImplicitlyDeclared=*/true,
14590       Constexpr ? CSK_constexpr : CSK_unspecified);
14591   CopyConstructor->setAccess(AS_public);
14592   CopyConstructor->setDefaulted();
14593 
14594   if (getLangOpts().CUDA) {
14595     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14596                                             CopyConstructor,
14597                                             /* ConstRHS */ Const,
14598                                             /* Diagnose */ false);
14599   }
14600 
14601   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14602 
14603   // Add the parameter to the constructor.
14604   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14605                                                ClassLoc, ClassLoc,
14606                                                /*IdentifierInfo=*/nullptr,
14607                                                ArgType, /*TInfo=*/nullptr,
14608                                                SC_None, nullptr);
14609   CopyConstructor->setParams(FromParam);
14610 
14611   CopyConstructor->setTrivial(
14612       ClassDecl->needsOverloadResolutionForCopyConstructor()
14613           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14614           : ClassDecl->hasTrivialCopyConstructor());
14615 
14616   CopyConstructor->setTrivialForCall(
14617       ClassDecl->hasAttr<TrivialABIAttr>() ||
14618       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14619            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14620              TAH_ConsiderTrivialABI)
14621            : ClassDecl->hasTrivialCopyConstructorForCall()));
14622 
14623   // Note that we have declared this constructor.
14624   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14625 
14626   Scope *S = getScopeForContext(ClassDecl);
14627   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14628 
14629   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14630     ClassDecl->setImplicitCopyConstructorIsDeleted();
14631     SetDeclDeleted(CopyConstructor, ClassLoc);
14632   }
14633 
14634   if (S)
14635     PushOnScopeChains(CopyConstructor, S, false);
14636   ClassDecl->addDecl(CopyConstructor);
14637 
14638   return CopyConstructor;
14639 }
14640 
14641 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14642                                          CXXConstructorDecl *CopyConstructor) {
14643   assert((CopyConstructor->isDefaulted() &&
14644           CopyConstructor->isCopyConstructor() &&
14645           !CopyConstructor->doesThisDeclarationHaveABody() &&
14646           !CopyConstructor->isDeleted()) &&
14647          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14648   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14649     return;
14650 
14651   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14652   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14653 
14654   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14655 
14656   // The exception specification is needed because we are defining the
14657   // function.
14658   ResolveExceptionSpec(CurrentLocation,
14659                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14660   MarkVTableUsed(CurrentLocation, ClassDecl);
14661 
14662   // Add a context note for diagnostics produced after this point.
14663   Scope.addContextNote(CurrentLocation);
14664 
14665   // C++11 [class.copy]p7:
14666   //   The [definition of an implicitly declared copy constructor] is
14667   //   deprecated if the class has a user-declared copy assignment operator
14668   //   or a user-declared destructor.
14669   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14670     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14671 
14672   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14673     CopyConstructor->setInvalidDecl();
14674   }  else {
14675     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14676                              ? CopyConstructor->getEndLoc()
14677                              : CopyConstructor->getLocation();
14678     Sema::CompoundScopeRAII CompoundScope(*this);
14679     CopyConstructor->setBody(
14680         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14681     CopyConstructor->markUsed(Context);
14682   }
14683 
14684   if (ASTMutationListener *L = getASTMutationListener()) {
14685     L->CompletedImplicitDefinition(CopyConstructor);
14686   }
14687 }
14688 
14689 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14690                                                     CXXRecordDecl *ClassDecl) {
14691   assert(ClassDecl->needsImplicitMoveConstructor());
14692 
14693   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14694   if (DSM.isAlreadyBeingDeclared())
14695     return nullptr;
14696 
14697   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14698 
14699   QualType ArgType = ClassType;
14700   LangAS AS = getDefaultCXXMethodAddrSpace();
14701   if (AS != LangAS::Default)
14702     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14703   ArgType = Context.getRValueReferenceType(ArgType);
14704 
14705   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14706                                                      CXXMoveConstructor,
14707                                                      false);
14708 
14709   DeclarationName Name
14710     = Context.DeclarationNames.getCXXConstructorName(
14711                                            Context.getCanonicalType(ClassType));
14712   SourceLocation ClassLoc = ClassDecl->getLocation();
14713   DeclarationNameInfo NameInfo(Name, ClassLoc);
14714 
14715   // C++11 [class.copy]p11:
14716   //   An implicitly-declared copy/move constructor is an inline public
14717   //   member of its class.
14718   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14719       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14720       ExplicitSpecifier(),
14721       /*isInline=*/true,
14722       /*isImplicitlyDeclared=*/true,
14723       Constexpr ? CSK_constexpr : CSK_unspecified);
14724   MoveConstructor->setAccess(AS_public);
14725   MoveConstructor->setDefaulted();
14726 
14727   if (getLangOpts().CUDA) {
14728     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14729                                             MoveConstructor,
14730                                             /* ConstRHS */ false,
14731                                             /* Diagnose */ false);
14732   }
14733 
14734   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14735 
14736   // Add the parameter to the constructor.
14737   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14738                                                ClassLoc, ClassLoc,
14739                                                /*IdentifierInfo=*/nullptr,
14740                                                ArgType, /*TInfo=*/nullptr,
14741                                                SC_None, nullptr);
14742   MoveConstructor->setParams(FromParam);
14743 
14744   MoveConstructor->setTrivial(
14745       ClassDecl->needsOverloadResolutionForMoveConstructor()
14746           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14747           : ClassDecl->hasTrivialMoveConstructor());
14748 
14749   MoveConstructor->setTrivialForCall(
14750       ClassDecl->hasAttr<TrivialABIAttr>() ||
14751       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14752            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14753                                     TAH_ConsiderTrivialABI)
14754            : ClassDecl->hasTrivialMoveConstructorForCall()));
14755 
14756   // Note that we have declared this constructor.
14757   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14758 
14759   Scope *S = getScopeForContext(ClassDecl);
14760   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14761 
14762   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14763     ClassDecl->setImplicitMoveConstructorIsDeleted();
14764     SetDeclDeleted(MoveConstructor, ClassLoc);
14765   }
14766 
14767   if (S)
14768     PushOnScopeChains(MoveConstructor, S, false);
14769   ClassDecl->addDecl(MoveConstructor);
14770 
14771   return MoveConstructor;
14772 }
14773 
14774 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14775                                          CXXConstructorDecl *MoveConstructor) {
14776   assert((MoveConstructor->isDefaulted() &&
14777           MoveConstructor->isMoveConstructor() &&
14778           !MoveConstructor->doesThisDeclarationHaveABody() &&
14779           !MoveConstructor->isDeleted()) &&
14780          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14781   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14782     return;
14783 
14784   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14785   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14786 
14787   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14788 
14789   // The exception specification is needed because we are defining the
14790   // function.
14791   ResolveExceptionSpec(CurrentLocation,
14792                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14793   MarkVTableUsed(CurrentLocation, ClassDecl);
14794 
14795   // Add a context note for diagnostics produced after this point.
14796   Scope.addContextNote(CurrentLocation);
14797 
14798   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14799     MoveConstructor->setInvalidDecl();
14800   } else {
14801     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14802                              ? MoveConstructor->getEndLoc()
14803                              : MoveConstructor->getLocation();
14804     Sema::CompoundScopeRAII CompoundScope(*this);
14805     MoveConstructor->setBody(ActOnCompoundStmt(
14806         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14807     MoveConstructor->markUsed(Context);
14808   }
14809 
14810   if (ASTMutationListener *L = getASTMutationListener()) {
14811     L->CompletedImplicitDefinition(MoveConstructor);
14812   }
14813 }
14814 
14815 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14816   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14817 }
14818 
14819 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14820                             SourceLocation CurrentLocation,
14821                             CXXConversionDecl *Conv) {
14822   SynthesizedFunctionScope Scope(*this, Conv);
14823   assert(!Conv->getReturnType()->isUndeducedType());
14824 
14825   QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType();
14826   CallingConv CC =
14827       ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv();
14828 
14829   CXXRecordDecl *Lambda = Conv->getParent();
14830   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14831   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
14832 
14833   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14834     CallOp = InstantiateFunctionDeclaration(
14835         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14836     if (!CallOp)
14837       return;
14838 
14839     Invoker = InstantiateFunctionDeclaration(
14840         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14841     if (!Invoker)
14842       return;
14843   }
14844 
14845   if (CallOp->isInvalidDecl())
14846     return;
14847 
14848   // Mark the call operator referenced (and add to pending instantiations
14849   // if necessary).
14850   // For both the conversion and static-invoker template specializations
14851   // we construct their body's in this function, so no need to add them
14852   // to the PendingInstantiations.
14853   MarkFunctionReferenced(CurrentLocation, CallOp);
14854 
14855   // Fill in the __invoke function with a dummy implementation. IR generation
14856   // will fill in the actual details. Update its type in case it contained
14857   // an 'auto'.
14858   Invoker->markUsed(Context);
14859   Invoker->setReferenced();
14860   Invoker->setType(Conv->getReturnType()->getPointeeType());
14861   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14862 
14863   // Construct the body of the conversion function { return __invoke; }.
14864   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14865                                        VK_LValue, Conv->getLocation());
14866   assert(FunctionRef && "Can't refer to __invoke function?");
14867   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14868   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14869                                      Conv->getLocation()));
14870   Conv->markUsed(Context);
14871   Conv->setReferenced();
14872 
14873   if (ASTMutationListener *L = getASTMutationListener()) {
14874     L->CompletedImplicitDefinition(Conv);
14875     L->CompletedImplicitDefinition(Invoker);
14876   }
14877 }
14878 
14879 
14880 
14881 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14882        SourceLocation CurrentLocation,
14883        CXXConversionDecl *Conv)
14884 {
14885   assert(!Conv->getParent()->isGenericLambda());
14886 
14887   SynthesizedFunctionScope Scope(*this, Conv);
14888 
14889   // Copy-initialize the lambda object as needed to capture it.
14890   Expr *This = ActOnCXXThis(CurrentLocation).get();
14891   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14892 
14893   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14894                                                         Conv->getLocation(),
14895                                                         Conv, DerefThis);
14896 
14897   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14898   // behavior.  Note that only the general conversion function does this
14899   // (since it's unusable otherwise); in the case where we inline the
14900   // block literal, it has block literal lifetime semantics.
14901   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14902     BuildBlock = ImplicitCastExpr::Create(
14903         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14904         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14905 
14906   if (BuildBlock.isInvalid()) {
14907     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14908     Conv->setInvalidDecl();
14909     return;
14910   }
14911 
14912   // Create the return statement that returns the block from the conversion
14913   // function.
14914   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14915   if (Return.isInvalid()) {
14916     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14917     Conv->setInvalidDecl();
14918     return;
14919   }
14920 
14921   // Set the body of the conversion function.
14922   Stmt *ReturnS = Return.get();
14923   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14924                                      Conv->getLocation()));
14925   Conv->markUsed(Context);
14926 
14927   // We're done; notify the mutation listener, if any.
14928   if (ASTMutationListener *L = getASTMutationListener()) {
14929     L->CompletedImplicitDefinition(Conv);
14930   }
14931 }
14932 
14933 /// Determine whether the given list arguments contains exactly one
14934 /// "real" (non-default) argument.
14935 static bool hasOneRealArgument(MultiExprArg Args) {
14936   switch (Args.size()) {
14937   case 0:
14938     return false;
14939 
14940   default:
14941     if (!Args[1]->isDefaultArgument())
14942       return false;
14943 
14944     LLVM_FALLTHROUGH;
14945   case 1:
14946     return !Args[0]->isDefaultArgument();
14947   }
14948 
14949   return false;
14950 }
14951 
14952 ExprResult
14953 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14954                             NamedDecl *FoundDecl,
14955                             CXXConstructorDecl *Constructor,
14956                             MultiExprArg ExprArgs,
14957                             bool HadMultipleCandidates,
14958                             bool IsListInitialization,
14959                             bool IsStdInitListInitialization,
14960                             bool RequiresZeroInit,
14961                             unsigned ConstructKind,
14962                             SourceRange ParenRange) {
14963   bool Elidable = false;
14964 
14965   // C++0x [class.copy]p34:
14966   //   When certain criteria are met, an implementation is allowed to
14967   //   omit the copy/move construction of a class object, even if the
14968   //   copy/move constructor and/or destructor for the object have
14969   //   side effects. [...]
14970   //     - when a temporary class object that has not been bound to a
14971   //       reference (12.2) would be copied/moved to a class object
14972   //       with the same cv-unqualified type, the copy/move operation
14973   //       can be omitted by constructing the temporary object
14974   //       directly into the target of the omitted copy/move
14975   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14976       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14977     Expr *SubExpr = ExprArgs[0];
14978     Elidable = SubExpr->isTemporaryObject(
14979         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14980   }
14981 
14982   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14983                                FoundDecl, Constructor,
14984                                Elidable, ExprArgs, HadMultipleCandidates,
14985                                IsListInitialization,
14986                                IsStdInitListInitialization, RequiresZeroInit,
14987                                ConstructKind, ParenRange);
14988 }
14989 
14990 ExprResult
14991 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14992                             NamedDecl *FoundDecl,
14993                             CXXConstructorDecl *Constructor,
14994                             bool Elidable,
14995                             MultiExprArg ExprArgs,
14996                             bool HadMultipleCandidates,
14997                             bool IsListInitialization,
14998                             bool IsStdInitListInitialization,
14999                             bool RequiresZeroInit,
15000                             unsigned ConstructKind,
15001                             SourceRange ParenRange) {
15002   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15003     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15004     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15005       return ExprError();
15006   }
15007 
15008   return BuildCXXConstructExpr(
15009       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15010       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15011       RequiresZeroInit, ConstructKind, ParenRange);
15012 }
15013 
15014 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15015 /// including handling of its default argument expressions.
15016 ExprResult
15017 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15018                             CXXConstructorDecl *Constructor,
15019                             bool Elidable,
15020                             MultiExprArg ExprArgs,
15021                             bool HadMultipleCandidates,
15022                             bool IsListInitialization,
15023                             bool IsStdInitListInitialization,
15024                             bool RequiresZeroInit,
15025                             unsigned ConstructKind,
15026                             SourceRange ParenRange) {
15027   assert(declaresSameEntity(
15028              Constructor->getParent(),
15029              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15030          "given constructor for wrong type");
15031   MarkFunctionReferenced(ConstructLoc, Constructor);
15032   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15033     return ExprError();
15034   if (getLangOpts().SYCLIsDevice &&
15035       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15036     return ExprError();
15037 
15038   return CheckForImmediateInvocation(
15039       CXXConstructExpr::Create(
15040           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15041           HadMultipleCandidates, IsListInitialization,
15042           IsStdInitListInitialization, RequiresZeroInit,
15043           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15044           ParenRange),
15045       Constructor);
15046 }
15047 
15048 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15049   assert(Field->hasInClassInitializer());
15050 
15051   // If we already have the in-class initializer nothing needs to be done.
15052   if (Field->getInClassInitializer())
15053     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15054 
15055   // If we might have already tried and failed to instantiate, don't try again.
15056   if (Field->isInvalidDecl())
15057     return ExprError();
15058 
15059   // Maybe we haven't instantiated the in-class initializer. Go check the
15060   // pattern FieldDecl to see if it has one.
15061   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15062 
15063   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15064     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15065     DeclContext::lookup_result Lookup =
15066         ClassPattern->lookup(Field->getDeclName());
15067 
15068     // Lookup can return at most two results: the pattern for the field, or the
15069     // injected class name of the parent record. No other member can have the
15070     // same name as the field.
15071     // In modules mode, lookup can return multiple results (coming from
15072     // different modules).
15073     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15074            "more than two lookup results for field name");
15075     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15076     if (!Pattern) {
15077       assert(isa<CXXRecordDecl>(Lookup[0]) &&
15078              "cannot have other non-field member with same name");
15079       for (auto L : Lookup)
15080         if (isa<FieldDecl>(L)) {
15081           Pattern = cast<FieldDecl>(L);
15082           break;
15083         }
15084       assert(Pattern && "We must have set the Pattern!");
15085     }
15086 
15087     if (!Pattern->hasInClassInitializer() ||
15088         InstantiateInClassInitializer(Loc, Field, Pattern,
15089                                       getTemplateInstantiationArgs(Field))) {
15090       // Don't diagnose this again.
15091       Field->setInvalidDecl();
15092       return ExprError();
15093     }
15094     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15095   }
15096 
15097   // DR1351:
15098   //   If the brace-or-equal-initializer of a non-static data member
15099   //   invokes a defaulted default constructor of its class or of an
15100   //   enclosing class in a potentially evaluated subexpression, the
15101   //   program is ill-formed.
15102   //
15103   // This resolution is unworkable: the exception specification of the
15104   // default constructor can be needed in an unevaluated context, in
15105   // particular, in the operand of a noexcept-expression, and we can be
15106   // unable to compute an exception specification for an enclosed class.
15107   //
15108   // Any attempt to resolve the exception specification of a defaulted default
15109   // constructor before the initializer is lexically complete will ultimately
15110   // come here at which point we can diagnose it.
15111   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15112   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15113       << OutermostClass << Field;
15114   Diag(Field->getEndLoc(),
15115        diag::note_default_member_initializer_not_yet_parsed);
15116   // Recover by marking the field invalid, unless we're in a SFINAE context.
15117   if (!isSFINAEContext())
15118     Field->setInvalidDecl();
15119   return ExprError();
15120 }
15121 
15122 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15123   if (VD->isInvalidDecl()) return;
15124   // If initializing the variable failed, don't also diagnose problems with
15125   // the desctructor, they're likely related.
15126   if (VD->getInit() && VD->getInit()->containsErrors())
15127     return;
15128 
15129   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15130   if (ClassDecl->isInvalidDecl()) return;
15131   if (ClassDecl->hasIrrelevantDestructor()) return;
15132   if (ClassDecl->isDependentContext()) return;
15133 
15134   if (VD->isNoDestroy(getASTContext()))
15135     return;
15136 
15137   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15138 
15139   // If this is an array, we'll require the destructor during initialization, so
15140   // we can skip over this. We still want to emit exit-time destructor warnings
15141   // though.
15142   if (!VD->getType()->isArrayType()) {
15143     MarkFunctionReferenced(VD->getLocation(), Destructor);
15144     CheckDestructorAccess(VD->getLocation(), Destructor,
15145                           PDiag(diag::err_access_dtor_var)
15146                               << VD->getDeclName() << VD->getType());
15147     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15148   }
15149 
15150   if (Destructor->isTrivial()) return;
15151 
15152   // If the destructor is constexpr, check whether the variable has constant
15153   // destruction now.
15154   if (Destructor->isConstexpr()) {
15155     bool HasConstantInit = false;
15156     if (VD->getInit() && !VD->getInit()->isValueDependent())
15157       HasConstantInit = VD->evaluateValue();
15158     SmallVector<PartialDiagnosticAt, 8> Notes;
15159     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15160         HasConstantInit) {
15161       Diag(VD->getLocation(),
15162            diag::err_constexpr_var_requires_const_destruction) << VD;
15163       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15164         Diag(Notes[I].first, Notes[I].second);
15165     }
15166   }
15167 
15168   if (!VD->hasGlobalStorage()) return;
15169 
15170   // Emit warning for non-trivial dtor in global scope (a real global,
15171   // class-static, function-static).
15172   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15173 
15174   // TODO: this should be re-enabled for static locals by !CXAAtExit
15175   if (!VD->isStaticLocal())
15176     Diag(VD->getLocation(), diag::warn_global_destructor);
15177 }
15178 
15179 /// Given a constructor and the set of arguments provided for the
15180 /// constructor, convert the arguments and add any required default arguments
15181 /// to form a proper call to this constructor.
15182 ///
15183 /// \returns true if an error occurred, false otherwise.
15184 bool
15185 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15186                               MultiExprArg ArgsPtr,
15187                               SourceLocation Loc,
15188                               SmallVectorImpl<Expr*> &ConvertedArgs,
15189                               bool AllowExplicit,
15190                               bool IsListInitialization) {
15191   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15192   unsigned NumArgs = ArgsPtr.size();
15193   Expr **Args = ArgsPtr.data();
15194 
15195   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15196   unsigned NumParams = Proto->getNumParams();
15197 
15198   // If too few arguments are available, we'll fill in the rest with defaults.
15199   if (NumArgs < NumParams)
15200     ConvertedArgs.reserve(NumParams);
15201   else
15202     ConvertedArgs.reserve(NumArgs);
15203 
15204   VariadicCallType CallType =
15205     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15206   SmallVector<Expr *, 8> AllArgs;
15207   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15208                                         Proto, 0,
15209                                         llvm::makeArrayRef(Args, NumArgs),
15210                                         AllArgs,
15211                                         CallType, AllowExplicit,
15212                                         IsListInitialization);
15213   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15214 
15215   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15216 
15217   CheckConstructorCall(Constructor,
15218                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15219                        Proto, Loc);
15220 
15221   return Invalid;
15222 }
15223 
15224 static inline bool
15225 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15226                                        const FunctionDecl *FnDecl) {
15227   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15228   if (isa<NamespaceDecl>(DC)) {
15229     return SemaRef.Diag(FnDecl->getLocation(),
15230                         diag::err_operator_new_delete_declared_in_namespace)
15231       << FnDecl->getDeclName();
15232   }
15233 
15234   if (isa<TranslationUnitDecl>(DC) &&
15235       FnDecl->getStorageClass() == SC_Static) {
15236     return SemaRef.Diag(FnDecl->getLocation(),
15237                         diag::err_operator_new_delete_declared_static)
15238       << FnDecl->getDeclName();
15239   }
15240 
15241   return false;
15242 }
15243 
15244 static QualType
15245 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15246   QualType QTy = PtrTy->getPointeeType();
15247   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15248   return SemaRef.Context.getPointerType(QTy);
15249 }
15250 
15251 static inline bool
15252 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15253                             CanQualType ExpectedResultType,
15254                             CanQualType ExpectedFirstParamType,
15255                             unsigned DependentParamTypeDiag,
15256                             unsigned InvalidParamTypeDiag) {
15257   QualType ResultType =
15258       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15259 
15260   // The operator is valid on any address space for OpenCL.
15261   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15262     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15263       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15264     }
15265   }
15266 
15267   // Check that the result type is what we expect.
15268   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15269     // Reject even if the type is dependent; an operator delete function is
15270     // required to have a non-dependent result type.
15271     return SemaRef.Diag(
15272                FnDecl->getLocation(),
15273                ResultType->isDependentType()
15274                    ? diag::err_operator_new_delete_dependent_result_type
15275                    : diag::err_operator_new_delete_invalid_result_type)
15276            << FnDecl->getDeclName() << ExpectedResultType;
15277   }
15278 
15279   // A function template must have at least 2 parameters.
15280   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15281     return SemaRef.Diag(FnDecl->getLocation(),
15282                       diag::err_operator_new_delete_template_too_few_parameters)
15283         << FnDecl->getDeclName();
15284 
15285   // The function decl must have at least 1 parameter.
15286   if (FnDecl->getNumParams() == 0)
15287     return SemaRef.Diag(FnDecl->getLocation(),
15288                         diag::err_operator_new_delete_too_few_parameters)
15289       << FnDecl->getDeclName();
15290 
15291   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15292   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15293     // The operator is valid on any address space for OpenCL.
15294     if (auto *PtrTy =
15295             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15296       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15297     }
15298   }
15299 
15300   // Check that the first parameter type is what we expect.
15301   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15302       ExpectedFirstParamType) {
15303     // The first parameter type is not allowed to be dependent. As a tentative
15304     // DR resolution, we allow a dependent parameter type if it is the right
15305     // type anyway, to allow destroying operator delete in class templates.
15306     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15307                                                    ? DependentParamTypeDiag
15308                                                    : InvalidParamTypeDiag)
15309            << FnDecl->getDeclName() << ExpectedFirstParamType;
15310   }
15311 
15312   return false;
15313 }
15314 
15315 static bool
15316 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15317   // C++ [basic.stc.dynamic.allocation]p1:
15318   //   A program is ill-formed if an allocation function is declared in a
15319   //   namespace scope other than global scope or declared static in global
15320   //   scope.
15321   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15322     return true;
15323 
15324   CanQualType SizeTy =
15325     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15326 
15327   // C++ [basic.stc.dynamic.allocation]p1:
15328   //  The return type shall be void*. The first parameter shall have type
15329   //  std::size_t.
15330   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15331                                   SizeTy,
15332                                   diag::err_operator_new_dependent_param_type,
15333                                   diag::err_operator_new_param_type))
15334     return true;
15335 
15336   // C++ [basic.stc.dynamic.allocation]p1:
15337   //  The first parameter shall not have an associated default argument.
15338   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15339     return SemaRef.Diag(FnDecl->getLocation(),
15340                         diag::err_operator_new_default_arg)
15341       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15342 
15343   return false;
15344 }
15345 
15346 static bool
15347 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15348   // C++ [basic.stc.dynamic.deallocation]p1:
15349   //   A program is ill-formed if deallocation functions are declared in a
15350   //   namespace scope other than global scope or declared static in global
15351   //   scope.
15352   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15353     return true;
15354 
15355   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15356 
15357   // C++ P0722:
15358   //   Within a class C, the first parameter of a destroying operator delete
15359   //   shall be of type C *. The first parameter of any other deallocation
15360   //   function shall be of type void *.
15361   CanQualType ExpectedFirstParamType =
15362       MD && MD->isDestroyingOperatorDelete()
15363           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15364                 SemaRef.Context.getRecordType(MD->getParent())))
15365           : SemaRef.Context.VoidPtrTy;
15366 
15367   // C++ [basic.stc.dynamic.deallocation]p2:
15368   //   Each deallocation function shall return void
15369   if (CheckOperatorNewDeleteTypes(
15370           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15371           diag::err_operator_delete_dependent_param_type,
15372           diag::err_operator_delete_param_type))
15373     return true;
15374 
15375   // C++ P0722:
15376   //   A destroying operator delete shall be a usual deallocation function.
15377   if (MD && !MD->getParent()->isDependentContext() &&
15378       MD->isDestroyingOperatorDelete() &&
15379       !SemaRef.isUsualDeallocationFunction(MD)) {
15380     SemaRef.Diag(MD->getLocation(),
15381                  diag::err_destroying_operator_delete_not_usual);
15382     return true;
15383   }
15384 
15385   return false;
15386 }
15387 
15388 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15389 /// of this overloaded operator is well-formed. If so, returns false;
15390 /// otherwise, emits appropriate diagnostics and returns true.
15391 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15392   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15393          "Expected an overloaded operator declaration");
15394 
15395   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15396 
15397   // C++ [over.oper]p5:
15398   //   The allocation and deallocation functions, operator new,
15399   //   operator new[], operator delete and operator delete[], are
15400   //   described completely in 3.7.3. The attributes and restrictions
15401   //   found in the rest of this subclause do not apply to them unless
15402   //   explicitly stated in 3.7.3.
15403   if (Op == OO_Delete || Op == OO_Array_Delete)
15404     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15405 
15406   if (Op == OO_New || Op == OO_Array_New)
15407     return CheckOperatorNewDeclaration(*this, FnDecl);
15408 
15409   // C++ [over.oper]p6:
15410   //   An operator function shall either be a non-static member
15411   //   function or be a non-member function and have at least one
15412   //   parameter whose type is a class, a reference to a class, an
15413   //   enumeration, or a reference to an enumeration.
15414   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15415     if (MethodDecl->isStatic())
15416       return Diag(FnDecl->getLocation(),
15417                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15418   } else {
15419     bool ClassOrEnumParam = false;
15420     for (auto Param : FnDecl->parameters()) {
15421       QualType ParamType = Param->getType().getNonReferenceType();
15422       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15423           ParamType->isEnumeralType()) {
15424         ClassOrEnumParam = true;
15425         break;
15426       }
15427     }
15428 
15429     if (!ClassOrEnumParam)
15430       return Diag(FnDecl->getLocation(),
15431                   diag::err_operator_overload_needs_class_or_enum)
15432         << FnDecl->getDeclName();
15433   }
15434 
15435   // C++ [over.oper]p8:
15436   //   An operator function cannot have default arguments (8.3.6),
15437   //   except where explicitly stated below.
15438   //
15439   // Only the function-call operator allows default arguments
15440   // (C++ [over.call]p1).
15441   if (Op != OO_Call) {
15442     for (auto Param : FnDecl->parameters()) {
15443       if (Param->hasDefaultArg())
15444         return Diag(Param->getLocation(),
15445                     diag::err_operator_overload_default_arg)
15446           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15447     }
15448   }
15449 
15450   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15451     { false, false, false }
15452 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15453     , { Unary, Binary, MemberOnly }
15454 #include "clang/Basic/OperatorKinds.def"
15455   };
15456 
15457   bool CanBeUnaryOperator = OperatorUses[Op][0];
15458   bool CanBeBinaryOperator = OperatorUses[Op][1];
15459   bool MustBeMemberOperator = OperatorUses[Op][2];
15460 
15461   // C++ [over.oper]p8:
15462   //   [...] Operator functions cannot have more or fewer parameters
15463   //   than the number required for the corresponding operator, as
15464   //   described in the rest of this subclause.
15465   unsigned NumParams = FnDecl->getNumParams()
15466                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15467   if (Op != OO_Call &&
15468       ((NumParams == 1 && !CanBeUnaryOperator) ||
15469        (NumParams == 2 && !CanBeBinaryOperator) ||
15470        (NumParams < 1) || (NumParams > 2))) {
15471     // We have the wrong number of parameters.
15472     unsigned ErrorKind;
15473     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15474       ErrorKind = 2;  // 2 -> unary or binary.
15475     } else if (CanBeUnaryOperator) {
15476       ErrorKind = 0;  // 0 -> unary
15477     } else {
15478       assert(CanBeBinaryOperator &&
15479              "All non-call overloaded operators are unary or binary!");
15480       ErrorKind = 1;  // 1 -> binary
15481     }
15482 
15483     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15484       << FnDecl->getDeclName() << NumParams << ErrorKind;
15485   }
15486 
15487   // Overloaded operators other than operator() cannot be variadic.
15488   if (Op != OO_Call &&
15489       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15490     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15491       << FnDecl->getDeclName();
15492   }
15493 
15494   // Some operators must be non-static member functions.
15495   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15496     return Diag(FnDecl->getLocation(),
15497                 diag::err_operator_overload_must_be_member)
15498       << FnDecl->getDeclName();
15499   }
15500 
15501   // C++ [over.inc]p1:
15502   //   The user-defined function called operator++ implements the
15503   //   prefix and postfix ++ operator. If this function is a member
15504   //   function with no parameters, or a non-member function with one
15505   //   parameter of class or enumeration type, it defines the prefix
15506   //   increment operator ++ for objects of that type. If the function
15507   //   is a member function with one parameter (which shall be of type
15508   //   int) or a non-member function with two parameters (the second
15509   //   of which shall be of type int), it defines the postfix
15510   //   increment operator ++ for objects of that type.
15511   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15512     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15513     QualType ParamType = LastParam->getType();
15514 
15515     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15516         !ParamType->isDependentType())
15517       return Diag(LastParam->getLocation(),
15518                   diag::err_operator_overload_post_incdec_must_be_int)
15519         << LastParam->getType() << (Op == OO_MinusMinus);
15520   }
15521 
15522   return false;
15523 }
15524 
15525 static bool
15526 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15527                                           FunctionTemplateDecl *TpDecl) {
15528   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15529 
15530   // Must have one or two template parameters.
15531   if (TemplateParams->size() == 1) {
15532     NonTypeTemplateParmDecl *PmDecl =
15533         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15534 
15535     // The template parameter must be a char parameter pack.
15536     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15537         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15538       return false;
15539 
15540     // C++20 [over.literal]p5:
15541     //   A string literal operator template is a literal operator template
15542     //   whose template-parameter-list comprises a single non-type
15543     //   template-parameter of class type.
15544     //
15545     // As a DR resolution, we also allow placeholders for deduced class
15546     // template specializations.
15547     if (SemaRef.getLangOpts().CPlusPlus20 &&
15548         !PmDecl->isTemplateParameterPack() &&
15549         (PmDecl->getType()->isRecordType() ||
15550          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15551       return false;
15552   } else if (TemplateParams->size() == 2) {
15553     TemplateTypeParmDecl *PmType =
15554         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15555     NonTypeTemplateParmDecl *PmArgs =
15556         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15557 
15558     // The second template parameter must be a parameter pack with the
15559     // first template parameter as its type.
15560     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15561         PmArgs->isTemplateParameterPack()) {
15562       const TemplateTypeParmType *TArgs =
15563           PmArgs->getType()->getAs<TemplateTypeParmType>();
15564       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15565           TArgs->getIndex() == PmType->getIndex()) {
15566         if (!SemaRef.inTemplateInstantiation())
15567           SemaRef.Diag(TpDecl->getLocation(),
15568                        diag::ext_string_literal_operator_template);
15569         return false;
15570       }
15571     }
15572   }
15573 
15574   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15575                diag::err_literal_operator_template)
15576       << TpDecl->getTemplateParameters()->getSourceRange();
15577   return true;
15578 }
15579 
15580 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15581 /// of this literal operator function is well-formed. If so, returns
15582 /// false; otherwise, emits appropriate diagnostics and returns true.
15583 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15584   if (isa<CXXMethodDecl>(FnDecl)) {
15585     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15586       << FnDecl->getDeclName();
15587     return true;
15588   }
15589 
15590   if (FnDecl->isExternC()) {
15591     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15592     if (const LinkageSpecDecl *LSD =
15593             FnDecl->getDeclContext()->getExternCContext())
15594       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15595     return true;
15596   }
15597 
15598   // This might be the definition of a literal operator template.
15599   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15600 
15601   // This might be a specialization of a literal operator template.
15602   if (!TpDecl)
15603     TpDecl = FnDecl->getPrimaryTemplate();
15604 
15605   // template <char...> type operator "" name() and
15606   // template <class T, T...> type operator "" name() are the only valid
15607   // template signatures, and the only valid signatures with no parameters.
15608   //
15609   // C++20 also allows template <SomeClass T> type operator "" name().
15610   if (TpDecl) {
15611     if (FnDecl->param_size() != 0) {
15612       Diag(FnDecl->getLocation(),
15613            diag::err_literal_operator_template_with_params);
15614       return true;
15615     }
15616 
15617     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15618       return true;
15619 
15620   } else if (FnDecl->param_size() == 1) {
15621     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15622 
15623     QualType ParamType = Param->getType().getUnqualifiedType();
15624 
15625     // Only unsigned long long int, long double, any character type, and const
15626     // char * are allowed as the only parameters.
15627     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15628         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15629         Context.hasSameType(ParamType, Context.CharTy) ||
15630         Context.hasSameType(ParamType, Context.WideCharTy) ||
15631         Context.hasSameType(ParamType, Context.Char8Ty) ||
15632         Context.hasSameType(ParamType, Context.Char16Ty) ||
15633         Context.hasSameType(ParamType, Context.Char32Ty)) {
15634     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15635       QualType InnerType = Ptr->getPointeeType();
15636 
15637       // Pointer parameter must be a const char *.
15638       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15639                                 Context.CharTy) &&
15640             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15641         Diag(Param->getSourceRange().getBegin(),
15642              diag::err_literal_operator_param)
15643             << ParamType << "'const char *'" << Param->getSourceRange();
15644         return true;
15645       }
15646 
15647     } else if (ParamType->isRealFloatingType()) {
15648       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15649           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15650       return true;
15651 
15652     } else if (ParamType->isIntegerType()) {
15653       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15654           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15655       return true;
15656 
15657     } else {
15658       Diag(Param->getSourceRange().getBegin(),
15659            diag::err_literal_operator_invalid_param)
15660           << ParamType << Param->getSourceRange();
15661       return true;
15662     }
15663 
15664   } else if (FnDecl->param_size() == 2) {
15665     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15666 
15667     // First, verify that the first parameter is correct.
15668 
15669     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15670 
15671     // Two parameter function must have a pointer to const as a
15672     // first parameter; let's strip those qualifiers.
15673     const PointerType *PT = FirstParamType->getAs<PointerType>();
15674 
15675     if (!PT) {
15676       Diag((*Param)->getSourceRange().getBegin(),
15677            diag::err_literal_operator_param)
15678           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15679       return true;
15680     }
15681 
15682     QualType PointeeType = PT->getPointeeType();
15683     // First parameter must be const
15684     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15685       Diag((*Param)->getSourceRange().getBegin(),
15686            diag::err_literal_operator_param)
15687           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15688       return true;
15689     }
15690 
15691     QualType InnerType = PointeeType.getUnqualifiedType();
15692     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15693     // const char32_t* are allowed as the first parameter to a two-parameter
15694     // function
15695     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15696           Context.hasSameType(InnerType, Context.WideCharTy) ||
15697           Context.hasSameType(InnerType, Context.Char8Ty) ||
15698           Context.hasSameType(InnerType, Context.Char16Ty) ||
15699           Context.hasSameType(InnerType, Context.Char32Ty))) {
15700       Diag((*Param)->getSourceRange().getBegin(),
15701            diag::err_literal_operator_param)
15702           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15703       return true;
15704     }
15705 
15706     // Move on to the second and final parameter.
15707     ++Param;
15708 
15709     // The second parameter must be a std::size_t.
15710     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15711     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15712       Diag((*Param)->getSourceRange().getBegin(),
15713            diag::err_literal_operator_param)
15714           << SecondParamType << Context.getSizeType()
15715           << (*Param)->getSourceRange();
15716       return true;
15717     }
15718   } else {
15719     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15720     return true;
15721   }
15722 
15723   // Parameters are good.
15724 
15725   // A parameter-declaration-clause containing a default argument is not
15726   // equivalent to any of the permitted forms.
15727   for (auto Param : FnDecl->parameters()) {
15728     if (Param->hasDefaultArg()) {
15729       Diag(Param->getDefaultArgRange().getBegin(),
15730            diag::err_literal_operator_default_argument)
15731         << Param->getDefaultArgRange();
15732       break;
15733     }
15734   }
15735 
15736   StringRef LiteralName
15737     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15738   if (LiteralName[0] != '_' &&
15739       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15740     // C++11 [usrlit.suffix]p1:
15741     //   Literal suffix identifiers that do not start with an underscore
15742     //   are reserved for future standardization.
15743     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15744       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15745   }
15746 
15747   return false;
15748 }
15749 
15750 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15751 /// linkage specification, including the language and (if present)
15752 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15753 /// language string literal. LBraceLoc, if valid, provides the location of
15754 /// the '{' brace. Otherwise, this linkage specification does not
15755 /// have any braces.
15756 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15757                                            Expr *LangStr,
15758                                            SourceLocation LBraceLoc) {
15759   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15760   if (!Lit->isAscii()) {
15761     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15762       << LangStr->getSourceRange();
15763     return nullptr;
15764   }
15765 
15766   StringRef Lang = Lit->getString();
15767   LinkageSpecDecl::LanguageIDs Language;
15768   if (Lang == "C")
15769     Language = LinkageSpecDecl::lang_c;
15770   else if (Lang == "C++")
15771     Language = LinkageSpecDecl::lang_cxx;
15772   else {
15773     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15774       << LangStr->getSourceRange();
15775     return nullptr;
15776   }
15777 
15778   // FIXME: Add all the various semantics of linkage specifications
15779 
15780   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15781                                                LangStr->getExprLoc(), Language,
15782                                                LBraceLoc.isValid());
15783   CurContext->addDecl(D);
15784   PushDeclContext(S, D);
15785   return D;
15786 }
15787 
15788 /// ActOnFinishLinkageSpecification - Complete the definition of
15789 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15790 /// valid, it's the position of the closing '}' brace in a linkage
15791 /// specification that uses braces.
15792 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15793                                             Decl *LinkageSpec,
15794                                             SourceLocation RBraceLoc) {
15795   if (RBraceLoc.isValid()) {
15796     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15797     LSDecl->setRBraceLoc(RBraceLoc);
15798   }
15799   PopDeclContext();
15800   return LinkageSpec;
15801 }
15802 
15803 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15804                                   const ParsedAttributesView &AttrList,
15805                                   SourceLocation SemiLoc) {
15806   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15807   // Attribute declarations appertain to empty declaration so we handle
15808   // them here.
15809   ProcessDeclAttributeList(S, ED, AttrList);
15810 
15811   CurContext->addDecl(ED);
15812   return ED;
15813 }
15814 
15815 /// Perform semantic analysis for the variable declaration that
15816 /// occurs within a C++ catch clause, returning the newly-created
15817 /// variable.
15818 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15819                                          TypeSourceInfo *TInfo,
15820                                          SourceLocation StartLoc,
15821                                          SourceLocation Loc,
15822                                          IdentifierInfo *Name) {
15823   bool Invalid = false;
15824   QualType ExDeclType = TInfo->getType();
15825 
15826   // Arrays and functions decay.
15827   if (ExDeclType->isArrayType())
15828     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15829   else if (ExDeclType->isFunctionType())
15830     ExDeclType = Context.getPointerType(ExDeclType);
15831 
15832   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15833   // The exception-declaration shall not denote a pointer or reference to an
15834   // incomplete type, other than [cv] void*.
15835   // N2844 forbids rvalue references.
15836   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15837     Diag(Loc, diag::err_catch_rvalue_ref);
15838     Invalid = true;
15839   }
15840 
15841   if (ExDeclType->isVariablyModifiedType()) {
15842     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15843     Invalid = true;
15844   }
15845 
15846   QualType BaseType = ExDeclType;
15847   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15848   unsigned DK = diag::err_catch_incomplete;
15849   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15850     BaseType = Ptr->getPointeeType();
15851     Mode = 1;
15852     DK = diag::err_catch_incomplete_ptr;
15853   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15854     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15855     BaseType = Ref->getPointeeType();
15856     Mode = 2;
15857     DK = diag::err_catch_incomplete_ref;
15858   }
15859   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15860       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15861     Invalid = true;
15862 
15863   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15864     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15865     Invalid = true;
15866   }
15867 
15868   if (!Invalid && !ExDeclType->isDependentType() &&
15869       RequireNonAbstractType(Loc, ExDeclType,
15870                              diag::err_abstract_type_in_decl,
15871                              AbstractVariableType))
15872     Invalid = true;
15873 
15874   // Only the non-fragile NeXT runtime currently supports C++ catches
15875   // of ObjC types, and no runtime supports catching ObjC types by value.
15876   if (!Invalid && getLangOpts().ObjC) {
15877     QualType T = ExDeclType;
15878     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15879       T = RT->getPointeeType();
15880 
15881     if (T->isObjCObjectType()) {
15882       Diag(Loc, diag::err_objc_object_catch);
15883       Invalid = true;
15884     } else if (T->isObjCObjectPointerType()) {
15885       // FIXME: should this be a test for macosx-fragile specifically?
15886       if (getLangOpts().ObjCRuntime.isFragile())
15887         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15888     }
15889   }
15890 
15891   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15892                                     ExDeclType, TInfo, SC_None);
15893   ExDecl->setExceptionVariable(true);
15894 
15895   // In ARC, infer 'retaining' for variables of retainable type.
15896   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15897     Invalid = true;
15898 
15899   if (!Invalid && !ExDeclType->isDependentType()) {
15900     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15901       // Insulate this from anything else we might currently be parsing.
15902       EnterExpressionEvaluationContext scope(
15903           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15904 
15905       // C++ [except.handle]p16:
15906       //   The object declared in an exception-declaration or, if the
15907       //   exception-declaration does not specify a name, a temporary (12.2) is
15908       //   copy-initialized (8.5) from the exception object. [...]
15909       //   The object is destroyed when the handler exits, after the destruction
15910       //   of any automatic objects initialized within the handler.
15911       //
15912       // We just pretend to initialize the object with itself, then make sure
15913       // it can be destroyed later.
15914       QualType initType = Context.getExceptionObjectType(ExDeclType);
15915 
15916       InitializedEntity entity =
15917         InitializedEntity::InitializeVariable(ExDecl);
15918       InitializationKind initKind =
15919         InitializationKind::CreateCopy(Loc, SourceLocation());
15920 
15921       Expr *opaqueValue =
15922         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15923       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15924       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15925       if (result.isInvalid())
15926         Invalid = true;
15927       else {
15928         // If the constructor used was non-trivial, set this as the
15929         // "initializer".
15930         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15931         if (!construct->getConstructor()->isTrivial()) {
15932           Expr *init = MaybeCreateExprWithCleanups(construct);
15933           ExDecl->setInit(init);
15934         }
15935 
15936         // And make sure it's destructable.
15937         FinalizeVarWithDestructor(ExDecl, recordType);
15938       }
15939     }
15940   }
15941 
15942   if (Invalid)
15943     ExDecl->setInvalidDecl();
15944 
15945   return ExDecl;
15946 }
15947 
15948 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15949 /// handler.
15950 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15951   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15952   bool Invalid = D.isInvalidType();
15953 
15954   // Check for unexpanded parameter packs.
15955   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15956                                       UPPC_ExceptionType)) {
15957     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15958                                              D.getIdentifierLoc());
15959     Invalid = true;
15960   }
15961 
15962   IdentifierInfo *II = D.getIdentifier();
15963   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15964                                              LookupOrdinaryName,
15965                                              ForVisibleRedeclaration)) {
15966     // The scope should be freshly made just for us. There is just no way
15967     // it contains any previous declaration, except for function parameters in
15968     // a function-try-block's catch statement.
15969     assert(!S->isDeclScope(PrevDecl));
15970     if (isDeclInScope(PrevDecl, CurContext, S)) {
15971       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15972         << D.getIdentifier();
15973       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15974       Invalid = true;
15975     } else if (PrevDecl->isTemplateParameter())
15976       // Maybe we will complain about the shadowed template parameter.
15977       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15978   }
15979 
15980   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15981     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15982       << D.getCXXScopeSpec().getRange();
15983     Invalid = true;
15984   }
15985 
15986   VarDecl *ExDecl = BuildExceptionDeclaration(
15987       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15988   if (Invalid)
15989     ExDecl->setInvalidDecl();
15990 
15991   // Add the exception declaration into this scope.
15992   if (II)
15993     PushOnScopeChains(ExDecl, S);
15994   else
15995     CurContext->addDecl(ExDecl);
15996 
15997   ProcessDeclAttributes(S, ExDecl, D);
15998   return ExDecl;
15999 }
16000 
16001 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16002                                          Expr *AssertExpr,
16003                                          Expr *AssertMessageExpr,
16004                                          SourceLocation RParenLoc) {
16005   StringLiteral *AssertMessage =
16006       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16007 
16008   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16009     return nullptr;
16010 
16011   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16012                                       AssertMessage, RParenLoc, false);
16013 }
16014 
16015 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16016                                          Expr *AssertExpr,
16017                                          StringLiteral *AssertMessage,
16018                                          SourceLocation RParenLoc,
16019                                          bool Failed) {
16020   assert(AssertExpr != nullptr && "Expected non-null condition");
16021   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16022       !Failed) {
16023     // In a static_assert-declaration, the constant-expression shall be a
16024     // constant expression that can be contextually converted to bool.
16025     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16026     if (Converted.isInvalid())
16027       Failed = true;
16028 
16029     ExprResult FullAssertExpr =
16030         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16031                             /*DiscardedValue*/ false,
16032                             /*IsConstexpr*/ true);
16033     if (FullAssertExpr.isInvalid())
16034       Failed = true;
16035     else
16036       AssertExpr = FullAssertExpr.get();
16037 
16038     llvm::APSInt Cond;
16039     if (!Failed && VerifyIntegerConstantExpression(
16040                        AssertExpr, &Cond,
16041                        diag::err_static_assert_expression_is_not_constant)
16042                        .isInvalid())
16043       Failed = true;
16044 
16045     if (!Failed && !Cond) {
16046       SmallString<256> MsgBuffer;
16047       llvm::raw_svector_ostream Msg(MsgBuffer);
16048       if (AssertMessage)
16049         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16050 
16051       Expr *InnerCond = nullptr;
16052       std::string InnerCondDescription;
16053       std::tie(InnerCond, InnerCondDescription) =
16054         findFailedBooleanCondition(Converted.get());
16055       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16056         // Drill down into concept specialization expressions to see why they
16057         // weren't satisfied.
16058         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16059           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16060         ConstraintSatisfaction Satisfaction;
16061         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16062           DiagnoseUnsatisfiedConstraint(Satisfaction);
16063       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16064                            && !isa<IntegerLiteral>(InnerCond)) {
16065         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16066           << InnerCondDescription << !AssertMessage
16067           << Msg.str() << InnerCond->getSourceRange();
16068       } else {
16069         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16070           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16071       }
16072       Failed = true;
16073     }
16074   } else {
16075     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16076                                                     /*DiscardedValue*/false,
16077                                                     /*IsConstexpr*/true);
16078     if (FullAssertExpr.isInvalid())
16079       Failed = true;
16080     else
16081       AssertExpr = FullAssertExpr.get();
16082   }
16083 
16084   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16085                                         AssertExpr, AssertMessage, RParenLoc,
16086                                         Failed);
16087 
16088   CurContext->addDecl(Decl);
16089   return Decl;
16090 }
16091 
16092 /// Perform semantic analysis of the given friend type declaration.
16093 ///
16094 /// \returns A friend declaration that.
16095 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16096                                       SourceLocation FriendLoc,
16097                                       TypeSourceInfo *TSInfo) {
16098   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16099 
16100   QualType T = TSInfo->getType();
16101   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16102 
16103   // C++03 [class.friend]p2:
16104   //   An elaborated-type-specifier shall be used in a friend declaration
16105   //   for a class.*
16106   //
16107   //   * The class-key of the elaborated-type-specifier is required.
16108   if (!CodeSynthesisContexts.empty()) {
16109     // Do not complain about the form of friend template types during any kind
16110     // of code synthesis. For template instantiation, we will have complained
16111     // when the template was defined.
16112   } else {
16113     if (!T->isElaboratedTypeSpecifier()) {
16114       // If we evaluated the type to a record type, suggest putting
16115       // a tag in front.
16116       if (const RecordType *RT = T->getAs<RecordType>()) {
16117         RecordDecl *RD = RT->getDecl();
16118 
16119         SmallString<16> InsertionText(" ");
16120         InsertionText += RD->getKindName();
16121 
16122         Diag(TypeRange.getBegin(),
16123              getLangOpts().CPlusPlus11 ?
16124                diag::warn_cxx98_compat_unelaborated_friend_type :
16125                diag::ext_unelaborated_friend_type)
16126           << (unsigned) RD->getTagKind()
16127           << T
16128           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16129                                         InsertionText);
16130       } else {
16131         Diag(FriendLoc,
16132              getLangOpts().CPlusPlus11 ?
16133                diag::warn_cxx98_compat_nonclass_type_friend :
16134                diag::ext_nonclass_type_friend)
16135           << T
16136           << TypeRange;
16137       }
16138     } else if (T->getAs<EnumType>()) {
16139       Diag(FriendLoc,
16140            getLangOpts().CPlusPlus11 ?
16141              diag::warn_cxx98_compat_enum_friend :
16142              diag::ext_enum_friend)
16143         << T
16144         << TypeRange;
16145     }
16146 
16147     // C++11 [class.friend]p3:
16148     //   A friend declaration that does not declare a function shall have one
16149     //   of the following forms:
16150     //     friend elaborated-type-specifier ;
16151     //     friend simple-type-specifier ;
16152     //     friend typename-specifier ;
16153     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16154       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16155   }
16156 
16157   //   If the type specifier in a friend declaration designates a (possibly
16158   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16159   //   the friend declaration is ignored.
16160   return FriendDecl::Create(Context, CurContext,
16161                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16162                             FriendLoc);
16163 }
16164 
16165 /// Handle a friend tag declaration where the scope specifier was
16166 /// templated.
16167 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16168                                     unsigned TagSpec, SourceLocation TagLoc,
16169                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16170                                     SourceLocation NameLoc,
16171                                     const ParsedAttributesView &Attr,
16172                                     MultiTemplateParamsArg TempParamLists) {
16173   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16174 
16175   bool IsMemberSpecialization = false;
16176   bool Invalid = false;
16177 
16178   if (TemplateParameterList *TemplateParams =
16179           MatchTemplateParametersToScopeSpecifier(
16180               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16181               IsMemberSpecialization, Invalid)) {
16182     if (TemplateParams->size() > 0) {
16183       // This is a declaration of a class template.
16184       if (Invalid)
16185         return nullptr;
16186 
16187       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16188                                 NameLoc, Attr, TemplateParams, AS_public,
16189                                 /*ModulePrivateLoc=*/SourceLocation(),
16190                                 FriendLoc, TempParamLists.size() - 1,
16191                                 TempParamLists.data()).get();
16192     } else {
16193       // The "template<>" header is extraneous.
16194       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16195         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16196       IsMemberSpecialization = true;
16197     }
16198   }
16199 
16200   if (Invalid) return nullptr;
16201 
16202   bool isAllExplicitSpecializations = true;
16203   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16204     if (TempParamLists[I]->size()) {
16205       isAllExplicitSpecializations = false;
16206       break;
16207     }
16208   }
16209 
16210   // FIXME: don't ignore attributes.
16211 
16212   // If it's explicit specializations all the way down, just forget
16213   // about the template header and build an appropriate non-templated
16214   // friend.  TODO: for source fidelity, remember the headers.
16215   if (isAllExplicitSpecializations) {
16216     if (SS.isEmpty()) {
16217       bool Owned = false;
16218       bool IsDependent = false;
16219       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16220                       Attr, AS_public,
16221                       /*ModulePrivateLoc=*/SourceLocation(),
16222                       MultiTemplateParamsArg(), Owned, IsDependent,
16223                       /*ScopedEnumKWLoc=*/SourceLocation(),
16224                       /*ScopedEnumUsesClassTag=*/false,
16225                       /*UnderlyingType=*/TypeResult(),
16226                       /*IsTypeSpecifier=*/false,
16227                       /*IsTemplateParamOrArg=*/false);
16228     }
16229 
16230     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16231     ElaboratedTypeKeyword Keyword
16232       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16233     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16234                                    *Name, NameLoc);
16235     if (T.isNull())
16236       return nullptr;
16237 
16238     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16239     if (isa<DependentNameType>(T)) {
16240       DependentNameTypeLoc TL =
16241           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16242       TL.setElaboratedKeywordLoc(TagLoc);
16243       TL.setQualifierLoc(QualifierLoc);
16244       TL.setNameLoc(NameLoc);
16245     } else {
16246       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16247       TL.setElaboratedKeywordLoc(TagLoc);
16248       TL.setQualifierLoc(QualifierLoc);
16249       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16250     }
16251 
16252     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16253                                             TSI, FriendLoc, TempParamLists);
16254     Friend->setAccess(AS_public);
16255     CurContext->addDecl(Friend);
16256     return Friend;
16257   }
16258 
16259   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16260 
16261 
16262 
16263   // Handle the case of a templated-scope friend class.  e.g.
16264   //   template <class T> class A<T>::B;
16265   // FIXME: we don't support these right now.
16266   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16267     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16268   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16269   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16270   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16271   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16272   TL.setElaboratedKeywordLoc(TagLoc);
16273   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16274   TL.setNameLoc(NameLoc);
16275 
16276   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16277                                           TSI, FriendLoc, TempParamLists);
16278   Friend->setAccess(AS_public);
16279   Friend->setUnsupportedFriend(true);
16280   CurContext->addDecl(Friend);
16281   return Friend;
16282 }
16283 
16284 /// Handle a friend type declaration.  This works in tandem with
16285 /// ActOnTag.
16286 ///
16287 /// Notes on friend class templates:
16288 ///
16289 /// We generally treat friend class declarations as if they were
16290 /// declaring a class.  So, for example, the elaborated type specifier
16291 /// in a friend declaration is required to obey the restrictions of a
16292 /// class-head (i.e. no typedefs in the scope chain), template
16293 /// parameters are required to match up with simple template-ids, &c.
16294 /// However, unlike when declaring a template specialization, it's
16295 /// okay to refer to a template specialization without an empty
16296 /// template parameter declaration, e.g.
16297 ///   friend class A<T>::B<unsigned>;
16298 /// We permit this as a special case; if there are any template
16299 /// parameters present at all, require proper matching, i.e.
16300 ///   template <> template \<class T> friend class A<int>::B;
16301 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16302                                 MultiTemplateParamsArg TempParams) {
16303   SourceLocation Loc = DS.getBeginLoc();
16304 
16305   assert(DS.isFriendSpecified());
16306   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16307 
16308   // C++ [class.friend]p3:
16309   // A friend declaration that does not declare a function shall have one of
16310   // the following forms:
16311   //     friend elaborated-type-specifier ;
16312   //     friend simple-type-specifier ;
16313   //     friend typename-specifier ;
16314   //
16315   // Any declaration with a type qualifier does not have that form. (It's
16316   // legal to specify a qualified type as a friend, you just can't write the
16317   // keywords.)
16318   if (DS.getTypeQualifiers()) {
16319     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16320       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16321     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16322       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16323     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16324       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16325     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16326       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16327     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16328       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16329   }
16330 
16331   // Try to convert the decl specifier to a type.  This works for
16332   // friend templates because ActOnTag never produces a ClassTemplateDecl
16333   // for a TUK_Friend.
16334   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16335   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16336   QualType T = TSI->getType();
16337   if (TheDeclarator.isInvalidType())
16338     return nullptr;
16339 
16340   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16341     return nullptr;
16342 
16343   // This is definitely an error in C++98.  It's probably meant to
16344   // be forbidden in C++0x, too, but the specification is just
16345   // poorly written.
16346   //
16347   // The problem is with declarations like the following:
16348   //   template <T> friend A<T>::foo;
16349   // where deciding whether a class C is a friend or not now hinges
16350   // on whether there exists an instantiation of A that causes
16351   // 'foo' to equal C.  There are restrictions on class-heads
16352   // (which we declare (by fiat) elaborated friend declarations to
16353   // be) that makes this tractable.
16354   //
16355   // FIXME: handle "template <> friend class A<T>;", which
16356   // is possibly well-formed?  Who even knows?
16357   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16358     Diag(Loc, diag::err_tagless_friend_type_template)
16359       << DS.getSourceRange();
16360     return nullptr;
16361   }
16362 
16363   // C++98 [class.friend]p1: A friend of a class is a function
16364   //   or class that is not a member of the class . . .
16365   // This is fixed in DR77, which just barely didn't make the C++03
16366   // deadline.  It's also a very silly restriction that seriously
16367   // affects inner classes and which nobody else seems to implement;
16368   // thus we never diagnose it, not even in -pedantic.
16369   //
16370   // But note that we could warn about it: it's always useless to
16371   // friend one of your own members (it's not, however, worthless to
16372   // friend a member of an arbitrary specialization of your template).
16373 
16374   Decl *D;
16375   if (!TempParams.empty())
16376     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16377                                    TempParams,
16378                                    TSI,
16379                                    DS.getFriendSpecLoc());
16380   else
16381     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16382 
16383   if (!D)
16384     return nullptr;
16385 
16386   D->setAccess(AS_public);
16387   CurContext->addDecl(D);
16388 
16389   return D;
16390 }
16391 
16392 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16393                                         MultiTemplateParamsArg TemplateParams) {
16394   const DeclSpec &DS = D.getDeclSpec();
16395 
16396   assert(DS.isFriendSpecified());
16397   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16398 
16399   SourceLocation Loc = D.getIdentifierLoc();
16400   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16401 
16402   // C++ [class.friend]p1
16403   //   A friend of a class is a function or class....
16404   // Note that this sees through typedefs, which is intended.
16405   // It *doesn't* see through dependent types, which is correct
16406   // according to [temp.arg.type]p3:
16407   //   If a declaration acquires a function type through a
16408   //   type dependent on a template-parameter and this causes
16409   //   a declaration that does not use the syntactic form of a
16410   //   function declarator to have a function type, the program
16411   //   is ill-formed.
16412   if (!TInfo->getType()->isFunctionType()) {
16413     Diag(Loc, diag::err_unexpected_friend);
16414 
16415     // It might be worthwhile to try to recover by creating an
16416     // appropriate declaration.
16417     return nullptr;
16418   }
16419 
16420   // C++ [namespace.memdef]p3
16421   //  - If a friend declaration in a non-local class first declares a
16422   //    class or function, the friend class or function is a member
16423   //    of the innermost enclosing namespace.
16424   //  - The name of the friend is not found by simple name lookup
16425   //    until a matching declaration is provided in that namespace
16426   //    scope (either before or after the class declaration granting
16427   //    friendship).
16428   //  - If a friend function is called, its name may be found by the
16429   //    name lookup that considers functions from namespaces and
16430   //    classes associated with the types of the function arguments.
16431   //  - When looking for a prior declaration of a class or a function
16432   //    declared as a friend, scopes outside the innermost enclosing
16433   //    namespace scope are not considered.
16434 
16435   CXXScopeSpec &SS = D.getCXXScopeSpec();
16436   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16437   assert(NameInfo.getName());
16438 
16439   // Check for unexpanded parameter packs.
16440   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16441       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16442       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16443     return nullptr;
16444 
16445   // The context we found the declaration in, or in which we should
16446   // create the declaration.
16447   DeclContext *DC;
16448   Scope *DCScope = S;
16449   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16450                         ForExternalRedeclaration);
16451 
16452   // There are five cases here.
16453   //   - There's no scope specifier and we're in a local class. Only look
16454   //     for functions declared in the immediately-enclosing block scope.
16455   // We recover from invalid scope qualifiers as if they just weren't there.
16456   FunctionDecl *FunctionContainingLocalClass = nullptr;
16457   if ((SS.isInvalid() || !SS.isSet()) &&
16458       (FunctionContainingLocalClass =
16459            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16460     // C++11 [class.friend]p11:
16461     //   If a friend declaration appears in a local class and the name
16462     //   specified is an unqualified name, a prior declaration is
16463     //   looked up without considering scopes that are outside the
16464     //   innermost enclosing non-class scope. For a friend function
16465     //   declaration, if there is no prior declaration, the program is
16466     //   ill-formed.
16467 
16468     // Find the innermost enclosing non-class scope. This is the block
16469     // scope containing the local class definition (or for a nested class,
16470     // the outer local class).
16471     DCScope = S->getFnParent();
16472 
16473     // Look up the function name in the scope.
16474     Previous.clear(LookupLocalFriendName);
16475     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16476 
16477     if (!Previous.empty()) {
16478       // All possible previous declarations must have the same context:
16479       // either they were declared at block scope or they are members of
16480       // one of the enclosing local classes.
16481       DC = Previous.getRepresentativeDecl()->getDeclContext();
16482     } else {
16483       // This is ill-formed, but provide the context that we would have
16484       // declared the function in, if we were permitted to, for error recovery.
16485       DC = FunctionContainingLocalClass;
16486     }
16487     adjustContextForLocalExternDecl(DC);
16488 
16489     // C++ [class.friend]p6:
16490     //   A function can be defined in a friend declaration of a class if and
16491     //   only if the class is a non-local class (9.8), the function name is
16492     //   unqualified, and the function has namespace scope.
16493     if (D.isFunctionDefinition()) {
16494       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16495     }
16496 
16497   //   - There's no scope specifier, in which case we just go to the
16498   //     appropriate scope and look for a function or function template
16499   //     there as appropriate.
16500   } else if (SS.isInvalid() || !SS.isSet()) {
16501     // C++11 [namespace.memdef]p3:
16502     //   If the name in a friend declaration is neither qualified nor
16503     //   a template-id and the declaration is a function or an
16504     //   elaborated-type-specifier, the lookup to determine whether
16505     //   the entity has been previously declared shall not consider
16506     //   any scopes outside the innermost enclosing namespace.
16507     bool isTemplateId =
16508         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16509 
16510     // Find the appropriate context according to the above.
16511     DC = CurContext;
16512 
16513     // Skip class contexts.  If someone can cite chapter and verse
16514     // for this behavior, that would be nice --- it's what GCC and
16515     // EDG do, and it seems like a reasonable intent, but the spec
16516     // really only says that checks for unqualified existing
16517     // declarations should stop at the nearest enclosing namespace,
16518     // not that they should only consider the nearest enclosing
16519     // namespace.
16520     while (DC->isRecord())
16521       DC = DC->getParent();
16522 
16523     DeclContext *LookupDC = DC;
16524     while (LookupDC->isTransparentContext())
16525       LookupDC = LookupDC->getParent();
16526 
16527     while (true) {
16528       LookupQualifiedName(Previous, LookupDC);
16529 
16530       if (!Previous.empty()) {
16531         DC = LookupDC;
16532         break;
16533       }
16534 
16535       if (isTemplateId) {
16536         if (isa<TranslationUnitDecl>(LookupDC)) break;
16537       } else {
16538         if (LookupDC->isFileContext()) break;
16539       }
16540       LookupDC = LookupDC->getParent();
16541     }
16542 
16543     DCScope = getScopeForDeclContext(S, DC);
16544 
16545   //   - There's a non-dependent scope specifier, in which case we
16546   //     compute it and do a previous lookup there for a function
16547   //     or function template.
16548   } else if (!SS.getScopeRep()->isDependent()) {
16549     DC = computeDeclContext(SS);
16550     if (!DC) return nullptr;
16551 
16552     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16553 
16554     LookupQualifiedName(Previous, DC);
16555 
16556     // C++ [class.friend]p1: A friend of a class is a function or
16557     //   class that is not a member of the class . . .
16558     if (DC->Equals(CurContext))
16559       Diag(DS.getFriendSpecLoc(),
16560            getLangOpts().CPlusPlus11 ?
16561              diag::warn_cxx98_compat_friend_is_member :
16562              diag::err_friend_is_member);
16563 
16564     if (D.isFunctionDefinition()) {
16565       // C++ [class.friend]p6:
16566       //   A function can be defined in a friend declaration of a class if and
16567       //   only if the class is a non-local class (9.8), the function name is
16568       //   unqualified, and the function has namespace scope.
16569       //
16570       // FIXME: We should only do this if the scope specifier names the
16571       // innermost enclosing namespace; otherwise the fixit changes the
16572       // meaning of the code.
16573       SemaDiagnosticBuilder DB
16574         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16575 
16576       DB << SS.getScopeRep();
16577       if (DC->isFileContext())
16578         DB << FixItHint::CreateRemoval(SS.getRange());
16579       SS.clear();
16580     }
16581 
16582   //   - There's a scope specifier that does not match any template
16583   //     parameter lists, in which case we use some arbitrary context,
16584   //     create a method or method template, and wait for instantiation.
16585   //   - There's a scope specifier that does match some template
16586   //     parameter lists, which we don't handle right now.
16587   } else {
16588     if (D.isFunctionDefinition()) {
16589       // C++ [class.friend]p6:
16590       //   A function can be defined in a friend declaration of a class if and
16591       //   only if the class is a non-local class (9.8), the function name is
16592       //   unqualified, and the function has namespace scope.
16593       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16594         << SS.getScopeRep();
16595     }
16596 
16597     DC = CurContext;
16598     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16599   }
16600 
16601   if (!DC->isRecord()) {
16602     int DiagArg = -1;
16603     switch (D.getName().getKind()) {
16604     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16605     case UnqualifiedIdKind::IK_ConstructorName:
16606       DiagArg = 0;
16607       break;
16608     case UnqualifiedIdKind::IK_DestructorName:
16609       DiagArg = 1;
16610       break;
16611     case UnqualifiedIdKind::IK_ConversionFunctionId:
16612       DiagArg = 2;
16613       break;
16614     case UnqualifiedIdKind::IK_DeductionGuideName:
16615       DiagArg = 3;
16616       break;
16617     case UnqualifiedIdKind::IK_Identifier:
16618     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16619     case UnqualifiedIdKind::IK_LiteralOperatorId:
16620     case UnqualifiedIdKind::IK_OperatorFunctionId:
16621     case UnqualifiedIdKind::IK_TemplateId:
16622       break;
16623     }
16624     // This implies that it has to be an operator or function.
16625     if (DiagArg >= 0) {
16626       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16627       return nullptr;
16628     }
16629   }
16630 
16631   // FIXME: This is an egregious hack to cope with cases where the scope stack
16632   // does not contain the declaration context, i.e., in an out-of-line
16633   // definition of a class.
16634   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16635   if (!DCScope) {
16636     FakeDCScope.setEntity(DC);
16637     DCScope = &FakeDCScope;
16638   }
16639 
16640   bool AddToScope = true;
16641   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16642                                           TemplateParams, AddToScope);
16643   if (!ND) return nullptr;
16644 
16645   assert(ND->getLexicalDeclContext() == CurContext);
16646 
16647   // If we performed typo correction, we might have added a scope specifier
16648   // and changed the decl context.
16649   DC = ND->getDeclContext();
16650 
16651   // Add the function declaration to the appropriate lookup tables,
16652   // adjusting the redeclarations list as necessary.  We don't
16653   // want to do this yet if the friending class is dependent.
16654   //
16655   // Also update the scope-based lookup if the target context's
16656   // lookup context is in lexical scope.
16657   if (!CurContext->isDependentContext()) {
16658     DC = DC->getRedeclContext();
16659     DC->makeDeclVisibleInContext(ND);
16660     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16661       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16662   }
16663 
16664   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16665                                        D.getIdentifierLoc(), ND,
16666                                        DS.getFriendSpecLoc());
16667   FrD->setAccess(AS_public);
16668   CurContext->addDecl(FrD);
16669 
16670   if (ND->isInvalidDecl()) {
16671     FrD->setInvalidDecl();
16672   } else {
16673     if (DC->isRecord()) CheckFriendAccess(ND);
16674 
16675     FunctionDecl *FD;
16676     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16677       FD = FTD->getTemplatedDecl();
16678     else
16679       FD = cast<FunctionDecl>(ND);
16680 
16681     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16682     // default argument expression, that declaration shall be a definition
16683     // and shall be the only declaration of the function or function
16684     // template in the translation unit.
16685     if (functionDeclHasDefaultArgument(FD)) {
16686       // We can't look at FD->getPreviousDecl() because it may not have been set
16687       // if we're in a dependent context. If the function is known to be a
16688       // redeclaration, we will have narrowed Previous down to the right decl.
16689       if (D.isRedeclaration()) {
16690         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16691         Diag(Previous.getRepresentativeDecl()->getLocation(),
16692              diag::note_previous_declaration);
16693       } else if (!D.isFunctionDefinition())
16694         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16695     }
16696 
16697     // Mark templated-scope function declarations as unsupported.
16698     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16699       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16700         << SS.getScopeRep() << SS.getRange()
16701         << cast<CXXRecordDecl>(CurContext);
16702       FrD->setUnsupportedFriend(true);
16703     }
16704   }
16705 
16706   return ND;
16707 }
16708 
16709 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16710   AdjustDeclIfTemplate(Dcl);
16711 
16712   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16713   if (!Fn) {
16714     Diag(DelLoc, diag::err_deleted_non_function);
16715     return;
16716   }
16717 
16718   // Deleted function does not have a body.
16719   Fn->setWillHaveBody(false);
16720 
16721   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16722     // Don't consider the implicit declaration we generate for explicit
16723     // specializations. FIXME: Do not generate these implicit declarations.
16724     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16725          Prev->getPreviousDecl()) &&
16726         !Prev->isDefined()) {
16727       Diag(DelLoc, diag::err_deleted_decl_not_first);
16728       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16729            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16730                               : diag::note_previous_declaration);
16731       // We can't recover from this; the declaration might have already
16732       // been used.
16733       Fn->setInvalidDecl();
16734       return;
16735     }
16736 
16737     // To maintain the invariant that functions are only deleted on their first
16738     // declaration, mark the implicitly-instantiated declaration of the
16739     // explicitly-specialized function as deleted instead of marking the
16740     // instantiated redeclaration.
16741     Fn = Fn->getCanonicalDecl();
16742   }
16743 
16744   // dllimport/dllexport cannot be deleted.
16745   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16746     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16747     Fn->setInvalidDecl();
16748   }
16749 
16750   // C++11 [basic.start.main]p3:
16751   //   A program that defines main as deleted [...] is ill-formed.
16752   if (Fn->isMain())
16753     Diag(DelLoc, diag::err_deleted_main);
16754 
16755   // C++11 [dcl.fct.def.delete]p4:
16756   //  A deleted function is implicitly inline.
16757   Fn->setImplicitlyInline();
16758   Fn->setDeletedAsWritten();
16759 }
16760 
16761 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16762   if (!Dcl || Dcl->isInvalidDecl())
16763     return;
16764 
16765   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16766   if (!FD) {
16767     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16768       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16769         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16770         return;
16771       }
16772     }
16773 
16774     Diag(DefaultLoc, diag::err_default_special_members)
16775         << getLangOpts().CPlusPlus20;
16776     return;
16777   }
16778 
16779   // Reject if this can't possibly be a defaultable function.
16780   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16781   if (!DefKind &&
16782       // A dependent function that doesn't locally look defaultable can
16783       // still instantiate to a defaultable function if it's a constructor
16784       // or assignment operator.
16785       (!FD->isDependentContext() ||
16786        (!isa<CXXConstructorDecl>(FD) &&
16787         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16788     Diag(DefaultLoc, diag::err_default_special_members)
16789         << getLangOpts().CPlusPlus20;
16790     return;
16791   }
16792 
16793   if (DefKind.isComparison() &&
16794       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16795     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16796         << (int)DefKind.asComparison();
16797     return;
16798   }
16799 
16800   // Issue compatibility warning. We already warned if the operator is
16801   // 'operator<=>' when parsing the '<=>' token.
16802   if (DefKind.isComparison() &&
16803       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16804     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16805                          ? diag::warn_cxx17_compat_defaulted_comparison
16806                          : diag::ext_defaulted_comparison);
16807   }
16808 
16809   FD->setDefaulted();
16810   FD->setExplicitlyDefaulted();
16811 
16812   // Defer checking functions that are defaulted in a dependent context.
16813   if (FD->isDependentContext())
16814     return;
16815 
16816   // Unset that we will have a body for this function. We might not,
16817   // if it turns out to be trivial, and we don't need this marking now
16818   // that we've marked it as defaulted.
16819   FD->setWillHaveBody(false);
16820 
16821   // If this definition appears within the record, do the checking when
16822   // the record is complete. This is always the case for a defaulted
16823   // comparison.
16824   if (DefKind.isComparison())
16825     return;
16826   auto *MD = cast<CXXMethodDecl>(FD);
16827 
16828   const FunctionDecl *Primary = FD;
16829   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16830     // Ask the template instantiation pattern that actually had the
16831     // '= default' on it.
16832     Primary = Pattern;
16833 
16834   // If the method was defaulted on its first declaration, we will have
16835   // already performed the checking in CheckCompletedCXXClass. Such a
16836   // declaration doesn't trigger an implicit definition.
16837   if (Primary->getCanonicalDecl()->isDefaulted())
16838     return;
16839 
16840   // FIXME: Once we support defining comparisons out of class, check for a
16841   // defaulted comparison here.
16842   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16843     MD->setInvalidDecl();
16844   else
16845     DefineDefaultedFunction(*this, MD, DefaultLoc);
16846 }
16847 
16848 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16849   for (Stmt *SubStmt : S->children()) {
16850     if (!SubStmt)
16851       continue;
16852     if (isa<ReturnStmt>(SubStmt))
16853       Self.Diag(SubStmt->getBeginLoc(),
16854                 diag::err_return_in_constructor_handler);
16855     if (!isa<Expr>(SubStmt))
16856       SearchForReturnInStmt(Self, SubStmt);
16857   }
16858 }
16859 
16860 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16861   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16862     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16863     SearchForReturnInStmt(*this, Handler);
16864   }
16865 }
16866 
16867 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16868                                              const CXXMethodDecl *Old) {
16869   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16870   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16871 
16872   if (OldFT->hasExtParameterInfos()) {
16873     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16874       // A parameter of the overriding method should be annotated with noescape
16875       // if the corresponding parameter of the overridden method is annotated.
16876       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16877           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16878         Diag(New->getParamDecl(I)->getLocation(),
16879              diag::warn_overriding_method_missing_noescape);
16880         Diag(Old->getParamDecl(I)->getLocation(),
16881              diag::note_overridden_marked_noescape);
16882       }
16883   }
16884 
16885   // Virtual overrides must have the same code_seg.
16886   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16887   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16888   if ((NewCSA || OldCSA) &&
16889       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16890     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16891     Diag(Old->getLocation(), diag::note_previous_declaration);
16892     return true;
16893   }
16894 
16895   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16896 
16897   // If the calling conventions match, everything is fine
16898   if (NewCC == OldCC)
16899     return false;
16900 
16901   // If the calling conventions mismatch because the new function is static,
16902   // suppress the calling convention mismatch error; the error about static
16903   // function override (err_static_overrides_virtual from
16904   // Sema::CheckFunctionDeclaration) is more clear.
16905   if (New->getStorageClass() == SC_Static)
16906     return false;
16907 
16908   Diag(New->getLocation(),
16909        diag::err_conflicting_overriding_cc_attributes)
16910     << New->getDeclName() << New->getType() << Old->getType();
16911   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16912   return true;
16913 }
16914 
16915 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16916                                              const CXXMethodDecl *Old) {
16917   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16918   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16919 
16920   if (Context.hasSameType(NewTy, OldTy) ||
16921       NewTy->isDependentType() || OldTy->isDependentType())
16922     return false;
16923 
16924   // Check if the return types are covariant
16925   QualType NewClassTy, OldClassTy;
16926 
16927   /// Both types must be pointers or references to classes.
16928   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16929     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16930       NewClassTy = NewPT->getPointeeType();
16931       OldClassTy = OldPT->getPointeeType();
16932     }
16933   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16934     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16935       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16936         NewClassTy = NewRT->getPointeeType();
16937         OldClassTy = OldRT->getPointeeType();
16938       }
16939     }
16940   }
16941 
16942   // The return types aren't either both pointers or references to a class type.
16943   if (NewClassTy.isNull()) {
16944     Diag(New->getLocation(),
16945          diag::err_different_return_type_for_overriding_virtual_function)
16946         << New->getDeclName() << NewTy << OldTy
16947         << New->getReturnTypeSourceRange();
16948     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16949         << Old->getReturnTypeSourceRange();
16950 
16951     return true;
16952   }
16953 
16954   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16955     // C++14 [class.virtual]p8:
16956     //   If the class type in the covariant return type of D::f differs from
16957     //   that of B::f, the class type in the return type of D::f shall be
16958     //   complete at the point of declaration of D::f or shall be the class
16959     //   type D.
16960     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16961       if (!RT->isBeingDefined() &&
16962           RequireCompleteType(New->getLocation(), NewClassTy,
16963                               diag::err_covariant_return_incomplete,
16964                               New->getDeclName()))
16965         return true;
16966     }
16967 
16968     // Check if the new class derives from the old class.
16969     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16970       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16971           << New->getDeclName() << NewTy << OldTy
16972           << New->getReturnTypeSourceRange();
16973       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16974           << Old->getReturnTypeSourceRange();
16975       return true;
16976     }
16977 
16978     // Check if we the conversion from derived to base is valid.
16979     if (CheckDerivedToBaseConversion(
16980             NewClassTy, OldClassTy,
16981             diag::err_covariant_return_inaccessible_base,
16982             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16983             New->getLocation(), New->getReturnTypeSourceRange(),
16984             New->getDeclName(), nullptr)) {
16985       // FIXME: this note won't trigger for delayed access control
16986       // diagnostics, and it's impossible to get an undelayed error
16987       // here from access control during the original parse because
16988       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16989       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16990           << Old->getReturnTypeSourceRange();
16991       return true;
16992     }
16993   }
16994 
16995   // The qualifiers of the return types must be the same.
16996   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16997     Diag(New->getLocation(),
16998          diag::err_covariant_return_type_different_qualifications)
16999         << New->getDeclName() << NewTy << OldTy
17000         << New->getReturnTypeSourceRange();
17001     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17002         << Old->getReturnTypeSourceRange();
17003     return true;
17004   }
17005 
17006 
17007   // The new class type must have the same or less qualifiers as the old type.
17008   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17009     Diag(New->getLocation(),
17010          diag::err_covariant_return_type_class_type_more_qualified)
17011         << New->getDeclName() << NewTy << OldTy
17012         << New->getReturnTypeSourceRange();
17013     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17014         << Old->getReturnTypeSourceRange();
17015     return true;
17016   }
17017 
17018   return false;
17019 }
17020 
17021 /// Mark the given method pure.
17022 ///
17023 /// \param Method the method to be marked pure.
17024 ///
17025 /// \param InitRange the source range that covers the "0" initializer.
17026 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17027   SourceLocation EndLoc = InitRange.getEnd();
17028   if (EndLoc.isValid())
17029     Method->setRangeEnd(EndLoc);
17030 
17031   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17032     Method->setPure();
17033     return false;
17034   }
17035 
17036   if (!Method->isInvalidDecl())
17037     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17038       << Method->getDeclName() << InitRange;
17039   return true;
17040 }
17041 
17042 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17043   if (D->getFriendObjectKind())
17044     Diag(D->getLocation(), diag::err_pure_friend);
17045   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17046     CheckPureMethod(M, ZeroLoc);
17047   else
17048     Diag(D->getLocation(), diag::err_illegal_initializer);
17049 }
17050 
17051 /// Determine whether the given declaration is a global variable or
17052 /// static data member.
17053 static bool isNonlocalVariable(const Decl *D) {
17054   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17055     return Var->hasGlobalStorage();
17056 
17057   return false;
17058 }
17059 
17060 /// Invoked when we are about to parse an initializer for the declaration
17061 /// 'Dcl'.
17062 ///
17063 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17064 /// static data member of class X, names should be looked up in the scope of
17065 /// class X. If the declaration had a scope specifier, a scope will have
17066 /// been created and passed in for this purpose. Otherwise, S will be null.
17067 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17068   // If there is no declaration, there was an error parsing it.
17069   if (!D || D->isInvalidDecl())
17070     return;
17071 
17072   // We will always have a nested name specifier here, but this declaration
17073   // might not be out of line if the specifier names the current namespace:
17074   //   extern int n;
17075   //   int ::n = 0;
17076   if (S && D->isOutOfLine())
17077     EnterDeclaratorContext(S, D->getDeclContext());
17078 
17079   // If we are parsing the initializer for a static data member, push a
17080   // new expression evaluation context that is associated with this static
17081   // data member.
17082   if (isNonlocalVariable(D))
17083     PushExpressionEvaluationContext(
17084         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17085 }
17086 
17087 /// Invoked after we are finished parsing an initializer for the declaration D.
17088 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17089   // If there is no declaration, there was an error parsing it.
17090   if (!D || D->isInvalidDecl())
17091     return;
17092 
17093   if (isNonlocalVariable(D))
17094     PopExpressionEvaluationContext();
17095 
17096   if (S && D->isOutOfLine())
17097     ExitDeclaratorContext(S);
17098 }
17099 
17100 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17101 /// C++ if/switch/while/for statement.
17102 /// e.g: "if (int x = f()) {...}"
17103 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17104   // C++ 6.4p2:
17105   // The declarator shall not specify a function or an array.
17106   // The type-specifier-seq shall not contain typedef and shall not declare a
17107   // new class or enumeration.
17108   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17109          "Parser allowed 'typedef' as storage class of condition decl.");
17110 
17111   Decl *Dcl = ActOnDeclarator(S, D);
17112   if (!Dcl)
17113     return true;
17114 
17115   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17116     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17117       << D.getSourceRange();
17118     return true;
17119   }
17120 
17121   return Dcl;
17122 }
17123 
17124 void Sema::LoadExternalVTableUses() {
17125   if (!ExternalSource)
17126     return;
17127 
17128   SmallVector<ExternalVTableUse, 4> VTables;
17129   ExternalSource->ReadUsedVTables(VTables);
17130   SmallVector<VTableUse, 4> NewUses;
17131   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17132     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17133       = VTablesUsed.find(VTables[I].Record);
17134     // Even if a definition wasn't required before, it may be required now.
17135     if (Pos != VTablesUsed.end()) {
17136       if (!Pos->second && VTables[I].DefinitionRequired)
17137         Pos->second = true;
17138       continue;
17139     }
17140 
17141     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17142     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17143   }
17144 
17145   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17146 }
17147 
17148 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17149                           bool DefinitionRequired) {
17150   // Ignore any vtable uses in unevaluated operands or for classes that do
17151   // not have a vtable.
17152   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17153       CurContext->isDependentContext() || isUnevaluatedContext())
17154     return;
17155   // Do not mark as used if compiling for the device outside of the target
17156   // region.
17157   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17158       !isInOpenMPDeclareTargetContext() &&
17159       !isInOpenMPTargetExecutionDirective()) {
17160     if (!DefinitionRequired)
17161       MarkVirtualMembersReferenced(Loc, Class);
17162     return;
17163   }
17164 
17165   // Try to insert this class into the map.
17166   LoadExternalVTableUses();
17167   Class = Class->getCanonicalDecl();
17168   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17169     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17170   if (!Pos.second) {
17171     // If we already had an entry, check to see if we are promoting this vtable
17172     // to require a definition. If so, we need to reappend to the VTableUses
17173     // list, since we may have already processed the first entry.
17174     if (DefinitionRequired && !Pos.first->second) {
17175       Pos.first->second = true;
17176     } else {
17177       // Otherwise, we can early exit.
17178       return;
17179     }
17180   } else {
17181     // The Microsoft ABI requires that we perform the destructor body
17182     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17183     // the deleting destructor is emitted with the vtable, not with the
17184     // destructor definition as in the Itanium ABI.
17185     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17186       CXXDestructorDecl *DD = Class->getDestructor();
17187       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17188         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17189           // If this is an out-of-line declaration, marking it referenced will
17190           // not do anything. Manually call CheckDestructor to look up operator
17191           // delete().
17192           ContextRAII SavedContext(*this, DD);
17193           CheckDestructor(DD);
17194         } else {
17195           MarkFunctionReferenced(Loc, Class->getDestructor());
17196         }
17197       }
17198     }
17199   }
17200 
17201   // Local classes need to have their virtual members marked
17202   // immediately. For all other classes, we mark their virtual members
17203   // at the end of the translation unit.
17204   if (Class->isLocalClass())
17205     MarkVirtualMembersReferenced(Loc, Class);
17206   else
17207     VTableUses.push_back(std::make_pair(Class, Loc));
17208 }
17209 
17210 bool Sema::DefineUsedVTables() {
17211   LoadExternalVTableUses();
17212   if (VTableUses.empty())
17213     return false;
17214 
17215   // Note: The VTableUses vector could grow as a result of marking
17216   // the members of a class as "used", so we check the size each
17217   // time through the loop and prefer indices (which are stable) to
17218   // iterators (which are not).
17219   bool DefinedAnything = false;
17220   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17221     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17222     if (!Class)
17223       continue;
17224     TemplateSpecializationKind ClassTSK =
17225         Class->getTemplateSpecializationKind();
17226 
17227     SourceLocation Loc = VTableUses[I].second;
17228 
17229     bool DefineVTable = true;
17230 
17231     // If this class has a key function, but that key function is
17232     // defined in another translation unit, we don't need to emit the
17233     // vtable even though we're using it.
17234     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17235     if (KeyFunction && !KeyFunction->hasBody()) {
17236       // The key function is in another translation unit.
17237       DefineVTable = false;
17238       TemplateSpecializationKind TSK =
17239           KeyFunction->getTemplateSpecializationKind();
17240       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17241              TSK != TSK_ImplicitInstantiation &&
17242              "Instantiations don't have key functions");
17243       (void)TSK;
17244     } else if (!KeyFunction) {
17245       // If we have a class with no key function that is the subject
17246       // of an explicit instantiation declaration, suppress the
17247       // vtable; it will live with the explicit instantiation
17248       // definition.
17249       bool IsExplicitInstantiationDeclaration =
17250           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17251       for (auto R : Class->redecls()) {
17252         TemplateSpecializationKind TSK
17253           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17254         if (TSK == TSK_ExplicitInstantiationDeclaration)
17255           IsExplicitInstantiationDeclaration = true;
17256         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17257           IsExplicitInstantiationDeclaration = false;
17258           break;
17259         }
17260       }
17261 
17262       if (IsExplicitInstantiationDeclaration)
17263         DefineVTable = false;
17264     }
17265 
17266     // The exception specifications for all virtual members may be needed even
17267     // if we are not providing an authoritative form of the vtable in this TU.
17268     // We may choose to emit it available_externally anyway.
17269     if (!DefineVTable) {
17270       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17271       continue;
17272     }
17273 
17274     // Mark all of the virtual members of this class as referenced, so
17275     // that we can build a vtable. Then, tell the AST consumer that a
17276     // vtable for this class is required.
17277     DefinedAnything = true;
17278     MarkVirtualMembersReferenced(Loc, Class);
17279     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17280     if (VTablesUsed[Canonical])
17281       Consumer.HandleVTable(Class);
17282 
17283     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17284     // no key function or the key function is inlined. Don't warn in C++ ABIs
17285     // that lack key functions, since the user won't be able to make one.
17286     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17287         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17288       const FunctionDecl *KeyFunctionDef = nullptr;
17289       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17290                            KeyFunctionDef->isInlined())) {
17291         Diag(Class->getLocation(),
17292              ClassTSK == TSK_ExplicitInstantiationDefinition
17293                  ? diag::warn_weak_template_vtable
17294                  : diag::warn_weak_vtable)
17295             << Class;
17296       }
17297     }
17298   }
17299   VTableUses.clear();
17300 
17301   return DefinedAnything;
17302 }
17303 
17304 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17305                                                  const CXXRecordDecl *RD) {
17306   for (const auto *I : RD->methods())
17307     if (I->isVirtual() && !I->isPure())
17308       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17309 }
17310 
17311 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17312                                         const CXXRecordDecl *RD,
17313                                         bool ConstexprOnly) {
17314   // Mark all functions which will appear in RD's vtable as used.
17315   CXXFinalOverriderMap FinalOverriders;
17316   RD->getFinalOverriders(FinalOverriders);
17317   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17318                                             E = FinalOverriders.end();
17319        I != E; ++I) {
17320     for (OverridingMethods::const_iterator OI = I->second.begin(),
17321                                            OE = I->second.end();
17322          OI != OE; ++OI) {
17323       assert(OI->second.size() > 0 && "no final overrider");
17324       CXXMethodDecl *Overrider = OI->second.front().Method;
17325 
17326       // C++ [basic.def.odr]p2:
17327       //   [...] A virtual member function is used if it is not pure. [...]
17328       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17329         MarkFunctionReferenced(Loc, Overrider);
17330     }
17331   }
17332 
17333   // Only classes that have virtual bases need a VTT.
17334   if (RD->getNumVBases() == 0)
17335     return;
17336 
17337   for (const auto &I : RD->bases()) {
17338     const auto *Base =
17339         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17340     if (Base->getNumVBases() == 0)
17341       continue;
17342     MarkVirtualMembersReferenced(Loc, Base);
17343   }
17344 }
17345 
17346 /// SetIvarInitializers - This routine builds initialization ASTs for the
17347 /// Objective-C implementation whose ivars need be initialized.
17348 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17349   if (!getLangOpts().CPlusPlus)
17350     return;
17351   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17352     SmallVector<ObjCIvarDecl*, 8> ivars;
17353     CollectIvarsToConstructOrDestruct(OID, ivars);
17354     if (ivars.empty())
17355       return;
17356     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17357     for (unsigned i = 0; i < ivars.size(); i++) {
17358       FieldDecl *Field = ivars[i];
17359       if (Field->isInvalidDecl())
17360         continue;
17361 
17362       CXXCtorInitializer *Member;
17363       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17364       InitializationKind InitKind =
17365         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17366 
17367       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17368       ExprResult MemberInit =
17369         InitSeq.Perform(*this, InitEntity, InitKind, None);
17370       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17371       // Note, MemberInit could actually come back empty if no initialization
17372       // is required (e.g., because it would call a trivial default constructor)
17373       if (!MemberInit.get() || MemberInit.isInvalid())
17374         continue;
17375 
17376       Member =
17377         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17378                                          SourceLocation(),
17379                                          MemberInit.getAs<Expr>(),
17380                                          SourceLocation());
17381       AllToInit.push_back(Member);
17382 
17383       // Be sure that the destructor is accessible and is marked as referenced.
17384       if (const RecordType *RecordTy =
17385               Context.getBaseElementType(Field->getType())
17386                   ->getAs<RecordType>()) {
17387         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17388         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17389           MarkFunctionReferenced(Field->getLocation(), Destructor);
17390           CheckDestructorAccess(Field->getLocation(), Destructor,
17391                             PDiag(diag::err_access_dtor_ivar)
17392                               << Context.getBaseElementType(Field->getType()));
17393         }
17394       }
17395     }
17396     ObjCImplementation->setIvarInitializers(Context,
17397                                             AllToInit.data(), AllToInit.size());
17398   }
17399 }
17400 
17401 static
17402 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17403                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17404                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17405                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17406                            Sema &S) {
17407   if (Ctor->isInvalidDecl())
17408     return;
17409 
17410   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17411 
17412   // Target may not be determinable yet, for instance if this is a dependent
17413   // call in an uninstantiated template.
17414   if (Target) {
17415     const FunctionDecl *FNTarget = nullptr;
17416     (void)Target->hasBody(FNTarget);
17417     Target = const_cast<CXXConstructorDecl*>(
17418       cast_or_null<CXXConstructorDecl>(FNTarget));
17419   }
17420 
17421   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17422                      // Avoid dereferencing a null pointer here.
17423                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17424 
17425   if (!Current.insert(Canonical).second)
17426     return;
17427 
17428   // We know that beyond here, we aren't chaining into a cycle.
17429   if (!Target || !Target->isDelegatingConstructor() ||
17430       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17431     Valid.insert(Current.begin(), Current.end());
17432     Current.clear();
17433   // We've hit a cycle.
17434   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17435              Current.count(TCanonical)) {
17436     // If we haven't diagnosed this cycle yet, do so now.
17437     if (!Invalid.count(TCanonical)) {
17438       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17439              diag::warn_delegating_ctor_cycle)
17440         << Ctor;
17441 
17442       // Don't add a note for a function delegating directly to itself.
17443       if (TCanonical != Canonical)
17444         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17445 
17446       CXXConstructorDecl *C = Target;
17447       while (C->getCanonicalDecl() != Canonical) {
17448         const FunctionDecl *FNTarget = nullptr;
17449         (void)C->getTargetConstructor()->hasBody(FNTarget);
17450         assert(FNTarget && "Ctor cycle through bodiless function");
17451 
17452         C = const_cast<CXXConstructorDecl*>(
17453           cast<CXXConstructorDecl>(FNTarget));
17454         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17455       }
17456     }
17457 
17458     Invalid.insert(Current.begin(), Current.end());
17459     Current.clear();
17460   } else {
17461     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17462   }
17463 }
17464 
17465 
17466 void Sema::CheckDelegatingCtorCycles() {
17467   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17468 
17469   for (DelegatingCtorDeclsType::iterator
17470          I = DelegatingCtorDecls.begin(ExternalSource),
17471          E = DelegatingCtorDecls.end();
17472        I != E; ++I)
17473     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17474 
17475   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17476     (*CI)->setInvalidDecl();
17477 }
17478 
17479 namespace {
17480   /// AST visitor that finds references to the 'this' expression.
17481   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17482     Sema &S;
17483 
17484   public:
17485     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17486 
17487     bool VisitCXXThisExpr(CXXThisExpr *E) {
17488       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17489         << E->isImplicit();
17490       return false;
17491     }
17492   };
17493 }
17494 
17495 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17496   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17497   if (!TSInfo)
17498     return false;
17499 
17500   TypeLoc TL = TSInfo->getTypeLoc();
17501   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17502   if (!ProtoTL)
17503     return false;
17504 
17505   // C++11 [expr.prim.general]p3:
17506   //   [The expression this] shall not appear before the optional
17507   //   cv-qualifier-seq and it shall not appear within the declaration of a
17508   //   static member function (although its type and value category are defined
17509   //   within a static member function as they are within a non-static member
17510   //   function). [ Note: this is because declaration matching does not occur
17511   //  until the complete declarator is known. - end note ]
17512   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17513   FindCXXThisExpr Finder(*this);
17514 
17515   // If the return type came after the cv-qualifier-seq, check it now.
17516   if (Proto->hasTrailingReturn() &&
17517       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17518     return true;
17519 
17520   // Check the exception specification.
17521   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17522     return true;
17523 
17524   // Check the trailing requires clause
17525   if (Expr *E = Method->getTrailingRequiresClause())
17526     if (!Finder.TraverseStmt(E))
17527       return true;
17528 
17529   return checkThisInStaticMemberFunctionAttributes(Method);
17530 }
17531 
17532 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17533   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17534   if (!TSInfo)
17535     return false;
17536 
17537   TypeLoc TL = TSInfo->getTypeLoc();
17538   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17539   if (!ProtoTL)
17540     return false;
17541 
17542   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17543   FindCXXThisExpr Finder(*this);
17544 
17545   switch (Proto->getExceptionSpecType()) {
17546   case EST_Unparsed:
17547   case EST_Uninstantiated:
17548   case EST_Unevaluated:
17549   case EST_BasicNoexcept:
17550   case EST_NoThrow:
17551   case EST_DynamicNone:
17552   case EST_MSAny:
17553   case EST_None:
17554     break;
17555 
17556   case EST_DependentNoexcept:
17557   case EST_NoexceptFalse:
17558   case EST_NoexceptTrue:
17559     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17560       return true;
17561     LLVM_FALLTHROUGH;
17562 
17563   case EST_Dynamic:
17564     for (const auto &E : Proto->exceptions()) {
17565       if (!Finder.TraverseType(E))
17566         return true;
17567     }
17568     break;
17569   }
17570 
17571   return false;
17572 }
17573 
17574 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17575   FindCXXThisExpr Finder(*this);
17576 
17577   // Check attributes.
17578   for (const auto *A : Method->attrs()) {
17579     // FIXME: This should be emitted by tblgen.
17580     Expr *Arg = nullptr;
17581     ArrayRef<Expr *> Args;
17582     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17583       Arg = G->getArg();
17584     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17585       Arg = G->getArg();
17586     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17587       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17588     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17589       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17590     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17591       Arg = ETLF->getSuccessValue();
17592       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17593     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17594       Arg = STLF->getSuccessValue();
17595       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17596     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17597       Arg = LR->getArg();
17598     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17599       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17600     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17601       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17602     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17603       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17604     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17605       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17606     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17607       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17608 
17609     if (Arg && !Finder.TraverseStmt(Arg))
17610       return true;
17611 
17612     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17613       if (!Finder.TraverseStmt(Args[I]))
17614         return true;
17615     }
17616   }
17617 
17618   return false;
17619 }
17620 
17621 void Sema::checkExceptionSpecification(
17622     bool IsTopLevel, ExceptionSpecificationType EST,
17623     ArrayRef<ParsedType> DynamicExceptions,
17624     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17625     SmallVectorImpl<QualType> &Exceptions,
17626     FunctionProtoType::ExceptionSpecInfo &ESI) {
17627   Exceptions.clear();
17628   ESI.Type = EST;
17629   if (EST == EST_Dynamic) {
17630     Exceptions.reserve(DynamicExceptions.size());
17631     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17632       // FIXME: Preserve type source info.
17633       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17634 
17635       if (IsTopLevel) {
17636         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17637         collectUnexpandedParameterPacks(ET, Unexpanded);
17638         if (!Unexpanded.empty()) {
17639           DiagnoseUnexpandedParameterPacks(
17640               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17641               Unexpanded);
17642           continue;
17643         }
17644       }
17645 
17646       // Check that the type is valid for an exception spec, and
17647       // drop it if not.
17648       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17649         Exceptions.push_back(ET);
17650     }
17651     ESI.Exceptions = Exceptions;
17652     return;
17653   }
17654 
17655   if (isComputedNoexcept(EST)) {
17656     assert((NoexceptExpr->isTypeDependent() ||
17657             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17658             Context.BoolTy) &&
17659            "Parser should have made sure that the expression is boolean");
17660     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17661       ESI.Type = EST_BasicNoexcept;
17662       return;
17663     }
17664 
17665     ESI.NoexceptExpr = NoexceptExpr;
17666     return;
17667   }
17668 }
17669 
17670 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17671              ExceptionSpecificationType EST,
17672              SourceRange SpecificationRange,
17673              ArrayRef<ParsedType> DynamicExceptions,
17674              ArrayRef<SourceRange> DynamicExceptionRanges,
17675              Expr *NoexceptExpr) {
17676   if (!MethodD)
17677     return;
17678 
17679   // Dig out the method we're referring to.
17680   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17681     MethodD = FunTmpl->getTemplatedDecl();
17682 
17683   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17684   if (!Method)
17685     return;
17686 
17687   // Check the exception specification.
17688   llvm::SmallVector<QualType, 4> Exceptions;
17689   FunctionProtoType::ExceptionSpecInfo ESI;
17690   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17691                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17692                               ESI);
17693 
17694   // Update the exception specification on the function type.
17695   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17696 
17697   if (Method->isStatic())
17698     checkThisInStaticMemberFunctionExceptionSpec(Method);
17699 
17700   if (Method->isVirtual()) {
17701     // Check overrides, which we previously had to delay.
17702     for (const CXXMethodDecl *O : Method->overridden_methods())
17703       CheckOverridingFunctionExceptionSpec(Method, O);
17704   }
17705 }
17706 
17707 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17708 ///
17709 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17710                                        SourceLocation DeclStart, Declarator &D,
17711                                        Expr *BitWidth,
17712                                        InClassInitStyle InitStyle,
17713                                        AccessSpecifier AS,
17714                                        const ParsedAttr &MSPropertyAttr) {
17715   IdentifierInfo *II = D.getIdentifier();
17716   if (!II) {
17717     Diag(DeclStart, diag::err_anonymous_property);
17718     return nullptr;
17719   }
17720   SourceLocation Loc = D.getIdentifierLoc();
17721 
17722   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17723   QualType T = TInfo->getType();
17724   if (getLangOpts().CPlusPlus) {
17725     CheckExtraCXXDefaultArguments(D);
17726 
17727     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17728                                         UPPC_DataMemberType)) {
17729       D.setInvalidType();
17730       T = Context.IntTy;
17731       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17732     }
17733   }
17734 
17735   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17736 
17737   if (D.getDeclSpec().isInlineSpecified())
17738     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17739         << getLangOpts().CPlusPlus17;
17740   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17741     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17742          diag::err_invalid_thread)
17743       << DeclSpec::getSpecifierName(TSCS);
17744 
17745   // Check to see if this name was declared as a member previously
17746   NamedDecl *PrevDecl = nullptr;
17747   LookupResult Previous(*this, II, Loc, LookupMemberName,
17748                         ForVisibleRedeclaration);
17749   LookupName(Previous, S);
17750   switch (Previous.getResultKind()) {
17751   case LookupResult::Found:
17752   case LookupResult::FoundUnresolvedValue:
17753     PrevDecl = Previous.getAsSingle<NamedDecl>();
17754     break;
17755 
17756   case LookupResult::FoundOverloaded:
17757     PrevDecl = Previous.getRepresentativeDecl();
17758     break;
17759 
17760   case LookupResult::NotFound:
17761   case LookupResult::NotFoundInCurrentInstantiation:
17762   case LookupResult::Ambiguous:
17763     break;
17764   }
17765 
17766   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17767     // Maybe we will complain about the shadowed template parameter.
17768     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17769     // Just pretend that we didn't see the previous declaration.
17770     PrevDecl = nullptr;
17771   }
17772 
17773   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17774     PrevDecl = nullptr;
17775 
17776   SourceLocation TSSL = D.getBeginLoc();
17777   MSPropertyDecl *NewPD =
17778       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17779                              MSPropertyAttr.getPropertyDataGetter(),
17780                              MSPropertyAttr.getPropertyDataSetter());
17781   ProcessDeclAttributes(TUScope, NewPD, D);
17782   NewPD->setAccess(AS);
17783 
17784   if (NewPD->isInvalidDecl())
17785     Record->setInvalidDecl();
17786 
17787   if (D.getDeclSpec().isModulePrivateSpecified())
17788     NewPD->setModulePrivate();
17789 
17790   if (NewPD->isInvalidDecl() && PrevDecl) {
17791     // Don't introduce NewFD into scope; there's already something
17792     // with the same name in the same scope.
17793   } else if (II) {
17794     PushOnScopeChains(NewPD, S);
17795   } else
17796     Record->addDecl(NewPD);
17797 
17798   return NewPD;
17799 }
17800 
17801 void Sema::ActOnStartFunctionDeclarationDeclarator(
17802     Declarator &Declarator, unsigned TemplateParameterDepth) {
17803   auto &Info = InventedParameterInfos.emplace_back();
17804   TemplateParameterList *ExplicitParams = nullptr;
17805   ArrayRef<TemplateParameterList *> ExplicitLists =
17806       Declarator.getTemplateParameterLists();
17807   if (!ExplicitLists.empty()) {
17808     bool IsMemberSpecialization, IsInvalid;
17809     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17810         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17811         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17812         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17813         /*SuppressDiagnostic=*/true);
17814   }
17815   if (ExplicitParams) {
17816     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17817     for (NamedDecl *Param : *ExplicitParams)
17818       Info.TemplateParams.push_back(Param);
17819     Info.NumExplicitTemplateParams = ExplicitParams->size();
17820   } else {
17821     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17822     Info.NumExplicitTemplateParams = 0;
17823   }
17824 }
17825 
17826 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17827   auto &FSI = InventedParameterInfos.back();
17828   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17829     if (FSI.NumExplicitTemplateParams != 0) {
17830       TemplateParameterList *ExplicitParams =
17831           Declarator.getTemplateParameterLists().back();
17832       Declarator.setInventedTemplateParameterList(
17833           TemplateParameterList::Create(
17834               Context, ExplicitParams->getTemplateLoc(),
17835               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17836               ExplicitParams->getRAngleLoc(),
17837               ExplicitParams->getRequiresClause()));
17838     } else {
17839       Declarator.setInventedTemplateParameterList(
17840           TemplateParameterList::Create(
17841               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17842               SourceLocation(), /*RequiresClause=*/nullptr));
17843     }
17844   }
17845   InventedParameterInfos.pop_back();
17846 }
17847