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   return Invalid;
698 }
699 
700 NamedDecl *
701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
702                                    MultiTemplateParamsArg TemplateParamLists) {
703   assert(D.isDecompositionDeclarator());
704   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
705 
706   // The syntax only allows a decomposition declarator as a simple-declaration,
707   // a for-range-declaration, or a condition in Clang, but we parse it in more
708   // cases than that.
709   if (!D.mayHaveDecompositionDeclarator()) {
710     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
711       << Decomp.getSourceRange();
712     return nullptr;
713   }
714 
715   if (!TemplateParamLists.empty()) {
716     // FIXME: There's no rule against this, but there are also no rules that
717     // would actually make it usable, so we reject it for now.
718     Diag(TemplateParamLists.front()->getTemplateLoc(),
719          diag::err_decomp_decl_template);
720     return nullptr;
721   }
722 
723   Diag(Decomp.getLSquareLoc(),
724        !getLangOpts().CPlusPlus17
725            ? diag::ext_decomp_decl
726            : D.getContext() == DeclaratorContext::ConditionContext
727                  ? diag::ext_decomp_decl_cond
728                  : diag::warn_cxx14_compat_decomp_decl)
729       << Decomp.getSourceRange();
730 
731   // The semantic context is always just the current context.
732   DeclContext *const DC = CurContext;
733 
734   // C++17 [dcl.dcl]/8:
735   //   The decl-specifier-seq shall contain only the type-specifier auto
736   //   and cv-qualifiers.
737   // C++2a [dcl.dcl]/8:
738   //   If decl-specifier-seq contains any decl-specifier other than static,
739   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
740   auto &DS = D.getDeclSpec();
741   {
742     SmallVector<StringRef, 8> BadSpecifiers;
743     SmallVector<SourceLocation, 8> BadSpecifierLocs;
744     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
745     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
746     if (auto SCS = DS.getStorageClassSpec()) {
747       if (SCS == DeclSpec::SCS_static) {
748         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
749         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
750       } else {
751         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
752         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
753       }
754     }
755     if (auto TSCS = DS.getThreadStorageClassSpec()) {
756       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
757       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
758     }
759     if (DS.hasConstexprSpecifier()) {
760       BadSpecifiers.push_back(
761           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
762       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
763     }
764     if (DS.isInlineSpecified()) {
765       BadSpecifiers.push_back("inline");
766       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
767     }
768     if (!BadSpecifiers.empty()) {
769       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
770       Err << (int)BadSpecifiers.size()
771           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
772       // Don't add FixItHints to remove the specifiers; we do still respect
773       // them when building the underlying variable.
774       for (auto Loc : BadSpecifierLocs)
775         Err << SourceRange(Loc, Loc);
776     } else if (!CPlusPlus20Specifiers.empty()) {
777       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
778                          getLangOpts().CPlusPlus20
779                              ? diag::warn_cxx17_compat_decomp_decl_spec
780                              : diag::ext_decomp_decl_spec);
781       Warn << (int)CPlusPlus20Specifiers.size()
782            << llvm::join(CPlusPlus20Specifiers.begin(),
783                          CPlusPlus20Specifiers.end(), " ");
784       for (auto Loc : CPlusPlus20SpecifierLocs)
785         Warn << SourceRange(Loc, Loc);
786     }
787     // We can't recover from it being declared as a typedef.
788     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
789       return nullptr;
790   }
791 
792   // C++2a [dcl.struct.bind]p1:
793   //   A cv that includes volatile is deprecated
794   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
795       getLangOpts().CPlusPlus20)
796     Diag(DS.getVolatileSpecLoc(),
797          diag::warn_deprecated_volatile_structured_binding);
798 
799   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
800   QualType R = TInfo->getType();
801 
802   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
803                                       UPPC_DeclarationType))
804     D.setInvalidType();
805 
806   // The syntax only allows a single ref-qualifier prior to the decomposition
807   // declarator. No other declarator chunks are permitted. Also check the type
808   // specifier here.
809   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
810       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
811       (D.getNumTypeObjects() == 1 &&
812        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
813     Diag(Decomp.getLSquareLoc(),
814          (D.hasGroupingParens() ||
815           (D.getNumTypeObjects() &&
816            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
817              ? diag::err_decomp_decl_parens
818              : diag::err_decomp_decl_type)
819         << R;
820 
821     // In most cases, there's no actual problem with an explicitly-specified
822     // type, but a function type won't work here, and ActOnVariableDeclarator
823     // shouldn't be called for such a type.
824     if (R->isFunctionType())
825       D.setInvalidType();
826   }
827 
828   // Build the BindingDecls.
829   SmallVector<BindingDecl*, 8> Bindings;
830 
831   // Build the BindingDecls.
832   for (auto &B : D.getDecompositionDeclarator().bindings()) {
833     // Check for name conflicts.
834     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
835     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
836                           ForVisibleRedeclaration);
837     LookupName(Previous, S,
838                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
839 
840     // It's not permitted to shadow a template parameter name.
841     if (Previous.isSingleResult() &&
842         Previous.getFoundDecl()->isTemplateParameter()) {
843       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
844                                       Previous.getFoundDecl());
845       Previous.clear();
846     }
847 
848     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
849                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
850     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
851                          /*AllowInlineNamespace*/false);
852     if (!Previous.empty()) {
853       auto *Old = Previous.getRepresentativeDecl();
854       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
855       Diag(Old->getLocation(), diag::note_previous_definition);
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859     PushOnScopeChains(BD, S, true);
860     Bindings.push_back(BD);
861     ParsingInitForAutoVars.insert(BD);
862   }
863 
864   // There are no prior lookup results for the variable itself, because it
865   // is unnamed.
866   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
867                                Decomp.getLSquareLoc());
868   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
869                         ForVisibleRedeclaration);
870 
871   // Build the variable that holds the non-decomposed object.
872   bool AddToScope = true;
873   NamedDecl *New =
874       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
875                               MultiTemplateParamsArg(), AddToScope, Bindings);
876   if (AddToScope) {
877     S->AddDecl(New);
878     CurContext->addHiddenDecl(New);
879   }
880 
881   if (isInOpenMPDeclareTargetContext())
882     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
883 
884   return New;
885 }
886 
887 static bool checkSimpleDecomposition(
888     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
889     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
890     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
891   if ((int64_t)Bindings.size() != NumElems) {
892     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
893         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
894         << (NumElems < Bindings.size());
895     return true;
896   }
897 
898   unsigned I = 0;
899   for (auto *B : Bindings) {
900     SourceLocation Loc = B->getLocation();
901     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
902     if (E.isInvalid())
903       return true;
904     E = GetInit(Loc, E.get(), I++);
905     if (E.isInvalid())
906       return true;
907     B->setBinding(ElemType, E.get());
908   }
909 
910   return false;
911 }
912 
913 static bool checkArrayLikeDecomposition(Sema &S,
914                                         ArrayRef<BindingDecl *> Bindings,
915                                         ValueDecl *Src, QualType DecompType,
916                                         const llvm::APSInt &NumElems,
917                                         QualType ElemType) {
918   return checkSimpleDecomposition(
919       S, Bindings, Src, DecompType, NumElems, ElemType,
920       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
921         ExprResult E = S.ActOnIntegerConstant(Loc, I);
922         if (E.isInvalid())
923           return ExprError();
924         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
925       });
926 }
927 
928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
929                                     ValueDecl *Src, QualType DecompType,
930                                     const ConstantArrayType *CAT) {
931   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
932                                      llvm::APSInt(CAT->getSize()),
933                                      CAT->getElementType());
934 }
935 
936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
937                                      ValueDecl *Src, QualType DecompType,
938                                      const VectorType *VT) {
939   return checkArrayLikeDecomposition(
940       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
941       S.Context.getQualifiedType(VT->getElementType(),
942                                  DecompType.getQualifiers()));
943 }
944 
945 static bool checkComplexDecomposition(Sema &S,
946                                       ArrayRef<BindingDecl *> Bindings,
947                                       ValueDecl *Src, QualType DecompType,
948                                       const ComplexType *CT) {
949   return checkSimpleDecomposition(
950       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
951       S.Context.getQualifiedType(CT->getElementType(),
952                                  DecompType.getQualifiers()),
953       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
954         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
955       });
956 }
957 
958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
959                                      TemplateArgumentListInfo &Args) {
960   SmallString<128> SS;
961   llvm::raw_svector_ostream OS(SS);
962   bool First = true;
963   for (auto &Arg : Args.arguments()) {
964     if (!First)
965       OS << ", ";
966     Arg.getArgument().print(PrintingPolicy, OS);
967     First = false;
968   }
969   return std::string(OS.str());
970 }
971 
972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
973                                      SourceLocation Loc, StringRef Trait,
974                                      TemplateArgumentListInfo &Args,
975                                      unsigned DiagID) {
976   auto DiagnoseMissing = [&] {
977     if (DiagID)
978       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
979                                                Args);
980     return true;
981   };
982 
983   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
984   NamespaceDecl *Std = S.getStdNamespace();
985   if (!Std)
986     return DiagnoseMissing();
987 
988   // Look up the trait itself, within namespace std. We can diagnose various
989   // problems with this lookup even if we've been asked to not diagnose a
990   // missing specialization, because this can only fail if the user has been
991   // declaring their own names in namespace std or we don't support the
992   // standard library implementation in use.
993   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
994                       Loc, Sema::LookupOrdinaryName);
995   if (!S.LookupQualifiedName(Result, Std))
996     return DiagnoseMissing();
997   if (Result.isAmbiguous())
998     return true;
999 
1000   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1001   if (!TraitTD) {
1002     Result.suppressDiagnostics();
1003     NamedDecl *Found = *Result.begin();
1004     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1005     S.Diag(Found->getLocation(), diag::note_declared_at);
1006     return true;
1007   }
1008 
1009   // Build the template-id.
1010   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1011   if (TraitTy.isNull())
1012     return true;
1013   if (!S.isCompleteType(Loc, TraitTy)) {
1014     if (DiagID)
1015       S.RequireCompleteType(
1016           Loc, TraitTy, DiagID,
1017           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1018     return true;
1019   }
1020 
1021   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1022   assert(RD && "specialization of class template is not a class?");
1023 
1024   // Look up the member of the trait type.
1025   S.LookupQualifiedName(TraitMemberLookup, RD);
1026   return TraitMemberLookup.isAmbiguous();
1027 }
1028 
1029 static TemplateArgumentLoc
1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1031                                    uint64_t I) {
1032   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1033   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1034 }
1035 
1036 static TemplateArgumentLoc
1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1038   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1039 }
1040 
1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1042 
1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1044                                llvm::APSInt &Size) {
1045   EnterExpressionEvaluationContext ContextRAII(
1046       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1047 
1048   DeclarationName Value = S.PP.getIdentifierInfo("value");
1049   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1050 
1051   // Form template argument list for tuple_size<T>.
1052   TemplateArgumentListInfo Args(Loc, Loc);
1053   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1054 
1055   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1056   // it's not tuple-like.
1057   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1058       R.empty())
1059     return IsTupleLike::NotTupleLike;
1060 
1061   // If we get this far, we've committed to the tuple interpretation, but
1062   // we can still fail if there actually isn't a usable ::value.
1063 
1064   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1065     LookupResult &R;
1066     TemplateArgumentListInfo &Args;
1067     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1068         : R(R), Args(Args) {}
1069     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1070       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1071           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1072     }
1073   } Diagnoser(R, Args);
1074 
1075   ExprResult E =
1076       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1077   if (E.isInvalid())
1078     return IsTupleLike::Error;
1079 
1080   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1081   if (E.isInvalid())
1082     return IsTupleLike::Error;
1083 
1084   return IsTupleLike::TupleLike;
1085 }
1086 
1087 /// \return std::tuple_element<I, T>::type.
1088 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1089                                         unsigned I, QualType T) {
1090   // Form template argument list for tuple_element<I, T>.
1091   TemplateArgumentListInfo Args(Loc, Loc);
1092   Args.addArgument(
1093       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1094   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1095 
1096   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1097   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1098   if (lookupStdTypeTraitMember(
1099           S, R, Loc, "tuple_element", Args,
1100           diag::err_decomp_decl_std_tuple_element_not_specialized))
1101     return QualType();
1102 
1103   auto *TD = R.getAsSingle<TypeDecl>();
1104   if (!TD) {
1105     R.suppressDiagnostics();
1106     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1107       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1108     if (!R.empty())
1109       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1110     return QualType();
1111   }
1112 
1113   return S.Context.getTypeDeclType(TD);
1114 }
1115 
1116 namespace {
1117 struct InitializingBinding {
1118   Sema &S;
1119   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1120     Sema::CodeSynthesisContext Ctx;
1121     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1122     Ctx.PointOfInstantiation = BD->getLocation();
1123     Ctx.Entity = BD;
1124     S.pushCodeSynthesisContext(Ctx);
1125   }
1126   ~InitializingBinding() {
1127     S.popCodeSynthesisContext();
1128   }
1129 };
1130 }
1131 
1132 static bool checkTupleLikeDecomposition(Sema &S,
1133                                         ArrayRef<BindingDecl *> Bindings,
1134                                         VarDecl *Src, QualType DecompType,
1135                                         const llvm::APSInt &TupleSize) {
1136   if ((int64_t)Bindings.size() != TupleSize) {
1137     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1138         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1139         << (TupleSize < Bindings.size());
1140     return true;
1141   }
1142 
1143   if (Bindings.empty())
1144     return false;
1145 
1146   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1147 
1148   // [dcl.decomp]p3:
1149   //   The unqualified-id get is looked up in the scope of E by class member
1150   //   access lookup ...
1151   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1152   bool UseMemberGet = false;
1153   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1154     if (auto *RD = DecompType->getAsCXXRecordDecl())
1155       S.LookupQualifiedName(MemberGet, RD);
1156     if (MemberGet.isAmbiguous())
1157       return true;
1158     //   ... and if that finds at least one declaration that is a function
1159     //   template whose first template parameter is a non-type parameter ...
1160     for (NamedDecl *D : MemberGet) {
1161       if (FunctionTemplateDecl *FTD =
1162               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1163         TemplateParameterList *TPL = FTD->getTemplateParameters();
1164         if (TPL->size() != 0 &&
1165             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1166           //   ... the initializer is e.get<i>().
1167           UseMemberGet = true;
1168           break;
1169         }
1170       }
1171     }
1172   }
1173 
1174   unsigned I = 0;
1175   for (auto *B : Bindings) {
1176     InitializingBinding InitContext(S, B);
1177     SourceLocation Loc = B->getLocation();
1178 
1179     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1180     if (E.isInvalid())
1181       return true;
1182 
1183     //   e is an lvalue if the type of the entity is an lvalue reference and
1184     //   an xvalue otherwise
1185     if (!Src->getType()->isLValueReferenceType())
1186       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1187                                    E.get(), nullptr, VK_XValue);
1188 
1189     TemplateArgumentListInfo Args(Loc, Loc);
1190     Args.addArgument(
1191         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1192 
1193     if (UseMemberGet) {
1194       //   if [lookup of member get] finds at least one declaration, the
1195       //   initializer is e.get<i-1>().
1196       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1197                                      CXXScopeSpec(), SourceLocation(), nullptr,
1198                                      MemberGet, &Args, nullptr);
1199       if (E.isInvalid())
1200         return true;
1201 
1202       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1203     } else {
1204       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1205       //   in the associated namespaces.
1206       Expr *Get = UnresolvedLookupExpr::Create(
1207           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1208           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1209           UnresolvedSetIterator(), UnresolvedSetIterator());
1210 
1211       Expr *Arg = E.get();
1212       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1213     }
1214     if (E.isInvalid())
1215       return true;
1216     Expr *Init = E.get();
1217 
1218     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1219     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1220     if (T.isNull())
1221       return true;
1222 
1223     //   each vi is a variable of type "reference to T" initialized with the
1224     //   initializer, where the reference is an lvalue reference if the
1225     //   initializer is an lvalue and an rvalue reference otherwise
1226     QualType RefType =
1227         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1228     if (RefType.isNull())
1229       return true;
1230     auto *RefVD = VarDecl::Create(
1231         S.Context, Src->getDeclContext(), Loc, Loc,
1232         B->getDeclName().getAsIdentifierInfo(), RefType,
1233         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1234     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1235     RefVD->setTSCSpec(Src->getTSCSpec());
1236     RefVD->setImplicit();
1237     if (Src->isInlineSpecified())
1238       RefVD->setInlineSpecified();
1239     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1240 
1241     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1242     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1243     InitializationSequence Seq(S, Entity, Kind, Init);
1244     E = Seq.Perform(S, Entity, Kind, Init);
1245     if (E.isInvalid())
1246       return true;
1247     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1248     if (E.isInvalid())
1249       return true;
1250     RefVD->setInit(E.get());
1251     if (!E.get()->isValueDependent())
1252       RefVD->checkInitIsICE();
1253 
1254     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1255                                    DeclarationNameInfo(B->getDeclName(), Loc),
1256                                    RefVD);
1257     if (E.isInvalid())
1258       return true;
1259 
1260     B->setBinding(T, E.get());
1261     I++;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 /// Find the base class to decompose in a built-in decomposition of a class type.
1268 /// This base class search is, unfortunately, not quite like any other that we
1269 /// perform anywhere else in C++.
1270 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1271                                                 const CXXRecordDecl *RD,
1272                                                 CXXCastPath &BasePath) {
1273   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1274                           CXXBasePath &Path) {
1275     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1276   };
1277 
1278   const CXXRecordDecl *ClassWithFields = nullptr;
1279   AccessSpecifier AS = AS_public;
1280   if (RD->hasDirectFields())
1281     // [dcl.decomp]p4:
1282     //   Otherwise, all of E's non-static data members shall be public direct
1283     //   members of E ...
1284     ClassWithFields = RD;
1285   else {
1286     //   ... or of ...
1287     CXXBasePaths Paths;
1288     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1289     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1290       // If no classes have fields, just decompose RD itself. (This will work
1291       // if and only if zero bindings were provided.)
1292       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1293     }
1294 
1295     CXXBasePath *BestPath = nullptr;
1296     for (auto &P : Paths) {
1297       if (!BestPath)
1298         BestPath = &P;
1299       else if (!S.Context.hasSameType(P.back().Base->getType(),
1300                                       BestPath->back().Base->getType())) {
1301         //   ... the same ...
1302         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1303           << false << RD << BestPath->back().Base->getType()
1304           << P.back().Base->getType();
1305         return DeclAccessPair();
1306       } else if (P.Access < BestPath->Access) {
1307         BestPath = &P;
1308       }
1309     }
1310 
1311     //   ... unambiguous ...
1312     QualType BaseType = BestPath->back().Base->getType();
1313     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1314       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1315         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1316       return DeclAccessPair();
1317     }
1318 
1319     //   ... [accessible, implied by other rules] base class of E.
1320     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1321                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1322     AS = BestPath->Access;
1323 
1324     ClassWithFields = BaseType->getAsCXXRecordDecl();
1325     S.BuildBasePathArray(Paths, BasePath);
1326   }
1327 
1328   // The above search did not check whether the selected class itself has base
1329   // classes with fields, so check that now.
1330   CXXBasePaths Paths;
1331   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1332     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1333       << (ClassWithFields == RD) << RD << ClassWithFields
1334       << Paths.front().back().Base->getType();
1335     return DeclAccessPair();
1336   }
1337 
1338   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1339 }
1340 
1341 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1342                                      ValueDecl *Src, QualType DecompType,
1343                                      const CXXRecordDecl *OrigRD) {
1344   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1345                             diag::err_incomplete_type))
1346     return true;
1347 
1348   CXXCastPath BasePath;
1349   DeclAccessPair BasePair =
1350       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1351   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1352   if (!RD)
1353     return true;
1354   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1355                                                  DecompType.getQualifiers());
1356 
1357   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1358     unsigned NumFields =
1359         std::count_if(RD->field_begin(), RD->field_end(),
1360                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1361     assert(Bindings.size() != NumFields);
1362     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1363         << DecompType << (unsigned)Bindings.size() << NumFields
1364         << (NumFields < Bindings.size());
1365     return true;
1366   };
1367 
1368   //   all of E's non-static data members shall be [...] well-formed
1369   //   when named as e.name in the context of the structured binding,
1370   //   E shall not have an anonymous union member, ...
1371   unsigned I = 0;
1372   for (auto *FD : RD->fields()) {
1373     if (FD->isUnnamedBitfield())
1374       continue;
1375 
1376     if (FD->isAnonymousStructOrUnion()) {
1377       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1378         << DecompType << FD->getType()->isUnionType();
1379       S.Diag(FD->getLocation(), diag::note_declared_at);
1380       return true;
1381     }
1382 
1383     // We have a real field to bind.
1384     if (I >= Bindings.size())
1385       return DiagnoseBadNumberOfBindings();
1386     auto *B = Bindings[I++];
1387     SourceLocation Loc = B->getLocation();
1388 
1389     // The field must be accessible in the context of the structured binding.
1390     // We already checked that the base class is accessible.
1391     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1392     // const_cast here.
1393     S.CheckStructuredBindingMemberAccess(
1394         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1395         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1396                                      BasePair.getAccess(), FD->getAccess())));
1397 
1398     // Initialize the binding to Src.FD.
1399     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1400     if (E.isInvalid())
1401       return true;
1402     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1403                             VK_LValue, &BasePath);
1404     if (E.isInvalid())
1405       return true;
1406     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1407                                   CXXScopeSpec(), FD,
1408                                   DeclAccessPair::make(FD, FD->getAccess()),
1409                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1410     if (E.isInvalid())
1411       return true;
1412 
1413     // If the type of the member is T, the referenced type is cv T, where cv is
1414     // the cv-qualification of the decomposition expression.
1415     //
1416     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1417     // 'const' to the type of the field.
1418     Qualifiers Q = DecompType.getQualifiers();
1419     if (FD->isMutable())
1420       Q.removeConst();
1421     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1422   }
1423 
1424   if (I != Bindings.size())
1425     return DiagnoseBadNumberOfBindings();
1426 
1427   return false;
1428 }
1429 
1430 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1431   QualType DecompType = DD->getType();
1432 
1433   // If the type of the decomposition is dependent, then so is the type of
1434   // each binding.
1435   if (DecompType->isDependentType()) {
1436     for (auto *B : DD->bindings())
1437       B->setType(Context.DependentTy);
1438     return;
1439   }
1440 
1441   DecompType = DecompType.getNonReferenceType();
1442   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1443 
1444   // C++1z [dcl.decomp]/2:
1445   //   If E is an array type [...]
1446   // As an extension, we also support decomposition of built-in complex and
1447   // vector types.
1448   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1449     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1450       DD->setInvalidDecl();
1451     return;
1452   }
1453   if (auto *VT = DecompType->getAs<VectorType>()) {
1454     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1455       DD->setInvalidDecl();
1456     return;
1457   }
1458   if (auto *CT = DecompType->getAs<ComplexType>()) {
1459     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1460       DD->setInvalidDecl();
1461     return;
1462   }
1463 
1464   // C++1z [dcl.decomp]/3:
1465   //   if the expression std::tuple_size<E>::value is a well-formed integral
1466   //   constant expression, [...]
1467   llvm::APSInt TupleSize(32);
1468   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1469   case IsTupleLike::Error:
1470     DD->setInvalidDecl();
1471     return;
1472 
1473   case IsTupleLike::TupleLike:
1474     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1475       DD->setInvalidDecl();
1476     return;
1477 
1478   case IsTupleLike::NotTupleLike:
1479     break;
1480   }
1481 
1482   // C++1z [dcl.dcl]/8:
1483   //   [E shall be of array or non-union class type]
1484   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1485   if (!RD || RD->isUnion()) {
1486     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1487         << DD << !RD << DecompType;
1488     DD->setInvalidDecl();
1489     return;
1490   }
1491 
1492   // C++1z [dcl.decomp]/4:
1493   //   all of E's non-static data members shall be [...] direct members of
1494   //   E or of the same unambiguous public base class of E, ...
1495   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1496     DD->setInvalidDecl();
1497 }
1498 
1499 /// Merge the exception specifications of two variable declarations.
1500 ///
1501 /// This is called when there's a redeclaration of a VarDecl. The function
1502 /// checks if the redeclaration might have an exception specification and
1503 /// validates compatibility and merges the specs if necessary.
1504 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1505   // Shortcut if exceptions are disabled.
1506   if (!getLangOpts().CXXExceptions)
1507     return;
1508 
1509   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1510          "Should only be called if types are otherwise the same.");
1511 
1512   QualType NewType = New->getType();
1513   QualType OldType = Old->getType();
1514 
1515   // We're only interested in pointers and references to functions, as well
1516   // as pointers to member functions.
1517   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1518     NewType = R->getPointeeType();
1519     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1520   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1521     NewType = P->getPointeeType();
1522     OldType = OldType->castAs<PointerType>()->getPointeeType();
1523   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1524     NewType = M->getPointeeType();
1525     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1526   }
1527 
1528   if (!NewType->isFunctionProtoType())
1529     return;
1530 
1531   // There's lots of special cases for functions. For function pointers, system
1532   // libraries are hopefully not as broken so that we don't need these
1533   // workarounds.
1534   if (CheckEquivalentExceptionSpec(
1535         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1536         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1537     New->setInvalidDecl();
1538   }
1539 }
1540 
1541 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1542 /// function declaration are well-formed according to C++
1543 /// [dcl.fct.default].
1544 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1545   unsigned NumParams = FD->getNumParams();
1546   unsigned ParamIdx = 0;
1547 
1548   // This checking doesn't make sense for explicit specializations; their
1549   // default arguments are determined by the declaration we're specializing,
1550   // not by FD.
1551   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1552     return;
1553   if (auto *FTD = FD->getDescribedFunctionTemplate())
1554     if (FTD->isMemberSpecialization())
1555       return;
1556 
1557   // Find first parameter with a default argument
1558   for (; ParamIdx < NumParams; ++ParamIdx) {
1559     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1560     if (Param->hasDefaultArg())
1561       break;
1562   }
1563 
1564   // C++20 [dcl.fct.default]p4:
1565   //   In a given function declaration, each parameter subsequent to a parameter
1566   //   with a default argument shall have a default argument supplied in this or
1567   //   a previous declaration, unless the parameter was expanded from a
1568   //   parameter pack, or shall be a function parameter pack.
1569   for (; ParamIdx < NumParams; ++ParamIdx) {
1570     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1571     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1572         !(CurrentInstantiationScope &&
1573           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1574       if (Param->isInvalidDecl())
1575         /* We already complained about this parameter. */;
1576       else if (Param->getIdentifier())
1577         Diag(Param->getLocation(),
1578              diag::err_param_default_argument_missing_name)
1579           << Param->getIdentifier();
1580       else
1581         Diag(Param->getLocation(),
1582              diag::err_param_default_argument_missing);
1583     }
1584   }
1585 }
1586 
1587 /// Check that the given type is a literal type. Issue a diagnostic if not,
1588 /// if Kind is Diagnose.
1589 /// \return \c true if a problem has been found (and optionally diagnosed).
1590 template <typename... Ts>
1591 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1592                              SourceLocation Loc, QualType T, unsigned DiagID,
1593                              Ts &&...DiagArgs) {
1594   if (T->isDependentType())
1595     return false;
1596 
1597   switch (Kind) {
1598   case Sema::CheckConstexprKind::Diagnose:
1599     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1600                                       std::forward<Ts>(DiagArgs)...);
1601 
1602   case Sema::CheckConstexprKind::CheckValid:
1603     return !T->isLiteralType(SemaRef.Context);
1604   }
1605 
1606   llvm_unreachable("unknown CheckConstexprKind");
1607 }
1608 
1609 /// Determine whether a destructor cannot be constexpr due to
1610 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1611                                                const CXXDestructorDecl *DD,
1612                                                Sema::CheckConstexprKind Kind) {
1613   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1614     const CXXRecordDecl *RD =
1615         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1616     if (!RD || RD->hasConstexprDestructor())
1617       return true;
1618 
1619     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1620       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1621           << DD->getConstexprKind() << !FD
1622           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1623       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1624           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1625     }
1626     return false;
1627   };
1628 
1629   const CXXRecordDecl *RD = DD->getParent();
1630   for (const CXXBaseSpecifier &B : RD->bases())
1631     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1632       return false;
1633   for (const FieldDecl *FD : RD->fields())
1634     if (!Check(FD->getLocation(), FD->getType(), FD))
1635       return false;
1636   return true;
1637 }
1638 
1639 /// Check whether a function's parameter types are all literal types. If so,
1640 /// return true. If not, produce a suitable diagnostic and return false.
1641 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1642                                          const FunctionDecl *FD,
1643                                          Sema::CheckConstexprKind Kind) {
1644   unsigned ArgIndex = 0;
1645   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1646   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1647                                               e = FT->param_type_end();
1648        i != e; ++i, ++ArgIndex) {
1649     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1650     SourceLocation ParamLoc = PD->getLocation();
1651     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1652                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1653                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1654                          FD->isConsteval()))
1655       return false;
1656   }
1657   return true;
1658 }
1659 
1660 /// Check whether a function's return type is a literal type. If so, return
1661 /// true. If not, produce a suitable diagnostic and return false.
1662 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1663                                      Sema::CheckConstexprKind Kind) {
1664   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1665                        diag::err_constexpr_non_literal_return,
1666                        FD->isConsteval()))
1667     return false;
1668   return true;
1669 }
1670 
1671 /// Get diagnostic %select index for tag kind for
1672 /// record diagnostic message.
1673 /// WARNING: Indexes apply to particular diagnostics only!
1674 ///
1675 /// \returns diagnostic %select index.
1676 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1677   switch (Tag) {
1678   case TTK_Struct: return 0;
1679   case TTK_Interface: return 1;
1680   case TTK_Class:  return 2;
1681   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1682   }
1683 }
1684 
1685 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1686                                        Stmt *Body,
1687                                        Sema::CheckConstexprKind Kind);
1688 
1689 // Check whether a function declaration satisfies the requirements of a
1690 // constexpr function definition or a constexpr constructor definition. If so,
1691 // return true. If not, produce appropriate diagnostics (unless asked not to by
1692 // Kind) and return false.
1693 //
1694 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1695 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1696                                             CheckConstexprKind Kind) {
1697   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1698   if (MD && MD->isInstance()) {
1699     // C++11 [dcl.constexpr]p4:
1700     //  The definition of a constexpr constructor shall satisfy the following
1701     //  constraints:
1702     //  - the class shall not have any virtual base classes;
1703     //
1704     // FIXME: This only applies to constructors and destructors, not arbitrary
1705     // member functions.
1706     const CXXRecordDecl *RD = MD->getParent();
1707     if (RD->getNumVBases()) {
1708       if (Kind == CheckConstexprKind::CheckValid)
1709         return false;
1710 
1711       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1712         << isa<CXXConstructorDecl>(NewFD)
1713         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1714       for (const auto &I : RD->vbases())
1715         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1716             << I.getSourceRange();
1717       return false;
1718     }
1719   }
1720 
1721   if (!isa<CXXConstructorDecl>(NewFD)) {
1722     // C++11 [dcl.constexpr]p3:
1723     //  The definition of a constexpr function shall satisfy the following
1724     //  constraints:
1725     // - it shall not be virtual; (removed in C++20)
1726     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1727     if (Method && Method->isVirtual()) {
1728       if (getLangOpts().CPlusPlus20) {
1729         if (Kind == CheckConstexprKind::Diagnose)
1730           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1731       } else {
1732         if (Kind == CheckConstexprKind::CheckValid)
1733           return false;
1734 
1735         Method = Method->getCanonicalDecl();
1736         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1737 
1738         // If it's not obvious why this function is virtual, find an overridden
1739         // function which uses the 'virtual' keyword.
1740         const CXXMethodDecl *WrittenVirtual = Method;
1741         while (!WrittenVirtual->isVirtualAsWritten())
1742           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1743         if (WrittenVirtual != Method)
1744           Diag(WrittenVirtual->getLocation(),
1745                diag::note_overridden_virtual_function);
1746         return false;
1747       }
1748     }
1749 
1750     // - its return type shall be a literal type;
1751     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1752       return false;
1753   }
1754 
1755   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1756     // A destructor can be constexpr only if the defaulted destructor could be;
1757     // we don't need to check the members and bases if we already know they all
1758     // have constexpr destructors.
1759     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1760       if (Kind == CheckConstexprKind::CheckValid)
1761         return false;
1762       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1763         return false;
1764     }
1765   }
1766 
1767   // - each of its parameter types shall be a literal type;
1768   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1769     return false;
1770 
1771   Stmt *Body = NewFD->getBody();
1772   assert(Body &&
1773          "CheckConstexprFunctionDefinition called on function with no body");
1774   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1775 }
1776 
1777 /// Check the given declaration statement is legal within a constexpr function
1778 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1779 ///
1780 /// \return true if the body is OK (maybe only as an extension), false if we
1781 ///         have diagnosed a problem.
1782 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1783                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1784                                    Sema::CheckConstexprKind Kind) {
1785   // C++11 [dcl.constexpr]p3 and p4:
1786   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1787   //  contain only
1788   for (const auto *DclIt : DS->decls()) {
1789     switch (DclIt->getKind()) {
1790     case Decl::StaticAssert:
1791     case Decl::Using:
1792     case Decl::UsingShadow:
1793     case Decl::UsingDirective:
1794     case Decl::UnresolvedUsingTypename:
1795     case Decl::UnresolvedUsingValue:
1796       //   - static_assert-declarations
1797       //   - using-declarations,
1798       //   - using-directives,
1799       continue;
1800 
1801     case Decl::Typedef:
1802     case Decl::TypeAlias: {
1803       //   - typedef declarations and alias-declarations that do not define
1804       //     classes or enumerations,
1805       const auto *TN = cast<TypedefNameDecl>(DclIt);
1806       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1807         // Don't allow variably-modified types in constexpr functions.
1808         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1809           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1810           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1811             << TL.getSourceRange() << TL.getType()
1812             << isa<CXXConstructorDecl>(Dcl);
1813         }
1814         return false;
1815       }
1816       continue;
1817     }
1818 
1819     case Decl::Enum:
1820     case Decl::CXXRecord:
1821       // C++1y allows types to be defined, not just declared.
1822       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1823         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1824           SemaRef.Diag(DS->getBeginLoc(),
1825                        SemaRef.getLangOpts().CPlusPlus14
1826                            ? diag::warn_cxx11_compat_constexpr_type_definition
1827                            : diag::ext_constexpr_type_definition)
1828               << isa<CXXConstructorDecl>(Dcl);
1829         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1830           return false;
1831         }
1832       }
1833       continue;
1834 
1835     case Decl::EnumConstant:
1836     case Decl::IndirectField:
1837     case Decl::ParmVar:
1838       // These can only appear with other declarations which are banned in
1839       // C++11 and permitted in C++1y, so ignore them.
1840       continue;
1841 
1842     case Decl::Var:
1843     case Decl::Decomposition: {
1844       // C++1y [dcl.constexpr]p3 allows anything except:
1845       //   a definition of a variable of non-literal type or of static or
1846       //   thread storage duration or [before C++2a] for which no
1847       //   initialization is performed.
1848       const auto *VD = cast<VarDecl>(DclIt);
1849       if (VD->isThisDeclarationADefinition()) {
1850         if (VD->isStaticLocal()) {
1851           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1852             SemaRef.Diag(VD->getLocation(),
1853                          diag::err_constexpr_local_var_static)
1854               << isa<CXXConstructorDecl>(Dcl)
1855               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1856           }
1857           return false;
1858         }
1859         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1860                              diag::err_constexpr_local_var_non_literal_type,
1861                              isa<CXXConstructorDecl>(Dcl)))
1862           return false;
1863         if (!VD->getType()->isDependentType() &&
1864             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1865           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866             SemaRef.Diag(
1867                 VD->getLocation(),
1868                 SemaRef.getLangOpts().CPlusPlus20
1869                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1870                     : diag::ext_constexpr_local_var_no_init)
1871                 << isa<CXXConstructorDecl>(Dcl);
1872           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1873             return false;
1874           }
1875           continue;
1876         }
1877       }
1878       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879         SemaRef.Diag(VD->getLocation(),
1880                      SemaRef.getLangOpts().CPlusPlus14
1881                       ? diag::warn_cxx11_compat_constexpr_local_var
1882                       : diag::ext_constexpr_local_var)
1883           << isa<CXXConstructorDecl>(Dcl);
1884       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1885         return false;
1886       }
1887       continue;
1888     }
1889 
1890     case Decl::NamespaceAlias:
1891     case Decl::Function:
1892       // These are disallowed in C++11 and permitted in C++1y. Allow them
1893       // everywhere as an extension.
1894       if (!Cxx1yLoc.isValid())
1895         Cxx1yLoc = DS->getBeginLoc();
1896       continue;
1897 
1898     default:
1899       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1901             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1902       }
1903       return false;
1904     }
1905   }
1906 
1907   return true;
1908 }
1909 
1910 /// Check that the given field is initialized within a constexpr constructor.
1911 ///
1912 /// \param Dcl The constexpr constructor being checked.
1913 /// \param Field The field being checked. This may be a member of an anonymous
1914 ///        struct or union nested within the class being checked.
1915 /// \param Inits All declarations, including anonymous struct/union members and
1916 ///        indirect members, for which any initialization was provided.
1917 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1918 ///        multiple notes for different members to the same error.
1919 /// \param Kind Whether we're diagnosing a constructor as written or determining
1920 ///        whether the formal requirements are satisfied.
1921 /// \return \c false if we're checking for validity and the constructor does
1922 ///         not satisfy the requirements on a constexpr constructor.
1923 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1924                                           const FunctionDecl *Dcl,
1925                                           FieldDecl *Field,
1926                                           llvm::SmallSet<Decl*, 16> &Inits,
1927                                           bool &Diagnosed,
1928                                           Sema::CheckConstexprKind Kind) {
1929   // In C++20 onwards, there's nothing to check for validity.
1930   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1931       SemaRef.getLangOpts().CPlusPlus20)
1932     return true;
1933 
1934   if (Field->isInvalidDecl())
1935     return true;
1936 
1937   if (Field->isUnnamedBitfield())
1938     return true;
1939 
1940   // Anonymous unions with no variant members and empty anonymous structs do not
1941   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1942   // indirect fields don't need initializing.
1943   if (Field->isAnonymousStructOrUnion() &&
1944       (Field->getType()->isUnionType()
1945            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1946            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1947     return true;
1948 
1949   if (!Inits.count(Field)) {
1950     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1951       if (!Diagnosed) {
1952         SemaRef.Diag(Dcl->getLocation(),
1953                      SemaRef.getLangOpts().CPlusPlus20
1954                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1955                          : diag::ext_constexpr_ctor_missing_init);
1956         Diagnosed = true;
1957       }
1958       SemaRef.Diag(Field->getLocation(),
1959                    diag::note_constexpr_ctor_missing_init);
1960     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1961       return false;
1962     }
1963   } else if (Field->isAnonymousStructOrUnion()) {
1964     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1965     for (auto *I : RD->fields())
1966       // If an anonymous union contains an anonymous struct of which any member
1967       // is initialized, all members must be initialized.
1968       if (!RD->isUnion() || Inits.count(I))
1969         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1970                                            Kind))
1971           return false;
1972   }
1973   return true;
1974 }
1975 
1976 /// Check the provided statement is allowed in a constexpr function
1977 /// definition.
1978 static bool
1979 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1980                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1981                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1982                            Sema::CheckConstexprKind Kind) {
1983   // - its function-body shall be [...] a compound-statement that contains only
1984   switch (S->getStmtClass()) {
1985   case Stmt::NullStmtClass:
1986     //   - null statements,
1987     return true;
1988 
1989   case Stmt::DeclStmtClass:
1990     //   - static_assert-declarations
1991     //   - using-declarations,
1992     //   - using-directives,
1993     //   - typedef declarations and alias-declarations that do not define
1994     //     classes or enumerations,
1995     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1996       return false;
1997     return true;
1998 
1999   case Stmt::ReturnStmtClass:
2000     //   - and exactly one return statement;
2001     if (isa<CXXConstructorDecl>(Dcl)) {
2002       // C++1y allows return statements in constexpr constructors.
2003       if (!Cxx1yLoc.isValid())
2004         Cxx1yLoc = S->getBeginLoc();
2005       return true;
2006     }
2007 
2008     ReturnStmts.push_back(S->getBeginLoc());
2009     return true;
2010 
2011   case Stmt::CompoundStmtClass: {
2012     // C++1y allows compound-statements.
2013     if (!Cxx1yLoc.isValid())
2014       Cxx1yLoc = S->getBeginLoc();
2015 
2016     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2017     for (auto *BodyIt : CompStmt->body()) {
2018       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2019                                       Cxx1yLoc, Cxx2aLoc, Kind))
2020         return false;
2021     }
2022     return true;
2023   }
2024 
2025   case Stmt::AttributedStmtClass:
2026     if (!Cxx1yLoc.isValid())
2027       Cxx1yLoc = S->getBeginLoc();
2028     return true;
2029 
2030   case Stmt::IfStmtClass: {
2031     // C++1y allows if-statements.
2032     if (!Cxx1yLoc.isValid())
2033       Cxx1yLoc = S->getBeginLoc();
2034 
2035     IfStmt *If = cast<IfStmt>(S);
2036     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2037                                     Cxx1yLoc, Cxx2aLoc, Kind))
2038       return false;
2039     if (If->getElse() &&
2040         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2041                                     Cxx1yLoc, Cxx2aLoc, Kind))
2042       return false;
2043     return true;
2044   }
2045 
2046   case Stmt::WhileStmtClass:
2047   case Stmt::DoStmtClass:
2048   case Stmt::ForStmtClass:
2049   case Stmt::CXXForRangeStmtClass:
2050   case Stmt::ContinueStmtClass:
2051     // C++1y allows all of these. We don't allow them as extensions in C++11,
2052     // because they don't make sense without variable mutation.
2053     if (!SemaRef.getLangOpts().CPlusPlus14)
2054       break;
2055     if (!Cxx1yLoc.isValid())
2056       Cxx1yLoc = S->getBeginLoc();
2057     for (Stmt *SubStmt : S->children())
2058       if (SubStmt &&
2059           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2060                                       Cxx1yLoc, Cxx2aLoc, Kind))
2061         return false;
2062     return true;
2063 
2064   case Stmt::SwitchStmtClass:
2065   case Stmt::CaseStmtClass:
2066   case Stmt::DefaultStmtClass:
2067   case Stmt::BreakStmtClass:
2068     // C++1y allows switch-statements, and since they don't need variable
2069     // mutation, we can reasonably allow them in C++11 as an extension.
2070     if (!Cxx1yLoc.isValid())
2071       Cxx1yLoc = S->getBeginLoc();
2072     for (Stmt *SubStmt : S->children())
2073       if (SubStmt &&
2074           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2075                                       Cxx1yLoc, Cxx2aLoc, Kind))
2076         return false;
2077     return true;
2078 
2079   case Stmt::GCCAsmStmtClass:
2080   case Stmt::MSAsmStmtClass:
2081     // C++2a allows inline assembly statements.
2082   case Stmt::CXXTryStmtClass:
2083     if (Cxx2aLoc.isInvalid())
2084       Cxx2aLoc = S->getBeginLoc();
2085     for (Stmt *SubStmt : S->children()) {
2086       if (SubStmt &&
2087           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2088                                       Cxx1yLoc, Cxx2aLoc, Kind))
2089         return false;
2090     }
2091     return true;
2092 
2093   case Stmt::CXXCatchStmtClass:
2094     // Do not bother checking the language mode (already covered by the
2095     // try block check).
2096     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2097                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2098                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2099       return false;
2100     return true;
2101 
2102   default:
2103     if (!isa<Expr>(S))
2104       break;
2105 
2106     // C++1y allows expression-statements.
2107     if (!Cxx1yLoc.isValid())
2108       Cxx1yLoc = S->getBeginLoc();
2109     return true;
2110   }
2111 
2112   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2113     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2114         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2115   }
2116   return false;
2117 }
2118 
2119 /// Check the body for the given constexpr function declaration only contains
2120 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2121 ///
2122 /// \return true if the body is OK, false if we have found or diagnosed a
2123 /// problem.
2124 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2125                                        Stmt *Body,
2126                                        Sema::CheckConstexprKind Kind) {
2127   SmallVector<SourceLocation, 4> ReturnStmts;
2128 
2129   if (isa<CXXTryStmt>(Body)) {
2130     // C++11 [dcl.constexpr]p3:
2131     //  The definition of a constexpr function shall satisfy the following
2132     //  constraints: [...]
2133     // - its function-body shall be = delete, = default, or a
2134     //   compound-statement
2135     //
2136     // C++11 [dcl.constexpr]p4:
2137     //  In the definition of a constexpr constructor, [...]
2138     // - its function-body shall not be a function-try-block;
2139     //
2140     // This restriction is lifted in C++2a, as long as inner statements also
2141     // apply the general constexpr rules.
2142     switch (Kind) {
2143     case Sema::CheckConstexprKind::CheckValid:
2144       if (!SemaRef.getLangOpts().CPlusPlus20)
2145         return false;
2146       break;
2147 
2148     case Sema::CheckConstexprKind::Diagnose:
2149       SemaRef.Diag(Body->getBeginLoc(),
2150            !SemaRef.getLangOpts().CPlusPlus20
2151                ? diag::ext_constexpr_function_try_block_cxx20
2152                : diag::warn_cxx17_compat_constexpr_function_try_block)
2153           << isa<CXXConstructorDecl>(Dcl);
2154       break;
2155     }
2156   }
2157 
2158   // - its function-body shall be [...] a compound-statement that contains only
2159   //   [... list of cases ...]
2160   //
2161   // Note that walking the children here is enough to properly check for
2162   // CompoundStmt and CXXTryStmt body.
2163   SourceLocation Cxx1yLoc, Cxx2aLoc;
2164   for (Stmt *SubStmt : Body->children()) {
2165     if (SubStmt &&
2166         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2167                                     Cxx1yLoc, Cxx2aLoc, Kind))
2168       return false;
2169   }
2170 
2171   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2172     // If this is only valid as an extension, report that we don't satisfy the
2173     // constraints of the current language.
2174     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2175         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2176       return false;
2177   } else if (Cxx2aLoc.isValid()) {
2178     SemaRef.Diag(Cxx2aLoc,
2179          SemaRef.getLangOpts().CPlusPlus20
2180            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2181            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2182       << isa<CXXConstructorDecl>(Dcl);
2183   } else if (Cxx1yLoc.isValid()) {
2184     SemaRef.Diag(Cxx1yLoc,
2185          SemaRef.getLangOpts().CPlusPlus14
2186            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2187            : diag::ext_constexpr_body_invalid_stmt)
2188       << isa<CXXConstructorDecl>(Dcl);
2189   }
2190 
2191   if (const CXXConstructorDecl *Constructor
2192         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2193     const CXXRecordDecl *RD = Constructor->getParent();
2194     // DR1359:
2195     // - every non-variant non-static data member and base class sub-object
2196     //   shall be initialized;
2197     // DR1460:
2198     // - if the class is a union having variant members, exactly one of them
2199     //   shall be initialized;
2200     if (RD->isUnion()) {
2201       if (Constructor->getNumCtorInitializers() == 0 &&
2202           RD->hasVariantMembers()) {
2203         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2204           SemaRef.Diag(
2205               Dcl->getLocation(),
2206               SemaRef.getLangOpts().CPlusPlus20
2207                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2208                   : diag::ext_constexpr_union_ctor_no_init);
2209         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2210           return false;
2211         }
2212       }
2213     } else if (!Constructor->isDependentContext() &&
2214                !Constructor->isDelegatingConstructor()) {
2215       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2216 
2217       // Skip detailed checking if we have enough initializers, and we would
2218       // allow at most one initializer per member.
2219       bool AnyAnonStructUnionMembers = false;
2220       unsigned Fields = 0;
2221       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2222            E = RD->field_end(); I != E; ++I, ++Fields) {
2223         if (I->isAnonymousStructOrUnion()) {
2224           AnyAnonStructUnionMembers = true;
2225           break;
2226         }
2227       }
2228       // DR1460:
2229       // - if the class is a union-like class, but is not a union, for each of
2230       //   its anonymous union members having variant members, exactly one of
2231       //   them shall be initialized;
2232       if (AnyAnonStructUnionMembers ||
2233           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2234         // Check initialization of non-static data members. Base classes are
2235         // always initialized so do not need to be checked. Dependent bases
2236         // might not have initializers in the member initializer list.
2237         llvm::SmallSet<Decl*, 16> Inits;
2238         for (const auto *I: Constructor->inits()) {
2239           if (FieldDecl *FD = I->getMember())
2240             Inits.insert(FD);
2241           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2242             Inits.insert(ID->chain_begin(), ID->chain_end());
2243         }
2244 
2245         bool Diagnosed = false;
2246         for (auto *I : RD->fields())
2247           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2248                                              Kind))
2249             return false;
2250       }
2251     }
2252   } else {
2253     if (ReturnStmts.empty()) {
2254       // C++1y doesn't require constexpr functions to contain a 'return'
2255       // statement. We still do, unless the return type might be void, because
2256       // otherwise if there's no return statement, the function cannot
2257       // be used in a core constant expression.
2258       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2259                 (Dcl->getReturnType()->isVoidType() ||
2260                  Dcl->getReturnType()->isDependentType());
2261       switch (Kind) {
2262       case Sema::CheckConstexprKind::Diagnose:
2263         SemaRef.Diag(Dcl->getLocation(),
2264                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2265                         : diag::err_constexpr_body_no_return)
2266             << Dcl->isConsteval();
2267         if (!OK)
2268           return false;
2269         break;
2270 
2271       case Sema::CheckConstexprKind::CheckValid:
2272         // The formal requirements don't include this rule in C++14, even
2273         // though the "must be able to produce a constant expression" rules
2274         // still imply it in some cases.
2275         if (!SemaRef.getLangOpts().CPlusPlus14)
2276           return false;
2277         break;
2278       }
2279     } else if (ReturnStmts.size() > 1) {
2280       switch (Kind) {
2281       case Sema::CheckConstexprKind::Diagnose:
2282         SemaRef.Diag(
2283             ReturnStmts.back(),
2284             SemaRef.getLangOpts().CPlusPlus14
2285                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2286                 : diag::ext_constexpr_body_multiple_return);
2287         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2288           SemaRef.Diag(ReturnStmts[I],
2289                        diag::note_constexpr_body_previous_return);
2290         break;
2291 
2292       case Sema::CheckConstexprKind::CheckValid:
2293         if (!SemaRef.getLangOpts().CPlusPlus14)
2294           return false;
2295         break;
2296       }
2297     }
2298   }
2299 
2300   // C++11 [dcl.constexpr]p5:
2301   //   if no function argument values exist such that the function invocation
2302   //   substitution would produce a constant expression, the program is
2303   //   ill-formed; no diagnostic required.
2304   // C++11 [dcl.constexpr]p3:
2305   //   - every constructor call and implicit conversion used in initializing the
2306   //     return value shall be one of those allowed in a constant expression.
2307   // C++11 [dcl.constexpr]p4:
2308   //   - every constructor involved in initializing non-static data members and
2309   //     base class sub-objects shall be a constexpr constructor.
2310   //
2311   // Note that this rule is distinct from the "requirements for a constexpr
2312   // function", so is not checked in CheckValid mode.
2313   SmallVector<PartialDiagnosticAt, 8> Diags;
2314   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2315       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2316     SemaRef.Diag(Dcl->getLocation(),
2317                  diag::ext_constexpr_function_never_constant_expr)
2318         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2319     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2320       SemaRef.Diag(Diags[I].first, Diags[I].second);
2321     // Don't return false here: we allow this for compatibility in
2322     // system headers.
2323   }
2324 
2325   return true;
2326 }
2327 
2328 /// Get the class that is directly named by the current context. This is the
2329 /// class for which an unqualified-id in this scope could name a constructor
2330 /// or destructor.
2331 ///
2332 /// If the scope specifier denotes a class, this will be that class.
2333 /// If the scope specifier is empty, this will be the class whose
2334 /// member-specification we are currently within. Otherwise, there
2335 /// is no such class.
2336 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2337   assert(getLangOpts().CPlusPlus && "No class names in C!");
2338 
2339   if (SS && SS->isInvalid())
2340     return nullptr;
2341 
2342   if (SS && SS->isNotEmpty()) {
2343     DeclContext *DC = computeDeclContext(*SS, true);
2344     return dyn_cast_or_null<CXXRecordDecl>(DC);
2345   }
2346 
2347   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2348 }
2349 
2350 /// isCurrentClassName - Determine whether the identifier II is the
2351 /// name of the class type currently being defined. In the case of
2352 /// nested classes, this will only return true if II is the name of
2353 /// the innermost class.
2354 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2355                               const CXXScopeSpec *SS) {
2356   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2357   return CurDecl && &II == CurDecl->getIdentifier();
2358 }
2359 
2360 /// Determine whether the identifier II is a typo for the name of
2361 /// the class type currently being defined. If so, update it to the identifier
2362 /// that should have been used.
2363 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2364   assert(getLangOpts().CPlusPlus && "No class names in C!");
2365 
2366   if (!getLangOpts().SpellChecking)
2367     return false;
2368 
2369   CXXRecordDecl *CurDecl;
2370   if (SS && SS->isSet() && !SS->isInvalid()) {
2371     DeclContext *DC = computeDeclContext(*SS, true);
2372     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2373   } else
2374     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2375 
2376   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2377       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2378           < II->getLength()) {
2379     II = CurDecl->getIdentifier();
2380     return true;
2381   }
2382 
2383   return false;
2384 }
2385 
2386 /// Determine whether the given class is a base class of the given
2387 /// class, including looking at dependent bases.
2388 static bool findCircularInheritance(const CXXRecordDecl *Class,
2389                                     const CXXRecordDecl *Current) {
2390   SmallVector<const CXXRecordDecl*, 8> Queue;
2391 
2392   Class = Class->getCanonicalDecl();
2393   while (true) {
2394     for (const auto &I : Current->bases()) {
2395       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2396       if (!Base)
2397         continue;
2398 
2399       Base = Base->getDefinition();
2400       if (!Base)
2401         continue;
2402 
2403       if (Base->getCanonicalDecl() == Class)
2404         return true;
2405 
2406       Queue.push_back(Base);
2407     }
2408 
2409     if (Queue.empty())
2410       return false;
2411 
2412     Current = Queue.pop_back_val();
2413   }
2414 
2415   return false;
2416 }
2417 
2418 /// Check the validity of a C++ base class specifier.
2419 ///
2420 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2421 /// and returns NULL otherwise.
2422 CXXBaseSpecifier *
2423 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2424                          SourceRange SpecifierRange,
2425                          bool Virtual, AccessSpecifier Access,
2426                          TypeSourceInfo *TInfo,
2427                          SourceLocation EllipsisLoc) {
2428   QualType BaseType = TInfo->getType();
2429   if (BaseType->containsErrors()) {
2430     // Already emitted a diagnostic when parsing the error type.
2431     return nullptr;
2432   }
2433   // C++ [class.union]p1:
2434   //   A union shall not have base classes.
2435   if (Class->isUnion()) {
2436     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2437       << SpecifierRange;
2438     return nullptr;
2439   }
2440 
2441   if (EllipsisLoc.isValid() &&
2442       !TInfo->getType()->containsUnexpandedParameterPack()) {
2443     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2444       << TInfo->getTypeLoc().getSourceRange();
2445     EllipsisLoc = SourceLocation();
2446   }
2447 
2448   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2449 
2450   if (BaseType->isDependentType()) {
2451     // Make sure that we don't have circular inheritance among our dependent
2452     // bases. For non-dependent bases, the check for completeness below handles
2453     // this.
2454     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2455       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2456           ((BaseDecl = BaseDecl->getDefinition()) &&
2457            findCircularInheritance(Class, BaseDecl))) {
2458         Diag(BaseLoc, diag::err_circular_inheritance)
2459           << BaseType << Context.getTypeDeclType(Class);
2460 
2461         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2462           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2463             << BaseType;
2464 
2465         return nullptr;
2466       }
2467     }
2468 
2469     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2470                                           Class->getTagKind() == TTK_Class,
2471                                           Access, TInfo, EllipsisLoc);
2472   }
2473 
2474   // Base specifiers must be record types.
2475   if (!BaseType->isRecordType()) {
2476     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2477     return nullptr;
2478   }
2479 
2480   // C++ [class.union]p1:
2481   //   A union shall not be used as a base class.
2482   if (BaseType->isUnionType()) {
2483     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2484     return nullptr;
2485   }
2486 
2487   // For the MS ABI, propagate DLL attributes to base class templates.
2488   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2489     if (Attr *ClassAttr = getDLLAttr(Class)) {
2490       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2491               BaseType->getAsCXXRecordDecl())) {
2492         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2493                                             BaseLoc);
2494       }
2495     }
2496   }
2497 
2498   // C++ [class.derived]p2:
2499   //   The class-name in a base-specifier shall not be an incompletely
2500   //   defined class.
2501   if (RequireCompleteType(BaseLoc, BaseType,
2502                           diag::err_incomplete_base_class, SpecifierRange)) {
2503     Class->setInvalidDecl();
2504     return nullptr;
2505   }
2506 
2507   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2508   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2509   assert(BaseDecl && "Record type has no declaration");
2510   BaseDecl = BaseDecl->getDefinition();
2511   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2512   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2513   assert(CXXBaseDecl && "Base type is not a C++ type");
2514 
2515   // Microsoft docs say:
2516   // "If a base-class has a code_seg attribute, derived classes must have the
2517   // same attribute."
2518   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2519   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2520   if ((DerivedCSA || BaseCSA) &&
2521       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2522     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2523     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2524       << CXXBaseDecl;
2525     return nullptr;
2526   }
2527 
2528   // A class which contains a flexible array member is not suitable for use as a
2529   // base class:
2530   //   - If the layout determines that a base comes before another base,
2531   //     the flexible array member would index into the subsequent base.
2532   //   - If the layout determines that base comes before the derived class,
2533   //     the flexible array member would index into the derived class.
2534   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2535     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2536       << CXXBaseDecl->getDeclName();
2537     return nullptr;
2538   }
2539 
2540   // C++ [class]p3:
2541   //   If a class is marked final and it appears as a base-type-specifier in
2542   //   base-clause, the program is ill-formed.
2543   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2544     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2545       << CXXBaseDecl->getDeclName()
2546       << FA->isSpelledAsSealed();
2547     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2548         << CXXBaseDecl->getDeclName() << FA->getRange();
2549     return nullptr;
2550   }
2551 
2552   if (BaseDecl->isInvalidDecl())
2553     Class->setInvalidDecl();
2554 
2555   // Create the base specifier.
2556   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2557                                         Class->getTagKind() == TTK_Class,
2558                                         Access, TInfo, EllipsisLoc);
2559 }
2560 
2561 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2562 /// one entry in the base class list of a class specifier, for
2563 /// example:
2564 ///    class foo : public bar, virtual private baz {
2565 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2566 BaseResult
2567 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2568                          ParsedAttributes &Attributes,
2569                          bool Virtual, AccessSpecifier Access,
2570                          ParsedType basetype, SourceLocation BaseLoc,
2571                          SourceLocation EllipsisLoc) {
2572   if (!classdecl)
2573     return true;
2574 
2575   AdjustDeclIfTemplate(classdecl);
2576   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2577   if (!Class)
2578     return true;
2579 
2580   // We haven't yet attached the base specifiers.
2581   Class->setIsParsingBaseSpecifiers();
2582 
2583   // We do not support any C++11 attributes on base-specifiers yet.
2584   // Diagnose any attributes we see.
2585   for (const ParsedAttr &AL : Attributes) {
2586     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2587       continue;
2588     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2589                           ? (unsigned)diag::warn_unknown_attribute_ignored
2590                           : (unsigned)diag::err_base_specifier_attribute)
2591         << AL;
2592   }
2593 
2594   TypeSourceInfo *TInfo = nullptr;
2595   GetTypeFromParser(basetype, &TInfo);
2596 
2597   if (EllipsisLoc.isInvalid() &&
2598       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2599                                       UPPC_BaseType))
2600     return true;
2601 
2602   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2603                                                       Virtual, Access, TInfo,
2604                                                       EllipsisLoc))
2605     return BaseSpec;
2606   else
2607     Class->setInvalidDecl();
2608 
2609   return true;
2610 }
2611 
2612 /// Use small set to collect indirect bases.  As this is only used
2613 /// locally, there's no need to abstract the small size parameter.
2614 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2615 
2616 /// Recursively add the bases of Type.  Don't add Type itself.
2617 static void
2618 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2619                   const QualType &Type)
2620 {
2621   // Even though the incoming type is a base, it might not be
2622   // a class -- it could be a template parm, for instance.
2623   if (auto Rec = Type->getAs<RecordType>()) {
2624     auto Decl = Rec->getAsCXXRecordDecl();
2625 
2626     // Iterate over its bases.
2627     for (const auto &BaseSpec : Decl->bases()) {
2628       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2629         .getUnqualifiedType();
2630       if (Set.insert(Base).second)
2631         // If we've not already seen it, recurse.
2632         NoteIndirectBases(Context, Set, Base);
2633     }
2634   }
2635 }
2636 
2637 /// Performs the actual work of attaching the given base class
2638 /// specifiers to a C++ class.
2639 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2640                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2641  if (Bases.empty())
2642     return false;
2643 
2644   // Used to keep track of which base types we have already seen, so
2645   // that we can properly diagnose redundant direct base types. Note
2646   // that the key is always the unqualified canonical type of the base
2647   // class.
2648   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2649 
2650   // Used to track indirect bases so we can see if a direct base is
2651   // ambiguous.
2652   IndirectBaseSet IndirectBaseTypes;
2653 
2654   // Copy non-redundant base specifiers into permanent storage.
2655   unsigned NumGoodBases = 0;
2656   bool Invalid = false;
2657   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2658     QualType NewBaseType
2659       = Context.getCanonicalType(Bases[idx]->getType());
2660     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2661 
2662     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2663     if (KnownBase) {
2664       // C++ [class.mi]p3:
2665       //   A class shall not be specified as a direct base class of a
2666       //   derived class more than once.
2667       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2668           << KnownBase->getType() << Bases[idx]->getSourceRange();
2669 
2670       // Delete the duplicate base class specifier; we're going to
2671       // overwrite its pointer later.
2672       Context.Deallocate(Bases[idx]);
2673 
2674       Invalid = true;
2675     } else {
2676       // Okay, add this new base class.
2677       KnownBase = Bases[idx];
2678       Bases[NumGoodBases++] = Bases[idx];
2679 
2680       // Note this base's direct & indirect bases, if there could be ambiguity.
2681       if (Bases.size() > 1)
2682         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2683 
2684       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2685         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2686         if (Class->isInterface() &&
2687               (!RD->isInterfaceLike() ||
2688                KnownBase->getAccessSpecifier() != AS_public)) {
2689           // The Microsoft extension __interface does not permit bases that
2690           // are not themselves public interfaces.
2691           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2692               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2693               << RD->getSourceRange();
2694           Invalid = true;
2695         }
2696         if (RD->hasAttr<WeakAttr>())
2697           Class->addAttr(WeakAttr::CreateImplicit(Context));
2698       }
2699     }
2700   }
2701 
2702   // Attach the remaining base class specifiers to the derived class.
2703   Class->setBases(Bases.data(), NumGoodBases);
2704 
2705   // Check that the only base classes that are duplicate are virtual.
2706   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2707     // Check whether this direct base is inaccessible due to ambiguity.
2708     QualType BaseType = Bases[idx]->getType();
2709 
2710     // Skip all dependent types in templates being used as base specifiers.
2711     // Checks below assume that the base specifier is a CXXRecord.
2712     if (BaseType->isDependentType())
2713       continue;
2714 
2715     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2716       .getUnqualifiedType();
2717 
2718     if (IndirectBaseTypes.count(CanonicalBase)) {
2719       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2720                          /*DetectVirtual=*/true);
2721       bool found
2722         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2723       assert(found);
2724       (void)found;
2725 
2726       if (Paths.isAmbiguous(CanonicalBase))
2727         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2728             << BaseType << getAmbiguousPathsDisplayString(Paths)
2729             << Bases[idx]->getSourceRange();
2730       else
2731         assert(Bases[idx]->isVirtual());
2732     }
2733 
2734     // Delete the base class specifier, since its data has been copied
2735     // into the CXXRecordDecl.
2736     Context.Deallocate(Bases[idx]);
2737   }
2738 
2739   return Invalid;
2740 }
2741 
2742 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2743 /// class, after checking whether there are any duplicate base
2744 /// classes.
2745 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2746                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2747   if (!ClassDecl || Bases.empty())
2748     return;
2749 
2750   AdjustDeclIfTemplate(ClassDecl);
2751   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2752 }
2753 
2754 /// Determine whether the type \p Derived is a C++ class that is
2755 /// derived from the type \p Base.
2756 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2757   if (!getLangOpts().CPlusPlus)
2758     return false;
2759 
2760   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2761   if (!DerivedRD)
2762     return false;
2763 
2764   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2765   if (!BaseRD)
2766     return false;
2767 
2768   // If either the base or the derived type is invalid, don't try to
2769   // check whether one is derived from the other.
2770   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2771     return false;
2772 
2773   // FIXME: In a modules build, do we need the entire path to be visible for us
2774   // to be able to use the inheritance relationship?
2775   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2776     return false;
2777 
2778   return DerivedRD->isDerivedFrom(BaseRD);
2779 }
2780 
2781 /// Determine whether the type \p Derived is a C++ class that is
2782 /// derived from the type \p Base.
2783 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2784                          CXXBasePaths &Paths) {
2785   if (!getLangOpts().CPlusPlus)
2786     return false;
2787 
2788   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2789   if (!DerivedRD)
2790     return false;
2791 
2792   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2793   if (!BaseRD)
2794     return false;
2795 
2796   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2797     return false;
2798 
2799   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2800 }
2801 
2802 static void BuildBasePathArray(const CXXBasePath &Path,
2803                                CXXCastPath &BasePathArray) {
2804   // We first go backward and check if we have a virtual base.
2805   // FIXME: It would be better if CXXBasePath had the base specifier for
2806   // the nearest virtual base.
2807   unsigned Start = 0;
2808   for (unsigned I = Path.size(); I != 0; --I) {
2809     if (Path[I - 1].Base->isVirtual()) {
2810       Start = I - 1;
2811       break;
2812     }
2813   }
2814 
2815   // Now add all bases.
2816   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2817     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2818 }
2819 
2820 
2821 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2822                               CXXCastPath &BasePathArray) {
2823   assert(BasePathArray.empty() && "Base path array must be empty!");
2824   assert(Paths.isRecordingPaths() && "Must record paths!");
2825   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2826 }
2827 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2828 /// conversion (where Derived and Base are class types) is
2829 /// well-formed, meaning that the conversion is unambiguous (and
2830 /// that all of the base classes are accessible). Returns true
2831 /// and emits a diagnostic if the code is ill-formed, returns false
2832 /// otherwise. Loc is the location where this routine should point to
2833 /// if there is an error, and Range is the source range to highlight
2834 /// if there is an error.
2835 ///
2836 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2837 /// diagnostic for the respective type of error will be suppressed, but the
2838 /// check for ill-formed code will still be performed.
2839 bool
2840 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2841                                    unsigned InaccessibleBaseID,
2842                                    unsigned AmbiguousBaseConvID,
2843                                    SourceLocation Loc, SourceRange Range,
2844                                    DeclarationName Name,
2845                                    CXXCastPath *BasePath,
2846                                    bool IgnoreAccess) {
2847   // First, determine whether the path from Derived to Base is
2848   // ambiguous. This is slightly more expensive than checking whether
2849   // the Derived to Base conversion exists, because here we need to
2850   // explore multiple paths to determine if there is an ambiguity.
2851   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2852                      /*DetectVirtual=*/false);
2853   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2854   if (!DerivationOkay)
2855     return true;
2856 
2857   const CXXBasePath *Path = nullptr;
2858   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2859     Path = &Paths.front();
2860 
2861   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2862   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2863   // user to access such bases.
2864   if (!Path && getLangOpts().MSVCCompat) {
2865     for (const CXXBasePath &PossiblePath : Paths) {
2866       if (PossiblePath.size() == 1) {
2867         Path = &PossiblePath;
2868         if (AmbiguousBaseConvID)
2869           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2870               << Base << Derived << Range;
2871         break;
2872       }
2873     }
2874   }
2875 
2876   if (Path) {
2877     if (!IgnoreAccess) {
2878       // Check that the base class can be accessed.
2879       switch (
2880           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2881       case AR_inaccessible:
2882         return true;
2883       case AR_accessible:
2884       case AR_dependent:
2885       case AR_delayed:
2886         break;
2887       }
2888     }
2889 
2890     // Build a base path if necessary.
2891     if (BasePath)
2892       ::BuildBasePathArray(*Path, *BasePath);
2893     return false;
2894   }
2895 
2896   if (AmbiguousBaseConvID) {
2897     // We know that the derived-to-base conversion is ambiguous, and
2898     // we're going to produce a diagnostic. Perform the derived-to-base
2899     // search just one more time to compute all of the possible paths so
2900     // that we can print them out. This is more expensive than any of
2901     // the previous derived-to-base checks we've done, but at this point
2902     // performance isn't as much of an issue.
2903     Paths.clear();
2904     Paths.setRecordingPaths(true);
2905     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2906     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2907     (void)StillOkay;
2908 
2909     // Build up a textual representation of the ambiguous paths, e.g.,
2910     // D -> B -> A, that will be used to illustrate the ambiguous
2911     // conversions in the diagnostic. We only print one of the paths
2912     // to each base class subobject.
2913     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2914 
2915     Diag(Loc, AmbiguousBaseConvID)
2916     << Derived << Base << PathDisplayStr << Range << Name;
2917   }
2918   return true;
2919 }
2920 
2921 bool
2922 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2923                                    SourceLocation Loc, SourceRange Range,
2924                                    CXXCastPath *BasePath,
2925                                    bool IgnoreAccess) {
2926   return CheckDerivedToBaseConversion(
2927       Derived, Base, diag::err_upcast_to_inaccessible_base,
2928       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2929       BasePath, IgnoreAccess);
2930 }
2931 
2932 
2933 /// Builds a string representing ambiguous paths from a
2934 /// specific derived class to different subobjects of the same base
2935 /// class.
2936 ///
2937 /// This function builds a string that can be used in error messages
2938 /// to show the different paths that one can take through the
2939 /// inheritance hierarchy to go from the derived class to different
2940 /// subobjects of a base class. The result looks something like this:
2941 /// @code
2942 /// struct D -> struct B -> struct A
2943 /// struct D -> struct C -> struct A
2944 /// @endcode
2945 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2946   std::string PathDisplayStr;
2947   std::set<unsigned> DisplayedPaths;
2948   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2949        Path != Paths.end(); ++Path) {
2950     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2951       // We haven't displayed a path to this particular base
2952       // class subobject yet.
2953       PathDisplayStr += "\n    ";
2954       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2955       for (CXXBasePath::const_iterator Element = Path->begin();
2956            Element != Path->end(); ++Element)
2957         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2958     }
2959   }
2960 
2961   return PathDisplayStr;
2962 }
2963 
2964 //===----------------------------------------------------------------------===//
2965 // C++ class member Handling
2966 //===----------------------------------------------------------------------===//
2967 
2968 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2969 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2970                                 SourceLocation ColonLoc,
2971                                 const ParsedAttributesView &Attrs) {
2972   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2973   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2974                                                   ASLoc, ColonLoc);
2975   CurContext->addHiddenDecl(ASDecl);
2976   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2977 }
2978 
2979 /// CheckOverrideControl - Check C++11 override control semantics.
2980 void Sema::CheckOverrideControl(NamedDecl *D) {
2981   if (D->isInvalidDecl())
2982     return;
2983 
2984   // We only care about "override" and "final" declarations.
2985   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2986     return;
2987 
2988   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2989 
2990   // We can't check dependent instance methods.
2991   if (MD && MD->isInstance() &&
2992       (MD->getParent()->hasAnyDependentBases() ||
2993        MD->getType()->isDependentType()))
2994     return;
2995 
2996   if (MD && !MD->isVirtual()) {
2997     // If we have a non-virtual method, check if if hides a virtual method.
2998     // (In that case, it's most likely the method has the wrong type.)
2999     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3000     FindHiddenVirtualMethods(MD, OverloadedMethods);
3001 
3002     if (!OverloadedMethods.empty()) {
3003       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3004         Diag(OA->getLocation(),
3005              diag::override_keyword_hides_virtual_member_function)
3006           << "override" << (OverloadedMethods.size() > 1);
3007       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3008         Diag(FA->getLocation(),
3009              diag::override_keyword_hides_virtual_member_function)
3010           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3011           << (OverloadedMethods.size() > 1);
3012       }
3013       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3014       MD->setInvalidDecl();
3015       return;
3016     }
3017     // Fall through into the general case diagnostic.
3018     // FIXME: We might want to attempt typo correction here.
3019   }
3020 
3021   if (!MD || !MD->isVirtual()) {
3022     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3023       Diag(OA->getLocation(),
3024            diag::override_keyword_only_allowed_on_virtual_member_functions)
3025         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3026       D->dropAttr<OverrideAttr>();
3027     }
3028     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3029       Diag(FA->getLocation(),
3030            diag::override_keyword_only_allowed_on_virtual_member_functions)
3031         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3032         << FixItHint::CreateRemoval(FA->getLocation());
3033       D->dropAttr<FinalAttr>();
3034     }
3035     return;
3036   }
3037 
3038   // C++11 [class.virtual]p5:
3039   //   If a function is marked with the virt-specifier override and
3040   //   does not override a member function of a base class, the program is
3041   //   ill-formed.
3042   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3043   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3044     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3045       << MD->getDeclName();
3046 }
3047 
3048 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3049   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3050     return;
3051   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3052   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3053     return;
3054 
3055   SourceLocation Loc = MD->getLocation();
3056   SourceLocation SpellingLoc = Loc;
3057   if (getSourceManager().isMacroArgExpansion(Loc))
3058     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3059   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3060   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3061       return;
3062 
3063   if (MD->size_overridden_methods() > 0) {
3064     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3065       unsigned DiagID =
3066           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3067               ? DiagInconsistent
3068               : DiagSuggest;
3069       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3070       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3071       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3072     };
3073     if (isa<CXXDestructorDecl>(MD))
3074       EmitDiag(
3075           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3076           diag::warn_suggest_destructor_marked_not_override_overriding);
3077     else
3078       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3079                diag::warn_suggest_function_marked_not_override_overriding);
3080   }
3081 }
3082 
3083 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3084 /// function overrides a virtual member function marked 'final', according to
3085 /// C++11 [class.virtual]p4.
3086 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3087                                                   const CXXMethodDecl *Old) {
3088   FinalAttr *FA = Old->getAttr<FinalAttr>();
3089   if (!FA)
3090     return false;
3091 
3092   Diag(New->getLocation(), diag::err_final_function_overridden)
3093     << New->getDeclName()
3094     << FA->isSpelledAsSealed();
3095   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3096   return true;
3097 }
3098 
3099 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3100   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3101   // FIXME: Destruction of ObjC lifetime types has side-effects.
3102   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3103     return !RD->isCompleteDefinition() ||
3104            !RD->hasTrivialDefaultConstructor() ||
3105            !RD->hasTrivialDestructor();
3106   return false;
3107 }
3108 
3109 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3110   ParsedAttributesView::const_iterator Itr =
3111       llvm::find_if(list, [](const ParsedAttr &AL) {
3112         return AL.isDeclspecPropertyAttribute();
3113       });
3114   if (Itr != list.end())
3115     return &*Itr;
3116   return nullptr;
3117 }
3118 
3119 // Check if there is a field shadowing.
3120 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3121                                       DeclarationName FieldName,
3122                                       const CXXRecordDecl *RD,
3123                                       bool DeclIsField) {
3124   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3125     return;
3126 
3127   // To record a shadowed field in a base
3128   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3129   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3130                            CXXBasePath &Path) {
3131     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3132     // Record an ambiguous path directly
3133     if (Bases.find(Base) != Bases.end())
3134       return true;
3135     for (const auto Field : Base->lookup(FieldName)) {
3136       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3137           Field->getAccess() != AS_private) {
3138         assert(Field->getAccess() != AS_none);
3139         assert(Bases.find(Base) == Bases.end());
3140         Bases[Base] = Field;
3141         return true;
3142       }
3143     }
3144     return false;
3145   };
3146 
3147   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3148                      /*DetectVirtual=*/true);
3149   if (!RD->lookupInBases(FieldShadowed, Paths))
3150     return;
3151 
3152   for (const auto &P : Paths) {
3153     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3154     auto It = Bases.find(Base);
3155     // Skip duplicated bases
3156     if (It == Bases.end())
3157       continue;
3158     auto BaseField = It->second;
3159     assert(BaseField->getAccess() != AS_private);
3160     if (AS_none !=
3161         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3162       Diag(Loc, diag::warn_shadow_field)
3163         << FieldName << RD << Base << DeclIsField;
3164       Diag(BaseField->getLocation(), diag::note_shadow_field);
3165       Bases.erase(It);
3166     }
3167   }
3168 }
3169 
3170 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3171 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3172 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3173 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3174 /// present (but parsing it has been deferred).
3175 NamedDecl *
3176 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3177                                MultiTemplateParamsArg TemplateParameterLists,
3178                                Expr *BW, const VirtSpecifiers &VS,
3179                                InClassInitStyle InitStyle) {
3180   const DeclSpec &DS = D.getDeclSpec();
3181   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3182   DeclarationName Name = NameInfo.getName();
3183   SourceLocation Loc = NameInfo.getLoc();
3184 
3185   // For anonymous bitfields, the location should point to the type.
3186   if (Loc.isInvalid())
3187     Loc = D.getBeginLoc();
3188 
3189   Expr *BitWidth = static_cast<Expr*>(BW);
3190 
3191   assert(isa<CXXRecordDecl>(CurContext));
3192   assert(!DS.isFriendSpecified());
3193 
3194   bool isFunc = D.isDeclarationOfFunction();
3195   const ParsedAttr *MSPropertyAttr =
3196       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3197 
3198   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3199     // The Microsoft extension __interface only permits public member functions
3200     // and prohibits constructors, destructors, operators, non-public member
3201     // functions, static methods and data members.
3202     unsigned InvalidDecl;
3203     bool ShowDeclName = true;
3204     if (!isFunc &&
3205         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3206       InvalidDecl = 0;
3207     else if (!isFunc)
3208       InvalidDecl = 1;
3209     else if (AS != AS_public)
3210       InvalidDecl = 2;
3211     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3212       InvalidDecl = 3;
3213     else switch (Name.getNameKind()) {
3214       case DeclarationName::CXXConstructorName:
3215         InvalidDecl = 4;
3216         ShowDeclName = false;
3217         break;
3218 
3219       case DeclarationName::CXXDestructorName:
3220         InvalidDecl = 5;
3221         ShowDeclName = false;
3222         break;
3223 
3224       case DeclarationName::CXXOperatorName:
3225       case DeclarationName::CXXConversionFunctionName:
3226         InvalidDecl = 6;
3227         break;
3228 
3229       default:
3230         InvalidDecl = 0;
3231         break;
3232     }
3233 
3234     if (InvalidDecl) {
3235       if (ShowDeclName)
3236         Diag(Loc, diag::err_invalid_member_in_interface)
3237           << (InvalidDecl-1) << Name;
3238       else
3239         Diag(Loc, diag::err_invalid_member_in_interface)
3240           << (InvalidDecl-1) << "";
3241       return nullptr;
3242     }
3243   }
3244 
3245   // C++ 9.2p6: A member shall not be declared to have automatic storage
3246   // duration (auto, register) or with the extern storage-class-specifier.
3247   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3248   // data members and cannot be applied to names declared const or static,
3249   // and cannot be applied to reference members.
3250   switch (DS.getStorageClassSpec()) {
3251   case DeclSpec::SCS_unspecified:
3252   case DeclSpec::SCS_typedef:
3253   case DeclSpec::SCS_static:
3254     break;
3255   case DeclSpec::SCS_mutable:
3256     if (isFunc) {
3257       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3258 
3259       // FIXME: It would be nicer if the keyword was ignored only for this
3260       // declarator. Otherwise we could get follow-up errors.
3261       D.getMutableDeclSpec().ClearStorageClassSpecs();
3262     }
3263     break;
3264   default:
3265     Diag(DS.getStorageClassSpecLoc(),
3266          diag::err_storageclass_invalid_for_member);
3267     D.getMutableDeclSpec().ClearStorageClassSpecs();
3268     break;
3269   }
3270 
3271   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3272                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3273                       !isFunc);
3274 
3275   if (DS.hasConstexprSpecifier() && isInstField) {
3276     SemaDiagnosticBuilder B =
3277         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3278     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3279     if (InitStyle == ICIS_NoInit) {
3280       B << 0 << 0;
3281       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3282         B << FixItHint::CreateRemoval(ConstexprLoc);
3283       else {
3284         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3285         D.getMutableDeclSpec().ClearConstexprSpec();
3286         const char *PrevSpec;
3287         unsigned DiagID;
3288         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3289             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3290         (void)Failed;
3291         assert(!Failed && "Making a constexpr member const shouldn't fail");
3292       }
3293     } else {
3294       B << 1;
3295       const char *PrevSpec;
3296       unsigned DiagID;
3297       if (D.getMutableDeclSpec().SetStorageClassSpec(
3298           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3299           Context.getPrintingPolicy())) {
3300         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3301                "This is the only DeclSpec that should fail to be applied");
3302         B << 1;
3303       } else {
3304         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3305         isInstField = false;
3306       }
3307     }
3308   }
3309 
3310   NamedDecl *Member;
3311   if (isInstField) {
3312     CXXScopeSpec &SS = D.getCXXScopeSpec();
3313 
3314     // Data members must have identifiers for names.
3315     if (!Name.isIdentifier()) {
3316       Diag(Loc, diag::err_bad_variable_name)
3317         << Name;
3318       return nullptr;
3319     }
3320 
3321     IdentifierInfo *II = Name.getAsIdentifierInfo();
3322 
3323     // Member field could not be with "template" keyword.
3324     // So TemplateParameterLists should be empty in this case.
3325     if (TemplateParameterLists.size()) {
3326       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3327       if (TemplateParams->size()) {
3328         // There is no such thing as a member field template.
3329         Diag(D.getIdentifierLoc(), diag::err_template_member)
3330             << II
3331             << SourceRange(TemplateParams->getTemplateLoc(),
3332                 TemplateParams->getRAngleLoc());
3333       } else {
3334         // There is an extraneous 'template<>' for this member.
3335         Diag(TemplateParams->getTemplateLoc(),
3336             diag::err_template_member_noparams)
3337             << II
3338             << SourceRange(TemplateParams->getTemplateLoc(),
3339                 TemplateParams->getRAngleLoc());
3340       }
3341       return nullptr;
3342     }
3343 
3344     if (SS.isSet() && !SS.isInvalid()) {
3345       // The user provided a superfluous scope specifier inside a class
3346       // definition:
3347       //
3348       // class X {
3349       //   int X::member;
3350       // };
3351       if (DeclContext *DC = computeDeclContext(SS, false))
3352         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3353                                      D.getName().getKind() ==
3354                                          UnqualifiedIdKind::IK_TemplateId);
3355       else
3356         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3357           << Name << SS.getRange();
3358 
3359       SS.clear();
3360     }
3361 
3362     if (MSPropertyAttr) {
3363       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3364                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3365       if (!Member)
3366         return nullptr;
3367       isInstField = false;
3368     } else {
3369       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3370                                 BitWidth, InitStyle, AS);
3371       if (!Member)
3372         return nullptr;
3373     }
3374 
3375     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3376   } else {
3377     Member = HandleDeclarator(S, D, TemplateParameterLists);
3378     if (!Member)
3379       return nullptr;
3380 
3381     // Non-instance-fields can't have a bitfield.
3382     if (BitWidth) {
3383       if (Member->isInvalidDecl()) {
3384         // don't emit another diagnostic.
3385       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3386         // C++ 9.6p3: A bit-field shall not be a static member.
3387         // "static member 'A' cannot be a bit-field"
3388         Diag(Loc, diag::err_static_not_bitfield)
3389           << Name << BitWidth->getSourceRange();
3390       } else if (isa<TypedefDecl>(Member)) {
3391         // "typedef member 'x' cannot be a bit-field"
3392         Diag(Loc, diag::err_typedef_not_bitfield)
3393           << Name << BitWidth->getSourceRange();
3394       } else {
3395         // A function typedef ("typedef int f(); f a;").
3396         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3397         Diag(Loc, diag::err_not_integral_type_bitfield)
3398           << Name << cast<ValueDecl>(Member)->getType()
3399           << BitWidth->getSourceRange();
3400       }
3401 
3402       BitWidth = nullptr;
3403       Member->setInvalidDecl();
3404     }
3405 
3406     NamedDecl *NonTemplateMember = Member;
3407     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3408       NonTemplateMember = FunTmpl->getTemplatedDecl();
3409     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3410       NonTemplateMember = VarTmpl->getTemplatedDecl();
3411 
3412     Member->setAccess(AS);
3413 
3414     // If we have declared a member function template or static data member
3415     // template, set the access of the templated declaration as well.
3416     if (NonTemplateMember != Member)
3417       NonTemplateMember->setAccess(AS);
3418 
3419     // C++ [temp.deduct.guide]p3:
3420     //   A deduction guide [...] for a member class template [shall be
3421     //   declared] with the same access [as the template].
3422     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3423       auto *TD = DG->getDeducedTemplate();
3424       // Access specifiers are only meaningful if both the template and the
3425       // deduction guide are from the same scope.
3426       if (AS != TD->getAccess() &&
3427           TD->getDeclContext()->getRedeclContext()->Equals(
3428               DG->getDeclContext()->getRedeclContext())) {
3429         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3430         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3431             << TD->getAccess();
3432         const AccessSpecDecl *LastAccessSpec = nullptr;
3433         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3434           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3435             LastAccessSpec = AccessSpec;
3436         }
3437         assert(LastAccessSpec && "differing access with no access specifier");
3438         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3439             << AS;
3440       }
3441     }
3442   }
3443 
3444   if (VS.isOverrideSpecified())
3445     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3446                                          AttributeCommonInfo::AS_Keyword));
3447   if (VS.isFinalSpecified())
3448     Member->addAttr(FinalAttr::Create(
3449         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3450         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3451 
3452   if (VS.getLastLocation().isValid()) {
3453     // Update the end location of a method that has a virt-specifiers.
3454     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3455       MD->setRangeEnd(VS.getLastLocation());
3456   }
3457 
3458   CheckOverrideControl(Member);
3459 
3460   assert((Name || isInstField) && "No identifier for non-field ?");
3461 
3462   if (isInstField) {
3463     FieldDecl *FD = cast<FieldDecl>(Member);
3464     FieldCollector->Add(FD);
3465 
3466     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3467       // Remember all explicit private FieldDecls that have a name, no side
3468       // effects and are not part of a dependent type declaration.
3469       if (!FD->isImplicit() && FD->getDeclName() &&
3470           FD->getAccess() == AS_private &&
3471           !FD->hasAttr<UnusedAttr>() &&
3472           !FD->getParent()->isDependentContext() &&
3473           !InitializationHasSideEffects(*FD))
3474         UnusedPrivateFields.insert(FD);
3475     }
3476   }
3477 
3478   return Member;
3479 }
3480 
3481 namespace {
3482   class UninitializedFieldVisitor
3483       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3484     Sema &S;
3485     // List of Decls to generate a warning on.  Also remove Decls that become
3486     // initialized.
3487     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3488     // List of base classes of the record.  Classes are removed after their
3489     // initializers.
3490     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3491     // Vector of decls to be removed from the Decl set prior to visiting the
3492     // nodes.  These Decls may have been initialized in the prior initializer.
3493     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3494     // If non-null, add a note to the warning pointing back to the constructor.
3495     const CXXConstructorDecl *Constructor;
3496     // Variables to hold state when processing an initializer list.  When
3497     // InitList is true, special case initialization of FieldDecls matching
3498     // InitListFieldDecl.
3499     bool InitList;
3500     FieldDecl *InitListFieldDecl;
3501     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3502 
3503   public:
3504     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3505     UninitializedFieldVisitor(Sema &S,
3506                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3507                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3508       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3509         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3510 
3511     // Returns true if the use of ME is not an uninitialized use.
3512     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3513                                          bool CheckReferenceOnly) {
3514       llvm::SmallVector<FieldDecl*, 4> Fields;
3515       bool ReferenceField = false;
3516       while (ME) {
3517         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3518         if (!FD)
3519           return false;
3520         Fields.push_back(FD);
3521         if (FD->getType()->isReferenceType())
3522           ReferenceField = true;
3523         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3524       }
3525 
3526       // Binding a reference to an uninitialized field is not an
3527       // uninitialized use.
3528       if (CheckReferenceOnly && !ReferenceField)
3529         return true;
3530 
3531       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3532       // Discard the first field since it is the field decl that is being
3533       // initialized.
3534       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3535         UsedFieldIndex.push_back((*I)->getFieldIndex());
3536       }
3537 
3538       for (auto UsedIter = UsedFieldIndex.begin(),
3539                 UsedEnd = UsedFieldIndex.end(),
3540                 OrigIter = InitFieldIndex.begin(),
3541                 OrigEnd = InitFieldIndex.end();
3542            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3543         if (*UsedIter < *OrigIter)
3544           return true;
3545         if (*UsedIter > *OrigIter)
3546           break;
3547       }
3548 
3549       return false;
3550     }
3551 
3552     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3553                           bool AddressOf) {
3554       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3555         return;
3556 
3557       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3558       // or union.
3559       MemberExpr *FieldME = ME;
3560 
3561       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3562 
3563       Expr *Base = ME;
3564       while (MemberExpr *SubME =
3565                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3566 
3567         if (isa<VarDecl>(SubME->getMemberDecl()))
3568           return;
3569 
3570         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3571           if (!FD->isAnonymousStructOrUnion())
3572             FieldME = SubME;
3573 
3574         if (!FieldME->getType().isPODType(S.Context))
3575           AllPODFields = false;
3576 
3577         Base = SubME->getBase();
3578       }
3579 
3580       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3581         Visit(Base);
3582         return;
3583       }
3584 
3585       if (AddressOf && AllPODFields)
3586         return;
3587 
3588       ValueDecl* FoundVD = FieldME->getMemberDecl();
3589 
3590       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3591         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3592           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3593         }
3594 
3595         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3596           QualType T = BaseCast->getType();
3597           if (T->isPointerType() &&
3598               BaseClasses.count(T->getPointeeType())) {
3599             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3600                 << T->getPointeeType() << FoundVD;
3601           }
3602         }
3603       }
3604 
3605       if (!Decls.count(FoundVD))
3606         return;
3607 
3608       const bool IsReference = FoundVD->getType()->isReferenceType();
3609 
3610       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3611         // Special checking for initializer lists.
3612         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3613           return;
3614         }
3615       } else {
3616         // Prevent double warnings on use of unbounded references.
3617         if (CheckReferenceOnly && !IsReference)
3618           return;
3619       }
3620 
3621       unsigned diag = IsReference
3622           ? diag::warn_reference_field_is_uninit
3623           : diag::warn_field_is_uninit;
3624       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3625       if (Constructor)
3626         S.Diag(Constructor->getLocation(),
3627                diag::note_uninit_in_this_constructor)
3628           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3629 
3630     }
3631 
3632     void HandleValue(Expr *E, bool AddressOf) {
3633       E = E->IgnoreParens();
3634 
3635       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3636         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3637                          AddressOf /*AddressOf*/);
3638         return;
3639       }
3640 
3641       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3642         Visit(CO->getCond());
3643         HandleValue(CO->getTrueExpr(), AddressOf);
3644         HandleValue(CO->getFalseExpr(), AddressOf);
3645         return;
3646       }
3647 
3648       if (BinaryConditionalOperator *BCO =
3649               dyn_cast<BinaryConditionalOperator>(E)) {
3650         Visit(BCO->getCond());
3651         HandleValue(BCO->getFalseExpr(), AddressOf);
3652         return;
3653       }
3654 
3655       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3656         HandleValue(OVE->getSourceExpr(), AddressOf);
3657         return;
3658       }
3659 
3660       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3661         switch (BO->getOpcode()) {
3662         default:
3663           break;
3664         case(BO_PtrMemD):
3665         case(BO_PtrMemI):
3666           HandleValue(BO->getLHS(), AddressOf);
3667           Visit(BO->getRHS());
3668           return;
3669         case(BO_Comma):
3670           Visit(BO->getLHS());
3671           HandleValue(BO->getRHS(), AddressOf);
3672           return;
3673         }
3674       }
3675 
3676       Visit(E);
3677     }
3678 
3679     void CheckInitListExpr(InitListExpr *ILE) {
3680       InitFieldIndex.push_back(0);
3681       for (auto Child : ILE->children()) {
3682         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3683           CheckInitListExpr(SubList);
3684         } else {
3685           Visit(Child);
3686         }
3687         ++InitFieldIndex.back();
3688       }
3689       InitFieldIndex.pop_back();
3690     }
3691 
3692     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3693                           FieldDecl *Field, const Type *BaseClass) {
3694       // Remove Decls that may have been initialized in the previous
3695       // initializer.
3696       for (ValueDecl* VD : DeclsToRemove)
3697         Decls.erase(VD);
3698       DeclsToRemove.clear();
3699 
3700       Constructor = FieldConstructor;
3701       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3702 
3703       if (ILE && Field) {
3704         InitList = true;
3705         InitListFieldDecl = Field;
3706         InitFieldIndex.clear();
3707         CheckInitListExpr(ILE);
3708       } else {
3709         InitList = false;
3710         Visit(E);
3711       }
3712 
3713       if (Field)
3714         Decls.erase(Field);
3715       if (BaseClass)
3716         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3717     }
3718 
3719     void VisitMemberExpr(MemberExpr *ME) {
3720       // All uses of unbounded reference fields will warn.
3721       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3722     }
3723 
3724     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3725       if (E->getCastKind() == CK_LValueToRValue) {
3726         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3727         return;
3728       }
3729 
3730       Inherited::VisitImplicitCastExpr(E);
3731     }
3732 
3733     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3734       if (E->getConstructor()->isCopyConstructor()) {
3735         Expr *ArgExpr = E->getArg(0);
3736         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3737           if (ILE->getNumInits() == 1)
3738             ArgExpr = ILE->getInit(0);
3739         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3740           if (ICE->getCastKind() == CK_NoOp)
3741             ArgExpr = ICE->getSubExpr();
3742         HandleValue(ArgExpr, false /*AddressOf*/);
3743         return;
3744       }
3745       Inherited::VisitCXXConstructExpr(E);
3746     }
3747 
3748     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3749       Expr *Callee = E->getCallee();
3750       if (isa<MemberExpr>(Callee)) {
3751         HandleValue(Callee, false /*AddressOf*/);
3752         for (auto Arg : E->arguments())
3753           Visit(Arg);
3754         return;
3755       }
3756 
3757       Inherited::VisitCXXMemberCallExpr(E);
3758     }
3759 
3760     void VisitCallExpr(CallExpr *E) {
3761       // Treat std::move as a use.
3762       if (E->isCallToStdMove()) {
3763         HandleValue(E->getArg(0), /*AddressOf=*/false);
3764         return;
3765       }
3766 
3767       Inherited::VisitCallExpr(E);
3768     }
3769 
3770     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3771       Expr *Callee = E->getCallee();
3772 
3773       if (isa<UnresolvedLookupExpr>(Callee))
3774         return Inherited::VisitCXXOperatorCallExpr(E);
3775 
3776       Visit(Callee);
3777       for (auto Arg : E->arguments())
3778         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3779     }
3780 
3781     void VisitBinaryOperator(BinaryOperator *E) {
3782       // If a field assignment is detected, remove the field from the
3783       // uninitiailized field set.
3784       if (E->getOpcode() == BO_Assign)
3785         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3786           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3787             if (!FD->getType()->isReferenceType())
3788               DeclsToRemove.push_back(FD);
3789 
3790       if (E->isCompoundAssignmentOp()) {
3791         HandleValue(E->getLHS(), false /*AddressOf*/);
3792         Visit(E->getRHS());
3793         return;
3794       }
3795 
3796       Inherited::VisitBinaryOperator(E);
3797     }
3798 
3799     void VisitUnaryOperator(UnaryOperator *E) {
3800       if (E->isIncrementDecrementOp()) {
3801         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3802         return;
3803       }
3804       if (E->getOpcode() == UO_AddrOf) {
3805         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3806           HandleValue(ME->getBase(), true /*AddressOf*/);
3807           return;
3808         }
3809       }
3810 
3811       Inherited::VisitUnaryOperator(E);
3812     }
3813   };
3814 
3815   // Diagnose value-uses of fields to initialize themselves, e.g.
3816   //   foo(foo)
3817   // where foo is not also a parameter to the constructor.
3818   // Also diagnose across field uninitialized use such as
3819   //   x(y), y(x)
3820   // TODO: implement -Wuninitialized and fold this into that framework.
3821   static void DiagnoseUninitializedFields(
3822       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3823 
3824     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3825                                            Constructor->getLocation())) {
3826       return;
3827     }
3828 
3829     if (Constructor->isInvalidDecl())
3830       return;
3831 
3832     const CXXRecordDecl *RD = Constructor->getParent();
3833 
3834     if (RD->isDependentContext())
3835       return;
3836 
3837     // Holds fields that are uninitialized.
3838     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3839 
3840     // At the beginning, all fields are uninitialized.
3841     for (auto *I : RD->decls()) {
3842       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3843         UninitializedFields.insert(FD);
3844       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3845         UninitializedFields.insert(IFD->getAnonField());
3846       }
3847     }
3848 
3849     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3850     for (auto I : RD->bases())
3851       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3852 
3853     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3854       return;
3855 
3856     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3857                                                    UninitializedFields,
3858                                                    UninitializedBaseClasses);
3859 
3860     for (const auto *FieldInit : Constructor->inits()) {
3861       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3862         break;
3863 
3864       Expr *InitExpr = FieldInit->getInit();
3865       if (!InitExpr)
3866         continue;
3867 
3868       if (CXXDefaultInitExpr *Default =
3869               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3870         InitExpr = Default->getExpr();
3871         if (!InitExpr)
3872           continue;
3873         // In class initializers will point to the constructor.
3874         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3875                                               FieldInit->getAnyMember(),
3876                                               FieldInit->getBaseClass());
3877       } else {
3878         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3879                                               FieldInit->getAnyMember(),
3880                                               FieldInit->getBaseClass());
3881       }
3882     }
3883   }
3884 } // namespace
3885 
3886 /// Enter a new C++ default initializer scope. After calling this, the
3887 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3888 /// parsing or instantiating the initializer failed.
3889 void Sema::ActOnStartCXXInClassMemberInitializer() {
3890   // Create a synthetic function scope to represent the call to the constructor
3891   // that notionally surrounds a use of this initializer.
3892   PushFunctionScope();
3893 }
3894 
3895 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3896   if (!D.isFunctionDeclarator())
3897     return;
3898   auto &FTI = D.getFunctionTypeInfo();
3899   if (!FTI.Params)
3900     return;
3901   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3902                                                           FTI.NumParams)) {
3903     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3904     if (ParamDecl->getDeclName())
3905       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3906   }
3907 }
3908 
3909 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3910   if (ConstraintExpr.isInvalid())
3911     return ExprError();
3912   return CorrectDelayedTyposInExpr(ConstraintExpr);
3913 }
3914 
3915 /// This is invoked after parsing an in-class initializer for a
3916 /// non-static C++ class member, and after instantiating an in-class initializer
3917 /// in a class template. Such actions are deferred until the class is complete.
3918 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3919                                                   SourceLocation InitLoc,
3920                                                   Expr *InitExpr) {
3921   // Pop the notional constructor scope we created earlier.
3922   PopFunctionScopeInfo(nullptr, D);
3923 
3924   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3925   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3926          "must set init style when field is created");
3927 
3928   if (!InitExpr) {
3929     D->setInvalidDecl();
3930     if (FD)
3931       FD->removeInClassInitializer();
3932     return;
3933   }
3934 
3935   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3936     FD->setInvalidDecl();
3937     FD->removeInClassInitializer();
3938     return;
3939   }
3940 
3941   ExprResult Init = InitExpr;
3942   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3943     InitializedEntity Entity =
3944         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3945     InitializationKind Kind =
3946         FD->getInClassInitStyle() == ICIS_ListInit
3947             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3948                                                    InitExpr->getBeginLoc(),
3949                                                    InitExpr->getEndLoc())
3950             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3951     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3952     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3953     if (Init.isInvalid()) {
3954       FD->setInvalidDecl();
3955       return;
3956     }
3957   }
3958 
3959   // C++11 [class.base.init]p7:
3960   //   The initialization of each base and member constitutes a
3961   //   full-expression.
3962   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3963   if (Init.isInvalid()) {
3964     FD->setInvalidDecl();
3965     return;
3966   }
3967 
3968   InitExpr = Init.get();
3969 
3970   FD->setInClassInitializer(InitExpr);
3971 }
3972 
3973 /// Find the direct and/or virtual base specifiers that
3974 /// correspond to the given base type, for use in base initialization
3975 /// within a constructor.
3976 static bool FindBaseInitializer(Sema &SemaRef,
3977                                 CXXRecordDecl *ClassDecl,
3978                                 QualType BaseType,
3979                                 const CXXBaseSpecifier *&DirectBaseSpec,
3980                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3981   // First, check for a direct base class.
3982   DirectBaseSpec = nullptr;
3983   for (const auto &Base : ClassDecl->bases()) {
3984     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3985       // We found a direct base of this type. That's what we're
3986       // initializing.
3987       DirectBaseSpec = &Base;
3988       break;
3989     }
3990   }
3991 
3992   // Check for a virtual base class.
3993   // FIXME: We might be able to short-circuit this if we know in advance that
3994   // there are no virtual bases.
3995   VirtualBaseSpec = nullptr;
3996   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3997     // We haven't found a base yet; search the class hierarchy for a
3998     // virtual base class.
3999     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4000                        /*DetectVirtual=*/false);
4001     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4002                               SemaRef.Context.getTypeDeclType(ClassDecl),
4003                               BaseType, Paths)) {
4004       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4005            Path != Paths.end(); ++Path) {
4006         if (Path->back().Base->isVirtual()) {
4007           VirtualBaseSpec = Path->back().Base;
4008           break;
4009         }
4010       }
4011     }
4012   }
4013 
4014   return DirectBaseSpec || VirtualBaseSpec;
4015 }
4016 
4017 /// Handle a C++ member initializer using braced-init-list syntax.
4018 MemInitResult
4019 Sema::ActOnMemInitializer(Decl *ConstructorD,
4020                           Scope *S,
4021                           CXXScopeSpec &SS,
4022                           IdentifierInfo *MemberOrBase,
4023                           ParsedType TemplateTypeTy,
4024                           const DeclSpec &DS,
4025                           SourceLocation IdLoc,
4026                           Expr *InitList,
4027                           SourceLocation EllipsisLoc) {
4028   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4029                              DS, IdLoc, InitList,
4030                              EllipsisLoc);
4031 }
4032 
4033 /// Handle a C++ member initializer using parentheses syntax.
4034 MemInitResult
4035 Sema::ActOnMemInitializer(Decl *ConstructorD,
4036                           Scope *S,
4037                           CXXScopeSpec &SS,
4038                           IdentifierInfo *MemberOrBase,
4039                           ParsedType TemplateTypeTy,
4040                           const DeclSpec &DS,
4041                           SourceLocation IdLoc,
4042                           SourceLocation LParenLoc,
4043                           ArrayRef<Expr *> Args,
4044                           SourceLocation RParenLoc,
4045                           SourceLocation EllipsisLoc) {
4046   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4047   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4048                              DS, IdLoc, List, EllipsisLoc);
4049 }
4050 
4051 namespace {
4052 
4053 // Callback to only accept typo corrections that can be a valid C++ member
4054 // intializer: either a non-static field member or a base class.
4055 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4056 public:
4057   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4058       : ClassDecl(ClassDecl) {}
4059 
4060   bool ValidateCandidate(const TypoCorrection &candidate) override {
4061     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4062       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4063         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4064       return isa<TypeDecl>(ND);
4065     }
4066     return false;
4067   }
4068 
4069   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4070     return std::make_unique<MemInitializerValidatorCCC>(*this);
4071   }
4072 
4073 private:
4074   CXXRecordDecl *ClassDecl;
4075 };
4076 
4077 }
4078 
4079 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4080                                              CXXScopeSpec &SS,
4081                                              ParsedType TemplateTypeTy,
4082                                              IdentifierInfo *MemberOrBase) {
4083   if (SS.getScopeRep() || TemplateTypeTy)
4084     return nullptr;
4085   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4086   if (Result.empty())
4087     return nullptr;
4088   ValueDecl *Member;
4089   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4090       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4091     return Member;
4092   return nullptr;
4093 }
4094 
4095 /// Handle a C++ member initializer.
4096 MemInitResult
4097 Sema::BuildMemInitializer(Decl *ConstructorD,
4098                           Scope *S,
4099                           CXXScopeSpec &SS,
4100                           IdentifierInfo *MemberOrBase,
4101                           ParsedType TemplateTypeTy,
4102                           const DeclSpec &DS,
4103                           SourceLocation IdLoc,
4104                           Expr *Init,
4105                           SourceLocation EllipsisLoc) {
4106   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4107   if (!Res.isUsable())
4108     return true;
4109   Init = Res.get();
4110 
4111   if (!ConstructorD)
4112     return true;
4113 
4114   AdjustDeclIfTemplate(ConstructorD);
4115 
4116   CXXConstructorDecl *Constructor
4117     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4118   if (!Constructor) {
4119     // The user wrote a constructor initializer on a function that is
4120     // not a C++ constructor. Ignore the error for now, because we may
4121     // have more member initializers coming; we'll diagnose it just
4122     // once in ActOnMemInitializers.
4123     return true;
4124   }
4125 
4126   CXXRecordDecl *ClassDecl = Constructor->getParent();
4127 
4128   // C++ [class.base.init]p2:
4129   //   Names in a mem-initializer-id are looked up in the scope of the
4130   //   constructor's class and, if not found in that scope, are looked
4131   //   up in the scope containing the constructor's definition.
4132   //   [Note: if the constructor's class contains a member with the
4133   //   same name as a direct or virtual base class of the class, a
4134   //   mem-initializer-id naming the member or base class and composed
4135   //   of a single identifier refers to the class member. A
4136   //   mem-initializer-id for the hidden base class may be specified
4137   //   using a qualified name. ]
4138 
4139   // Look for a member, first.
4140   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4141           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4142     if (EllipsisLoc.isValid())
4143       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4144           << MemberOrBase
4145           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4146 
4147     return BuildMemberInitializer(Member, Init, IdLoc);
4148   }
4149   // It didn't name a member, so see if it names a class.
4150   QualType BaseType;
4151   TypeSourceInfo *TInfo = nullptr;
4152 
4153   if (TemplateTypeTy) {
4154     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4155     if (BaseType.isNull())
4156       return true;
4157   } else if (DS.getTypeSpecType() == TST_decltype) {
4158     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4159   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4160     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4161     return true;
4162   } else {
4163     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4164     LookupParsedName(R, S, &SS);
4165 
4166     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4167     if (!TyD) {
4168       if (R.isAmbiguous()) return true;
4169 
4170       // We don't want access-control diagnostics here.
4171       R.suppressDiagnostics();
4172 
4173       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4174         bool NotUnknownSpecialization = false;
4175         DeclContext *DC = computeDeclContext(SS, false);
4176         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4177           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4178 
4179         if (!NotUnknownSpecialization) {
4180           // When the scope specifier can refer to a member of an unknown
4181           // specialization, we take it as a type name.
4182           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4183                                        SS.getWithLocInContext(Context),
4184                                        *MemberOrBase, IdLoc);
4185           if (BaseType.isNull())
4186             return true;
4187 
4188           TInfo = Context.CreateTypeSourceInfo(BaseType);
4189           DependentNameTypeLoc TL =
4190               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4191           if (!TL.isNull()) {
4192             TL.setNameLoc(IdLoc);
4193             TL.setElaboratedKeywordLoc(SourceLocation());
4194             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4195           }
4196 
4197           R.clear();
4198           R.setLookupName(MemberOrBase);
4199         }
4200       }
4201 
4202       // If no results were found, try to correct typos.
4203       TypoCorrection Corr;
4204       MemInitializerValidatorCCC CCC(ClassDecl);
4205       if (R.empty() && BaseType.isNull() &&
4206           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4207                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4208         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4209           // We have found a non-static data member with a similar
4210           // name to what was typed; complain and initialize that
4211           // member.
4212           diagnoseTypo(Corr,
4213                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4214                          << MemberOrBase << true);
4215           return BuildMemberInitializer(Member, Init, IdLoc);
4216         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4217           const CXXBaseSpecifier *DirectBaseSpec;
4218           const CXXBaseSpecifier *VirtualBaseSpec;
4219           if (FindBaseInitializer(*this, ClassDecl,
4220                                   Context.getTypeDeclType(Type),
4221                                   DirectBaseSpec, VirtualBaseSpec)) {
4222             // We have found a direct or virtual base class with a
4223             // similar name to what was typed; complain and initialize
4224             // that base class.
4225             diagnoseTypo(Corr,
4226                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4227                            << MemberOrBase << false,
4228                          PDiag() /*Suppress note, we provide our own.*/);
4229 
4230             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4231                                                               : VirtualBaseSpec;
4232             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4233                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4234 
4235             TyD = Type;
4236           }
4237         }
4238       }
4239 
4240       if (!TyD && BaseType.isNull()) {
4241         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4242           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4243         return true;
4244       }
4245     }
4246 
4247     if (BaseType.isNull()) {
4248       BaseType = Context.getTypeDeclType(TyD);
4249       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4250       if (SS.isSet()) {
4251         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4252                                              BaseType);
4253         TInfo = Context.CreateTypeSourceInfo(BaseType);
4254         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4255         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4256         TL.setElaboratedKeywordLoc(SourceLocation());
4257         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4258       }
4259     }
4260   }
4261 
4262   if (!TInfo)
4263     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4264 
4265   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4266 }
4267 
4268 MemInitResult
4269 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4270                              SourceLocation IdLoc) {
4271   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4272   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4273   assert((DirectMember || IndirectMember) &&
4274          "Member must be a FieldDecl or IndirectFieldDecl");
4275 
4276   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4277     return true;
4278 
4279   if (Member->isInvalidDecl())
4280     return true;
4281 
4282   MultiExprArg Args;
4283   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4284     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4285   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4286     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4287   } else {
4288     // Template instantiation doesn't reconstruct ParenListExprs for us.
4289     Args = Init;
4290   }
4291 
4292   SourceRange InitRange = Init->getSourceRange();
4293 
4294   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4295     // Can't check initialization for a member of dependent type or when
4296     // any of the arguments are type-dependent expressions.
4297     DiscardCleanupsInEvaluationContext();
4298   } else {
4299     bool InitList = false;
4300     if (isa<InitListExpr>(Init)) {
4301       InitList = true;
4302       Args = Init;
4303     }
4304 
4305     // Initialize the member.
4306     InitializedEntity MemberEntity =
4307       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4308                    : InitializedEntity::InitializeMember(IndirectMember,
4309                                                          nullptr);
4310     InitializationKind Kind =
4311         InitList ? InitializationKind::CreateDirectList(
4312                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4313                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4314                                                     InitRange.getEnd());
4315 
4316     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4317     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4318                                             nullptr);
4319     if (MemberInit.isInvalid())
4320       return true;
4321 
4322     // C++11 [class.base.init]p7:
4323     //   The initialization of each base and member constitutes a
4324     //   full-expression.
4325     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4326                                      /*DiscardedValue*/ false);
4327     if (MemberInit.isInvalid())
4328       return true;
4329 
4330     Init = MemberInit.get();
4331   }
4332 
4333   if (DirectMember) {
4334     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4335                                             InitRange.getBegin(), Init,
4336                                             InitRange.getEnd());
4337   } else {
4338     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4339                                             InitRange.getBegin(), Init,
4340                                             InitRange.getEnd());
4341   }
4342 }
4343 
4344 MemInitResult
4345 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4346                                  CXXRecordDecl *ClassDecl) {
4347   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4348   if (!LangOpts.CPlusPlus11)
4349     return Diag(NameLoc, diag::err_delegating_ctor)
4350       << TInfo->getTypeLoc().getLocalSourceRange();
4351   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4352 
4353   bool InitList = true;
4354   MultiExprArg Args = Init;
4355   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4356     InitList = false;
4357     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4358   }
4359 
4360   SourceRange InitRange = Init->getSourceRange();
4361   // Initialize the object.
4362   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4363                                      QualType(ClassDecl->getTypeForDecl(), 0));
4364   InitializationKind Kind =
4365       InitList ? InitializationKind::CreateDirectList(
4366                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4367                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4368                                                   InitRange.getEnd());
4369   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4370   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4371                                               Args, nullptr);
4372   if (DelegationInit.isInvalid())
4373     return true;
4374 
4375   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4376          "Delegating constructor with no target?");
4377 
4378   // C++11 [class.base.init]p7:
4379   //   The initialization of each base and member constitutes a
4380   //   full-expression.
4381   DelegationInit = ActOnFinishFullExpr(
4382       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4383   if (DelegationInit.isInvalid())
4384     return true;
4385 
4386   // If we are in a dependent context, template instantiation will
4387   // perform this type-checking again. Just save the arguments that we
4388   // received in a ParenListExpr.
4389   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4390   // of the information that we have about the base
4391   // initializer. However, deconstructing the ASTs is a dicey process,
4392   // and this approach is far more likely to get the corner cases right.
4393   if (CurContext->isDependentContext())
4394     DelegationInit = Init;
4395 
4396   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4397                                           DelegationInit.getAs<Expr>(),
4398                                           InitRange.getEnd());
4399 }
4400 
4401 MemInitResult
4402 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4403                            Expr *Init, CXXRecordDecl *ClassDecl,
4404                            SourceLocation EllipsisLoc) {
4405   SourceLocation BaseLoc
4406     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4407 
4408   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4409     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4410              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4411 
4412   // C++ [class.base.init]p2:
4413   //   [...] Unless the mem-initializer-id names a nonstatic data
4414   //   member of the constructor's class or a direct or virtual base
4415   //   of that class, the mem-initializer is ill-formed. A
4416   //   mem-initializer-list can initialize a base class using any
4417   //   name that denotes that base class type.
4418   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4419 
4420   SourceRange InitRange = Init->getSourceRange();
4421   if (EllipsisLoc.isValid()) {
4422     // This is a pack expansion.
4423     if (!BaseType->containsUnexpandedParameterPack())  {
4424       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4425         << SourceRange(BaseLoc, InitRange.getEnd());
4426 
4427       EllipsisLoc = SourceLocation();
4428     }
4429   } else {
4430     // Check for any unexpanded parameter packs.
4431     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4432       return true;
4433 
4434     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4435       return true;
4436   }
4437 
4438   // Check for direct and virtual base classes.
4439   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4440   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4441   if (!Dependent) {
4442     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4443                                        BaseType))
4444       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4445 
4446     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4447                         VirtualBaseSpec);
4448 
4449     // C++ [base.class.init]p2:
4450     // Unless the mem-initializer-id names a nonstatic data member of the
4451     // constructor's class or a direct or virtual base of that class, the
4452     // mem-initializer is ill-formed.
4453     if (!DirectBaseSpec && !VirtualBaseSpec) {
4454       // If the class has any dependent bases, then it's possible that
4455       // one of those types will resolve to the same type as
4456       // BaseType. Therefore, just treat this as a dependent base
4457       // class initialization.  FIXME: Should we try to check the
4458       // initialization anyway? It seems odd.
4459       if (ClassDecl->hasAnyDependentBases())
4460         Dependent = true;
4461       else
4462         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4463           << BaseType << Context.getTypeDeclType(ClassDecl)
4464           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4465     }
4466   }
4467 
4468   if (Dependent) {
4469     DiscardCleanupsInEvaluationContext();
4470 
4471     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4472                                             /*IsVirtual=*/false,
4473                                             InitRange.getBegin(), Init,
4474                                             InitRange.getEnd(), EllipsisLoc);
4475   }
4476 
4477   // C++ [base.class.init]p2:
4478   //   If a mem-initializer-id is ambiguous because it designates both
4479   //   a direct non-virtual base class and an inherited virtual base
4480   //   class, the mem-initializer is ill-formed.
4481   if (DirectBaseSpec && VirtualBaseSpec)
4482     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4483       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4484 
4485   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4486   if (!BaseSpec)
4487     BaseSpec = VirtualBaseSpec;
4488 
4489   // Initialize the base.
4490   bool InitList = true;
4491   MultiExprArg Args = Init;
4492   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4493     InitList = false;
4494     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4495   }
4496 
4497   InitializedEntity BaseEntity =
4498     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4499   InitializationKind Kind =
4500       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4501                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4502                                                   InitRange.getEnd());
4503   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4504   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4505   if (BaseInit.isInvalid())
4506     return true;
4507 
4508   // C++11 [class.base.init]p7:
4509   //   The initialization of each base and member constitutes a
4510   //   full-expression.
4511   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4512                                  /*DiscardedValue*/ false);
4513   if (BaseInit.isInvalid())
4514     return true;
4515 
4516   // If we are in a dependent context, template instantiation will
4517   // perform this type-checking again. Just save the arguments that we
4518   // received in a ParenListExpr.
4519   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4520   // of the information that we have about the base
4521   // initializer. However, deconstructing the ASTs is a dicey process,
4522   // and this approach is far more likely to get the corner cases right.
4523   if (CurContext->isDependentContext())
4524     BaseInit = Init;
4525 
4526   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4527                                           BaseSpec->isVirtual(),
4528                                           InitRange.getBegin(),
4529                                           BaseInit.getAs<Expr>(),
4530                                           InitRange.getEnd(), EllipsisLoc);
4531 }
4532 
4533 // Create a static_cast\<T&&>(expr).
4534 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4535   if (T.isNull()) T = E->getType();
4536   QualType TargetType = SemaRef.BuildReferenceType(
4537       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4538   SourceLocation ExprLoc = E->getBeginLoc();
4539   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4540       TargetType, ExprLoc);
4541 
4542   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4543                                    SourceRange(ExprLoc, ExprLoc),
4544                                    E->getSourceRange()).get();
4545 }
4546 
4547 /// ImplicitInitializerKind - How an implicit base or member initializer should
4548 /// initialize its base or member.
4549 enum ImplicitInitializerKind {
4550   IIK_Default,
4551   IIK_Copy,
4552   IIK_Move,
4553   IIK_Inherit
4554 };
4555 
4556 static bool
4557 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4558                              ImplicitInitializerKind ImplicitInitKind,
4559                              CXXBaseSpecifier *BaseSpec,
4560                              bool IsInheritedVirtualBase,
4561                              CXXCtorInitializer *&CXXBaseInit) {
4562   InitializedEntity InitEntity
4563     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4564                                         IsInheritedVirtualBase);
4565 
4566   ExprResult BaseInit;
4567 
4568   switch (ImplicitInitKind) {
4569   case IIK_Inherit:
4570   case IIK_Default: {
4571     InitializationKind InitKind
4572       = InitializationKind::CreateDefault(Constructor->getLocation());
4573     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4574     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4575     break;
4576   }
4577 
4578   case IIK_Move:
4579   case IIK_Copy: {
4580     bool Moving = ImplicitInitKind == IIK_Move;
4581     ParmVarDecl *Param = Constructor->getParamDecl(0);
4582     QualType ParamType = Param->getType().getNonReferenceType();
4583 
4584     Expr *CopyCtorArg =
4585       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4586                           SourceLocation(), Param, false,
4587                           Constructor->getLocation(), ParamType,
4588                           VK_LValue, nullptr);
4589 
4590     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4591 
4592     // Cast to the base class to avoid ambiguities.
4593     QualType ArgTy =
4594       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4595                                        ParamType.getQualifiers());
4596 
4597     if (Moving) {
4598       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4599     }
4600 
4601     CXXCastPath BasePath;
4602     BasePath.push_back(BaseSpec);
4603     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4604                                             CK_UncheckedDerivedToBase,
4605                                             Moving ? VK_XValue : VK_LValue,
4606                                             &BasePath).get();
4607 
4608     InitializationKind InitKind
4609       = InitializationKind::CreateDirect(Constructor->getLocation(),
4610                                          SourceLocation(), SourceLocation());
4611     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4612     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4613     break;
4614   }
4615   }
4616 
4617   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4618   if (BaseInit.isInvalid())
4619     return true;
4620 
4621   CXXBaseInit =
4622     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4623                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4624                                                         SourceLocation()),
4625                                              BaseSpec->isVirtual(),
4626                                              SourceLocation(),
4627                                              BaseInit.getAs<Expr>(),
4628                                              SourceLocation(),
4629                                              SourceLocation());
4630 
4631   return false;
4632 }
4633 
4634 static bool RefersToRValueRef(Expr *MemRef) {
4635   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4636   return Referenced->getType()->isRValueReferenceType();
4637 }
4638 
4639 static bool
4640 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4641                                ImplicitInitializerKind ImplicitInitKind,
4642                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4643                                CXXCtorInitializer *&CXXMemberInit) {
4644   if (Field->isInvalidDecl())
4645     return true;
4646 
4647   SourceLocation Loc = Constructor->getLocation();
4648 
4649   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4650     bool Moving = ImplicitInitKind == IIK_Move;
4651     ParmVarDecl *Param = Constructor->getParamDecl(0);
4652     QualType ParamType = Param->getType().getNonReferenceType();
4653 
4654     // Suppress copying zero-width bitfields.
4655     if (Field->isZeroLengthBitField(SemaRef.Context))
4656       return false;
4657 
4658     Expr *MemberExprBase =
4659       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4660                           SourceLocation(), Param, false,
4661                           Loc, ParamType, VK_LValue, nullptr);
4662 
4663     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4664 
4665     if (Moving) {
4666       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4667     }
4668 
4669     // Build a reference to this field within the parameter.
4670     CXXScopeSpec SS;
4671     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4672                               Sema::LookupMemberName);
4673     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4674                                   : cast<ValueDecl>(Field), AS_public);
4675     MemberLookup.resolveKind();
4676     ExprResult CtorArg
4677       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4678                                          ParamType, Loc,
4679                                          /*IsArrow=*/false,
4680                                          SS,
4681                                          /*TemplateKWLoc=*/SourceLocation(),
4682                                          /*FirstQualifierInScope=*/nullptr,
4683                                          MemberLookup,
4684                                          /*TemplateArgs=*/nullptr,
4685                                          /*S*/nullptr);
4686     if (CtorArg.isInvalid())
4687       return true;
4688 
4689     // C++11 [class.copy]p15:
4690     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4691     //     with static_cast<T&&>(x.m);
4692     if (RefersToRValueRef(CtorArg.get())) {
4693       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4694     }
4695 
4696     InitializedEntity Entity =
4697         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4698                                                        /*Implicit*/ true)
4699                  : InitializedEntity::InitializeMember(Field, nullptr,
4700                                                        /*Implicit*/ true);
4701 
4702     // Direct-initialize to use the copy constructor.
4703     InitializationKind InitKind =
4704       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4705 
4706     Expr *CtorArgE = CtorArg.getAs<Expr>();
4707     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4708     ExprResult MemberInit =
4709         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4710     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4711     if (MemberInit.isInvalid())
4712       return true;
4713 
4714     if (Indirect)
4715       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4716           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4717     else
4718       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4719           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4720     return false;
4721   }
4722 
4723   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4724          "Unhandled implicit init kind!");
4725 
4726   QualType FieldBaseElementType =
4727     SemaRef.Context.getBaseElementType(Field->getType());
4728 
4729   if (FieldBaseElementType->isRecordType()) {
4730     InitializedEntity InitEntity =
4731         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4732                                                        /*Implicit*/ true)
4733                  : InitializedEntity::InitializeMember(Field, nullptr,
4734                                                        /*Implicit*/ true);
4735     InitializationKind InitKind =
4736       InitializationKind::CreateDefault(Loc);
4737 
4738     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4739     ExprResult MemberInit =
4740       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4741 
4742     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4743     if (MemberInit.isInvalid())
4744       return true;
4745 
4746     if (Indirect)
4747       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4748                                                                Indirect, Loc,
4749                                                                Loc,
4750                                                                MemberInit.get(),
4751                                                                Loc);
4752     else
4753       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4754                                                                Field, Loc, Loc,
4755                                                                MemberInit.get(),
4756                                                                Loc);
4757     return false;
4758   }
4759 
4760   if (!Field->getParent()->isUnion()) {
4761     if (FieldBaseElementType->isReferenceType()) {
4762       SemaRef.Diag(Constructor->getLocation(),
4763                    diag::err_uninitialized_member_in_ctor)
4764       << (int)Constructor->isImplicit()
4765       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4766       << 0 << Field->getDeclName();
4767       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4768       return true;
4769     }
4770 
4771     if (FieldBaseElementType.isConstQualified()) {
4772       SemaRef.Diag(Constructor->getLocation(),
4773                    diag::err_uninitialized_member_in_ctor)
4774       << (int)Constructor->isImplicit()
4775       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4776       << 1 << Field->getDeclName();
4777       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4778       return true;
4779     }
4780   }
4781 
4782   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4783     // ARC and Weak:
4784     //   Default-initialize Objective-C pointers to NULL.
4785     CXXMemberInit
4786       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4787                                                  Loc, Loc,
4788                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4789                                                  Loc);
4790     return false;
4791   }
4792 
4793   // Nothing to initialize.
4794   CXXMemberInit = nullptr;
4795   return false;
4796 }
4797 
4798 namespace {
4799 struct BaseAndFieldInfo {
4800   Sema &S;
4801   CXXConstructorDecl *Ctor;
4802   bool AnyErrorsInInits;
4803   ImplicitInitializerKind IIK;
4804   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4805   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4806   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4807 
4808   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4809     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4810     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4811     if (Ctor->getInheritedConstructor())
4812       IIK = IIK_Inherit;
4813     else if (Generated && Ctor->isCopyConstructor())
4814       IIK = IIK_Copy;
4815     else if (Generated && Ctor->isMoveConstructor())
4816       IIK = IIK_Move;
4817     else
4818       IIK = IIK_Default;
4819   }
4820 
4821   bool isImplicitCopyOrMove() const {
4822     switch (IIK) {
4823     case IIK_Copy:
4824     case IIK_Move:
4825       return true;
4826 
4827     case IIK_Default:
4828     case IIK_Inherit:
4829       return false;
4830     }
4831 
4832     llvm_unreachable("Invalid ImplicitInitializerKind!");
4833   }
4834 
4835   bool addFieldInitializer(CXXCtorInitializer *Init) {
4836     AllToInit.push_back(Init);
4837 
4838     // Check whether this initializer makes the field "used".
4839     if (Init->getInit()->HasSideEffects(S.Context))
4840       S.UnusedPrivateFields.remove(Init->getAnyMember());
4841 
4842     return false;
4843   }
4844 
4845   bool isInactiveUnionMember(FieldDecl *Field) {
4846     RecordDecl *Record = Field->getParent();
4847     if (!Record->isUnion())
4848       return false;
4849 
4850     if (FieldDecl *Active =
4851             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4852       return Active != Field->getCanonicalDecl();
4853 
4854     // In an implicit copy or move constructor, ignore any in-class initializer.
4855     if (isImplicitCopyOrMove())
4856       return true;
4857 
4858     // If there's no explicit initialization, the field is active only if it
4859     // has an in-class initializer...
4860     if (Field->hasInClassInitializer())
4861       return false;
4862     // ... or it's an anonymous struct or union whose class has an in-class
4863     // initializer.
4864     if (!Field->isAnonymousStructOrUnion())
4865       return true;
4866     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4867     return !FieldRD->hasInClassInitializer();
4868   }
4869 
4870   /// Determine whether the given field is, or is within, a union member
4871   /// that is inactive (because there was an initializer given for a different
4872   /// member of the union, or because the union was not initialized at all).
4873   bool isWithinInactiveUnionMember(FieldDecl *Field,
4874                                    IndirectFieldDecl *Indirect) {
4875     if (!Indirect)
4876       return isInactiveUnionMember(Field);
4877 
4878     for (auto *C : Indirect->chain()) {
4879       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4880       if (Field && isInactiveUnionMember(Field))
4881         return true;
4882     }
4883     return false;
4884   }
4885 };
4886 }
4887 
4888 /// Determine whether the given type is an incomplete or zero-lenfgth
4889 /// array type.
4890 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4891   if (T->isIncompleteArrayType())
4892     return true;
4893 
4894   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4895     if (!ArrayT->getSize())
4896       return true;
4897 
4898     T = ArrayT->getElementType();
4899   }
4900 
4901   return false;
4902 }
4903 
4904 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4905                                     FieldDecl *Field,
4906                                     IndirectFieldDecl *Indirect = nullptr) {
4907   if (Field->isInvalidDecl())
4908     return false;
4909 
4910   // Overwhelmingly common case: we have a direct initializer for this field.
4911   if (CXXCtorInitializer *Init =
4912           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4913     return Info.addFieldInitializer(Init);
4914 
4915   // C++11 [class.base.init]p8:
4916   //   if the entity is a non-static data member that has a
4917   //   brace-or-equal-initializer and either
4918   //   -- the constructor's class is a union and no other variant member of that
4919   //      union is designated by a mem-initializer-id or
4920   //   -- the constructor's class is not a union, and, if the entity is a member
4921   //      of an anonymous union, no other member of that union is designated by
4922   //      a mem-initializer-id,
4923   //   the entity is initialized as specified in [dcl.init].
4924   //
4925   // We also apply the same rules to handle anonymous structs within anonymous
4926   // unions.
4927   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4928     return false;
4929 
4930   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4931     ExprResult DIE =
4932         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4933     if (DIE.isInvalid())
4934       return true;
4935 
4936     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4937     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4938 
4939     CXXCtorInitializer *Init;
4940     if (Indirect)
4941       Init = new (SemaRef.Context)
4942           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4943                              SourceLocation(), DIE.get(), SourceLocation());
4944     else
4945       Init = new (SemaRef.Context)
4946           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4947                              SourceLocation(), DIE.get(), SourceLocation());
4948     return Info.addFieldInitializer(Init);
4949   }
4950 
4951   // Don't initialize incomplete or zero-length arrays.
4952   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4953     return false;
4954 
4955   // Don't try to build an implicit initializer if there were semantic
4956   // errors in any of the initializers (and therefore we might be
4957   // missing some that the user actually wrote).
4958   if (Info.AnyErrorsInInits)
4959     return false;
4960 
4961   CXXCtorInitializer *Init = nullptr;
4962   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4963                                      Indirect, Init))
4964     return true;
4965 
4966   if (!Init)
4967     return false;
4968 
4969   return Info.addFieldInitializer(Init);
4970 }
4971 
4972 bool
4973 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4974                                CXXCtorInitializer *Initializer) {
4975   assert(Initializer->isDelegatingInitializer());
4976   Constructor->setNumCtorInitializers(1);
4977   CXXCtorInitializer **initializer =
4978     new (Context) CXXCtorInitializer*[1];
4979   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4980   Constructor->setCtorInitializers(initializer);
4981 
4982   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4983     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4984     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4985   }
4986 
4987   DelegatingCtorDecls.push_back(Constructor);
4988 
4989   DiagnoseUninitializedFields(*this, Constructor);
4990 
4991   return false;
4992 }
4993 
4994 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4995                                ArrayRef<CXXCtorInitializer *> Initializers) {
4996   if (Constructor->isDependentContext()) {
4997     // Just store the initializers as written, they will be checked during
4998     // instantiation.
4999     if (!Initializers.empty()) {
5000       Constructor->setNumCtorInitializers(Initializers.size());
5001       CXXCtorInitializer **baseOrMemberInitializers =
5002         new (Context) CXXCtorInitializer*[Initializers.size()];
5003       memcpy(baseOrMemberInitializers, Initializers.data(),
5004              Initializers.size() * sizeof(CXXCtorInitializer*));
5005       Constructor->setCtorInitializers(baseOrMemberInitializers);
5006     }
5007 
5008     // Let template instantiation know whether we had errors.
5009     if (AnyErrors)
5010       Constructor->setInvalidDecl();
5011 
5012     return false;
5013   }
5014 
5015   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5016 
5017   // We need to build the initializer AST according to order of construction
5018   // and not what user specified in the Initializers list.
5019   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5020   if (!ClassDecl)
5021     return true;
5022 
5023   bool HadError = false;
5024 
5025   for (unsigned i = 0; i < Initializers.size(); i++) {
5026     CXXCtorInitializer *Member = Initializers[i];
5027 
5028     if (Member->isBaseInitializer())
5029       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5030     else {
5031       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5032 
5033       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5034         for (auto *C : F->chain()) {
5035           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5036           if (FD && FD->getParent()->isUnion())
5037             Info.ActiveUnionMember.insert(std::make_pair(
5038                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5039         }
5040       } else if (FieldDecl *FD = Member->getMember()) {
5041         if (FD->getParent()->isUnion())
5042           Info.ActiveUnionMember.insert(std::make_pair(
5043               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5044       }
5045     }
5046   }
5047 
5048   // Keep track of the direct virtual bases.
5049   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5050   for (auto &I : ClassDecl->bases()) {
5051     if (I.isVirtual())
5052       DirectVBases.insert(&I);
5053   }
5054 
5055   // Push virtual bases before others.
5056   for (auto &VBase : ClassDecl->vbases()) {
5057     if (CXXCtorInitializer *Value
5058         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5059       // [class.base.init]p7, per DR257:
5060       //   A mem-initializer where the mem-initializer-id names a virtual base
5061       //   class is ignored during execution of a constructor of any class that
5062       //   is not the most derived class.
5063       if (ClassDecl->isAbstract()) {
5064         // FIXME: Provide a fixit to remove the base specifier. This requires
5065         // tracking the location of the associated comma for a base specifier.
5066         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5067           << VBase.getType() << ClassDecl;
5068         DiagnoseAbstractType(ClassDecl);
5069       }
5070 
5071       Info.AllToInit.push_back(Value);
5072     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5073       // [class.base.init]p8, per DR257:
5074       //   If a given [...] base class is not named by a mem-initializer-id
5075       //   [...] and the entity is not a virtual base class of an abstract
5076       //   class, then [...] the entity is default-initialized.
5077       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5078       CXXCtorInitializer *CXXBaseInit;
5079       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5080                                        &VBase, IsInheritedVirtualBase,
5081                                        CXXBaseInit)) {
5082         HadError = true;
5083         continue;
5084       }
5085 
5086       Info.AllToInit.push_back(CXXBaseInit);
5087     }
5088   }
5089 
5090   // Non-virtual bases.
5091   for (auto &Base : ClassDecl->bases()) {
5092     // Virtuals are in the virtual base list and already constructed.
5093     if (Base.isVirtual())
5094       continue;
5095 
5096     if (CXXCtorInitializer *Value
5097           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5098       Info.AllToInit.push_back(Value);
5099     } else if (!AnyErrors) {
5100       CXXCtorInitializer *CXXBaseInit;
5101       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5102                                        &Base, /*IsInheritedVirtualBase=*/false,
5103                                        CXXBaseInit)) {
5104         HadError = true;
5105         continue;
5106       }
5107 
5108       Info.AllToInit.push_back(CXXBaseInit);
5109     }
5110   }
5111 
5112   // Fields.
5113   for (auto *Mem : ClassDecl->decls()) {
5114     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5115       // C++ [class.bit]p2:
5116       //   A declaration for a bit-field that omits the identifier declares an
5117       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5118       //   initialized.
5119       if (F->isUnnamedBitfield())
5120         continue;
5121 
5122       // If we're not generating the implicit copy/move constructor, then we'll
5123       // handle anonymous struct/union fields based on their individual
5124       // indirect fields.
5125       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5126         continue;
5127 
5128       if (CollectFieldInitializer(*this, Info, F))
5129         HadError = true;
5130       continue;
5131     }
5132 
5133     // Beyond this point, we only consider default initialization.
5134     if (Info.isImplicitCopyOrMove())
5135       continue;
5136 
5137     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5138       if (F->getType()->isIncompleteArrayType()) {
5139         assert(ClassDecl->hasFlexibleArrayMember() &&
5140                "Incomplete array type is not valid");
5141         continue;
5142       }
5143 
5144       // Initialize each field of an anonymous struct individually.
5145       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5146         HadError = true;
5147 
5148       continue;
5149     }
5150   }
5151 
5152   unsigned NumInitializers = Info.AllToInit.size();
5153   if (NumInitializers > 0) {
5154     Constructor->setNumCtorInitializers(NumInitializers);
5155     CXXCtorInitializer **baseOrMemberInitializers =
5156       new (Context) CXXCtorInitializer*[NumInitializers];
5157     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5158            NumInitializers * sizeof(CXXCtorInitializer*));
5159     Constructor->setCtorInitializers(baseOrMemberInitializers);
5160 
5161     // Constructors implicitly reference the base and member
5162     // destructors.
5163     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5164                                            Constructor->getParent());
5165   }
5166 
5167   return HadError;
5168 }
5169 
5170 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5171   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5172     const RecordDecl *RD = RT->getDecl();
5173     if (RD->isAnonymousStructOrUnion()) {
5174       for (auto *Field : RD->fields())
5175         PopulateKeysForFields(Field, IdealInits);
5176       return;
5177     }
5178   }
5179   IdealInits.push_back(Field->getCanonicalDecl());
5180 }
5181 
5182 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5183   return Context.getCanonicalType(BaseType).getTypePtr();
5184 }
5185 
5186 static const void *GetKeyForMember(ASTContext &Context,
5187                                    CXXCtorInitializer *Member) {
5188   if (!Member->isAnyMemberInitializer())
5189     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5190 
5191   return Member->getAnyMember()->getCanonicalDecl();
5192 }
5193 
5194 static void DiagnoseBaseOrMemInitializerOrder(
5195     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5196     ArrayRef<CXXCtorInitializer *> Inits) {
5197   if (Constructor->getDeclContext()->isDependentContext())
5198     return;
5199 
5200   // Don't check initializers order unless the warning is enabled at the
5201   // location of at least one initializer.
5202   bool ShouldCheckOrder = false;
5203   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5204     CXXCtorInitializer *Init = Inits[InitIndex];
5205     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5206                                  Init->getSourceLocation())) {
5207       ShouldCheckOrder = true;
5208       break;
5209     }
5210   }
5211   if (!ShouldCheckOrder)
5212     return;
5213 
5214   // Build the list of bases and members in the order that they'll
5215   // actually be initialized.  The explicit initializers should be in
5216   // this same order but may be missing things.
5217   SmallVector<const void*, 32> IdealInitKeys;
5218 
5219   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5220 
5221   // 1. Virtual bases.
5222   for (const auto &VBase : ClassDecl->vbases())
5223     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5224 
5225   // 2. Non-virtual bases.
5226   for (const auto &Base : ClassDecl->bases()) {
5227     if (Base.isVirtual())
5228       continue;
5229     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5230   }
5231 
5232   // 3. Direct fields.
5233   for (auto *Field : ClassDecl->fields()) {
5234     if (Field->isUnnamedBitfield())
5235       continue;
5236 
5237     PopulateKeysForFields(Field, IdealInitKeys);
5238   }
5239 
5240   unsigned NumIdealInits = IdealInitKeys.size();
5241   unsigned IdealIndex = 0;
5242 
5243   CXXCtorInitializer *PrevInit = nullptr;
5244   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5245     CXXCtorInitializer *Init = Inits[InitIndex];
5246     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5247 
5248     // Scan forward to try to find this initializer in the idealized
5249     // initializers list.
5250     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5251       if (InitKey == IdealInitKeys[IdealIndex])
5252         break;
5253 
5254     // If we didn't find this initializer, it must be because we
5255     // scanned past it on a previous iteration.  That can only
5256     // happen if we're out of order;  emit a warning.
5257     if (IdealIndex == NumIdealInits && PrevInit) {
5258       Sema::SemaDiagnosticBuilder D =
5259         SemaRef.Diag(PrevInit->getSourceLocation(),
5260                      diag::warn_initializer_out_of_order);
5261 
5262       if (PrevInit->isAnyMemberInitializer())
5263         D << 0 << PrevInit->getAnyMember()->getDeclName();
5264       else
5265         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5266 
5267       if (Init->isAnyMemberInitializer())
5268         D << 0 << Init->getAnyMember()->getDeclName();
5269       else
5270         D << 1 << Init->getTypeSourceInfo()->getType();
5271 
5272       // Move back to the initializer's location in the ideal list.
5273       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5274         if (InitKey == IdealInitKeys[IdealIndex])
5275           break;
5276 
5277       assert(IdealIndex < NumIdealInits &&
5278              "initializer not found in initializer list");
5279     }
5280 
5281     PrevInit = Init;
5282   }
5283 }
5284 
5285 namespace {
5286 bool CheckRedundantInit(Sema &S,
5287                         CXXCtorInitializer *Init,
5288                         CXXCtorInitializer *&PrevInit) {
5289   if (!PrevInit) {
5290     PrevInit = Init;
5291     return false;
5292   }
5293 
5294   if (FieldDecl *Field = Init->getAnyMember())
5295     S.Diag(Init->getSourceLocation(),
5296            diag::err_multiple_mem_initialization)
5297       << Field->getDeclName()
5298       << Init->getSourceRange();
5299   else {
5300     const Type *BaseClass = Init->getBaseClass();
5301     assert(BaseClass && "neither field nor base");
5302     S.Diag(Init->getSourceLocation(),
5303            diag::err_multiple_base_initialization)
5304       << QualType(BaseClass, 0)
5305       << Init->getSourceRange();
5306   }
5307   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5308     << 0 << PrevInit->getSourceRange();
5309 
5310   return true;
5311 }
5312 
5313 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5314 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5315 
5316 bool CheckRedundantUnionInit(Sema &S,
5317                              CXXCtorInitializer *Init,
5318                              RedundantUnionMap &Unions) {
5319   FieldDecl *Field = Init->getAnyMember();
5320   RecordDecl *Parent = Field->getParent();
5321   NamedDecl *Child = Field;
5322 
5323   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5324     if (Parent->isUnion()) {
5325       UnionEntry &En = Unions[Parent];
5326       if (En.first && En.first != Child) {
5327         S.Diag(Init->getSourceLocation(),
5328                diag::err_multiple_mem_union_initialization)
5329           << Field->getDeclName()
5330           << Init->getSourceRange();
5331         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5332           << 0 << En.second->getSourceRange();
5333         return true;
5334       }
5335       if (!En.first) {
5336         En.first = Child;
5337         En.second = Init;
5338       }
5339       if (!Parent->isAnonymousStructOrUnion())
5340         return false;
5341     }
5342 
5343     Child = Parent;
5344     Parent = cast<RecordDecl>(Parent->getDeclContext());
5345   }
5346 
5347   return false;
5348 }
5349 }
5350 
5351 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5352 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5353                                 SourceLocation ColonLoc,
5354                                 ArrayRef<CXXCtorInitializer*> MemInits,
5355                                 bool AnyErrors) {
5356   if (!ConstructorDecl)
5357     return;
5358 
5359   AdjustDeclIfTemplate(ConstructorDecl);
5360 
5361   CXXConstructorDecl *Constructor
5362     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5363 
5364   if (!Constructor) {
5365     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5366     return;
5367   }
5368 
5369   // Mapping for the duplicate initializers check.
5370   // For member initializers, this is keyed with a FieldDecl*.
5371   // For base initializers, this is keyed with a Type*.
5372   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5373 
5374   // Mapping for the inconsistent anonymous-union initializers check.
5375   RedundantUnionMap MemberUnions;
5376 
5377   bool HadError = false;
5378   for (unsigned i = 0; i < MemInits.size(); i++) {
5379     CXXCtorInitializer *Init = MemInits[i];
5380 
5381     // Set the source order index.
5382     Init->setSourceOrder(i);
5383 
5384     if (Init->isAnyMemberInitializer()) {
5385       const void *Key = GetKeyForMember(Context, Init);
5386       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5387           CheckRedundantUnionInit(*this, Init, MemberUnions))
5388         HadError = true;
5389     } else if (Init->isBaseInitializer()) {
5390       const void *Key = GetKeyForMember(Context, Init);
5391       if (CheckRedundantInit(*this, Init, Members[Key]))
5392         HadError = true;
5393     } else {
5394       assert(Init->isDelegatingInitializer());
5395       // This must be the only initializer
5396       if (MemInits.size() != 1) {
5397         Diag(Init->getSourceLocation(),
5398              diag::err_delegating_initializer_alone)
5399           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5400         // We will treat this as being the only initializer.
5401       }
5402       SetDelegatingInitializer(Constructor, MemInits[i]);
5403       // Return immediately as the initializer is set.
5404       return;
5405     }
5406   }
5407 
5408   if (HadError)
5409     return;
5410 
5411   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5412 
5413   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5414 
5415   DiagnoseUninitializedFields(*this, Constructor);
5416 }
5417 
5418 void
5419 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5420                                              CXXRecordDecl *ClassDecl) {
5421   // Ignore dependent contexts. Also ignore unions, since their members never
5422   // have destructors implicitly called.
5423   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5424     return;
5425 
5426   // FIXME: all the access-control diagnostics are positioned on the
5427   // field/base declaration.  That's probably good; that said, the
5428   // user might reasonably want to know why the destructor is being
5429   // emitted, and we currently don't say.
5430 
5431   // Non-static data members.
5432   for (auto *Field : ClassDecl->fields()) {
5433     if (Field->isInvalidDecl())
5434       continue;
5435 
5436     // Don't destroy incomplete or zero-length arrays.
5437     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5438       continue;
5439 
5440     QualType FieldType = Context.getBaseElementType(Field->getType());
5441 
5442     const RecordType* RT = FieldType->getAs<RecordType>();
5443     if (!RT)
5444       continue;
5445 
5446     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5447     if (FieldClassDecl->isInvalidDecl())
5448       continue;
5449     if (FieldClassDecl->hasIrrelevantDestructor())
5450       continue;
5451     // The destructor for an implicit anonymous union member is never invoked.
5452     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5453       continue;
5454 
5455     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5456     assert(Dtor && "No dtor found for FieldClassDecl!");
5457     CheckDestructorAccess(Field->getLocation(), Dtor,
5458                           PDiag(diag::err_access_dtor_field)
5459                             << Field->getDeclName()
5460                             << FieldType);
5461 
5462     MarkFunctionReferenced(Location, Dtor);
5463     DiagnoseUseOfDecl(Dtor, Location);
5464   }
5465 
5466   // We only potentially invoke the destructors of potentially constructed
5467   // subobjects.
5468   bool VisitVirtualBases = !ClassDecl->isAbstract();
5469 
5470   // If the destructor exists and has already been marked used in the MS ABI,
5471   // then virtual base destructors have already been checked and marked used.
5472   // Skip checking them again to avoid duplicate diagnostics.
5473   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5474     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5475     if (Dtor && Dtor->isUsed())
5476       VisitVirtualBases = false;
5477   }
5478 
5479   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5480 
5481   // Bases.
5482   for (const auto &Base : ClassDecl->bases()) {
5483     // Bases are always records in a well-formed non-dependent class.
5484     const RecordType *RT = Base.getType()->getAs<RecordType>();
5485 
5486     // Remember direct virtual bases.
5487     if (Base.isVirtual()) {
5488       if (!VisitVirtualBases)
5489         continue;
5490       DirectVirtualBases.insert(RT);
5491     }
5492 
5493     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5494     // If our base class is invalid, we probably can't get its dtor anyway.
5495     if (BaseClassDecl->isInvalidDecl())
5496       continue;
5497     if (BaseClassDecl->hasIrrelevantDestructor())
5498       continue;
5499 
5500     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5501     assert(Dtor && "No dtor found for BaseClassDecl!");
5502 
5503     // FIXME: caret should be on the start of the class name
5504     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5505                           PDiag(diag::err_access_dtor_base)
5506                               << Base.getType() << Base.getSourceRange(),
5507                           Context.getTypeDeclType(ClassDecl));
5508 
5509     MarkFunctionReferenced(Location, Dtor);
5510     DiagnoseUseOfDecl(Dtor, Location);
5511   }
5512 
5513   if (VisitVirtualBases)
5514     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5515                                          &DirectVirtualBases);
5516 }
5517 
5518 void Sema::MarkVirtualBaseDestructorsReferenced(
5519     SourceLocation Location, CXXRecordDecl *ClassDecl,
5520     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5521   // Virtual bases.
5522   for (const auto &VBase : ClassDecl->vbases()) {
5523     // Bases are always records in a well-formed non-dependent class.
5524     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5525 
5526     // Ignore already visited direct virtual bases.
5527     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5528       continue;
5529 
5530     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5531     // If our base class is invalid, we probably can't get its dtor anyway.
5532     if (BaseClassDecl->isInvalidDecl())
5533       continue;
5534     if (BaseClassDecl->hasIrrelevantDestructor())
5535       continue;
5536 
5537     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5538     assert(Dtor && "No dtor found for BaseClassDecl!");
5539     if (CheckDestructorAccess(
5540             ClassDecl->getLocation(), Dtor,
5541             PDiag(diag::err_access_dtor_vbase)
5542                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5543             Context.getTypeDeclType(ClassDecl)) ==
5544         AR_accessible) {
5545       CheckDerivedToBaseConversion(
5546           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5547           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5548           SourceRange(), DeclarationName(), nullptr);
5549     }
5550 
5551     MarkFunctionReferenced(Location, Dtor);
5552     DiagnoseUseOfDecl(Dtor, Location);
5553   }
5554 }
5555 
5556 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5557   if (!CDtorDecl)
5558     return;
5559 
5560   if (CXXConstructorDecl *Constructor
5561       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5562     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5563     DiagnoseUninitializedFields(*this, Constructor);
5564   }
5565 }
5566 
5567 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5568   if (!getLangOpts().CPlusPlus)
5569     return false;
5570 
5571   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5572   if (!RD)
5573     return false;
5574 
5575   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5576   // class template specialization here, but doing so breaks a lot of code.
5577 
5578   // We can't answer whether something is abstract until it has a
5579   // definition. If it's currently being defined, we'll walk back
5580   // over all the declarations when we have a full definition.
5581   const CXXRecordDecl *Def = RD->getDefinition();
5582   if (!Def || Def->isBeingDefined())
5583     return false;
5584 
5585   return RD->isAbstract();
5586 }
5587 
5588 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5589                                   TypeDiagnoser &Diagnoser) {
5590   if (!isAbstractType(Loc, T))
5591     return false;
5592 
5593   T = Context.getBaseElementType(T);
5594   Diagnoser.diagnose(*this, Loc, T);
5595   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5596   return true;
5597 }
5598 
5599 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5600   // Check if we've already emitted the list of pure virtual functions
5601   // for this class.
5602   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5603     return;
5604 
5605   // If the diagnostic is suppressed, don't emit the notes. We're only
5606   // going to emit them once, so try to attach them to a diagnostic we're
5607   // actually going to show.
5608   if (Diags.isLastDiagnosticIgnored())
5609     return;
5610 
5611   CXXFinalOverriderMap FinalOverriders;
5612   RD->getFinalOverriders(FinalOverriders);
5613 
5614   // Keep a set of seen pure methods so we won't diagnose the same method
5615   // more than once.
5616   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5617 
5618   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5619                                    MEnd = FinalOverriders.end();
5620        M != MEnd;
5621        ++M) {
5622     for (OverridingMethods::iterator SO = M->second.begin(),
5623                                   SOEnd = M->second.end();
5624          SO != SOEnd; ++SO) {
5625       // C++ [class.abstract]p4:
5626       //   A class is abstract if it contains or inherits at least one
5627       //   pure virtual function for which the final overrider is pure
5628       //   virtual.
5629 
5630       //
5631       if (SO->second.size() != 1)
5632         continue;
5633 
5634       if (!SO->second.front().Method->isPure())
5635         continue;
5636 
5637       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5638         continue;
5639 
5640       Diag(SO->second.front().Method->getLocation(),
5641            diag::note_pure_virtual_function)
5642         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5643     }
5644   }
5645 
5646   if (!PureVirtualClassDiagSet)
5647     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5648   PureVirtualClassDiagSet->insert(RD);
5649 }
5650 
5651 namespace {
5652 struct AbstractUsageInfo {
5653   Sema &S;
5654   CXXRecordDecl *Record;
5655   CanQualType AbstractType;
5656   bool Invalid;
5657 
5658   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5659     : S(S), Record(Record),
5660       AbstractType(S.Context.getCanonicalType(
5661                    S.Context.getTypeDeclType(Record))),
5662       Invalid(false) {}
5663 
5664   void DiagnoseAbstractType() {
5665     if (Invalid) return;
5666     S.DiagnoseAbstractType(Record);
5667     Invalid = true;
5668   }
5669 
5670   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5671 };
5672 
5673 struct CheckAbstractUsage {
5674   AbstractUsageInfo &Info;
5675   const NamedDecl *Ctx;
5676 
5677   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5678     : Info(Info), Ctx(Ctx) {}
5679 
5680   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5681     switch (TL.getTypeLocClass()) {
5682 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5683 #define TYPELOC(CLASS, PARENT) \
5684     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5685 #include "clang/AST/TypeLocNodes.def"
5686     }
5687   }
5688 
5689   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5690     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5691     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5692       if (!TL.getParam(I))
5693         continue;
5694 
5695       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5696       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5697     }
5698   }
5699 
5700   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5701     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5702   }
5703 
5704   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5705     // Visit the type parameters from a permissive context.
5706     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5707       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5708       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5709         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5710           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5711       // TODO: other template argument types?
5712     }
5713   }
5714 
5715   // Visit pointee types from a permissive context.
5716 #define CheckPolymorphic(Type) \
5717   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5718     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5719   }
5720   CheckPolymorphic(PointerTypeLoc)
5721   CheckPolymorphic(ReferenceTypeLoc)
5722   CheckPolymorphic(MemberPointerTypeLoc)
5723   CheckPolymorphic(BlockPointerTypeLoc)
5724   CheckPolymorphic(AtomicTypeLoc)
5725 
5726   /// Handle all the types we haven't given a more specific
5727   /// implementation for above.
5728   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5729     // Every other kind of type that we haven't called out already
5730     // that has an inner type is either (1) sugar or (2) contains that
5731     // inner type in some way as a subobject.
5732     if (TypeLoc Next = TL.getNextTypeLoc())
5733       return Visit(Next, Sel);
5734 
5735     // If there's no inner type and we're in a permissive context,
5736     // don't diagnose.
5737     if (Sel == Sema::AbstractNone) return;
5738 
5739     // Check whether the type matches the abstract type.
5740     QualType T = TL.getType();
5741     if (T->isArrayType()) {
5742       Sel = Sema::AbstractArrayType;
5743       T = Info.S.Context.getBaseElementType(T);
5744     }
5745     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5746     if (CT != Info.AbstractType) return;
5747 
5748     // It matched; do some magic.
5749     if (Sel == Sema::AbstractArrayType) {
5750       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5751         << T << TL.getSourceRange();
5752     } else {
5753       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5754         << Sel << T << TL.getSourceRange();
5755     }
5756     Info.DiagnoseAbstractType();
5757   }
5758 };
5759 
5760 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5761                                   Sema::AbstractDiagSelID Sel) {
5762   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5763 }
5764 
5765 }
5766 
5767 /// Check for invalid uses of an abstract type in a method declaration.
5768 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5769                                     CXXMethodDecl *MD) {
5770   // No need to do the check on definitions, which require that
5771   // the return/param types be complete.
5772   if (MD->doesThisDeclarationHaveABody())
5773     return;
5774 
5775   // For safety's sake, just ignore it if we don't have type source
5776   // information.  This should never happen for non-implicit methods,
5777   // but...
5778   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5779     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5780 }
5781 
5782 /// Check for invalid uses of an abstract type within a class definition.
5783 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5784                                     CXXRecordDecl *RD) {
5785   for (auto *D : RD->decls()) {
5786     if (D->isImplicit()) continue;
5787 
5788     // Methods and method templates.
5789     if (isa<CXXMethodDecl>(D)) {
5790       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5791     } else if (isa<FunctionTemplateDecl>(D)) {
5792       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5793       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5794 
5795     // Fields and static variables.
5796     } else if (isa<FieldDecl>(D)) {
5797       FieldDecl *FD = cast<FieldDecl>(D);
5798       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5799         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5800     } else if (isa<VarDecl>(D)) {
5801       VarDecl *VD = cast<VarDecl>(D);
5802       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5803         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5804 
5805     // Nested classes and class templates.
5806     } else if (isa<CXXRecordDecl>(D)) {
5807       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5808     } else if (isa<ClassTemplateDecl>(D)) {
5809       CheckAbstractClassUsage(Info,
5810                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5811     }
5812   }
5813 }
5814 
5815 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5816   Attr *ClassAttr = getDLLAttr(Class);
5817   if (!ClassAttr)
5818     return;
5819 
5820   assert(ClassAttr->getKind() == attr::DLLExport);
5821 
5822   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5823 
5824   if (TSK == TSK_ExplicitInstantiationDeclaration)
5825     // Don't go any further if this is just an explicit instantiation
5826     // declaration.
5827     return;
5828 
5829   // Add a context note to explain how we got to any diagnostics produced below.
5830   struct MarkingClassDllexported {
5831     Sema &S;
5832     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5833                             SourceLocation AttrLoc)
5834         : S(S) {
5835       Sema::CodeSynthesisContext Ctx;
5836       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5837       Ctx.PointOfInstantiation = AttrLoc;
5838       Ctx.Entity = Class;
5839       S.pushCodeSynthesisContext(Ctx);
5840     }
5841     ~MarkingClassDllexported() {
5842       S.popCodeSynthesisContext();
5843     }
5844   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5845 
5846   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5847     S.MarkVTableUsed(Class->getLocation(), Class, true);
5848 
5849   for (Decl *Member : Class->decls()) {
5850     // Defined static variables that are members of an exported base
5851     // class must be marked export too.
5852     auto *VD = dyn_cast<VarDecl>(Member);
5853     if (VD && Member->getAttr<DLLExportAttr>() &&
5854         VD->getStorageClass() == SC_Static &&
5855         TSK == TSK_ImplicitInstantiation)
5856       S.MarkVariableReferenced(VD->getLocation(), VD);
5857 
5858     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5859     if (!MD)
5860       continue;
5861 
5862     if (Member->getAttr<DLLExportAttr>()) {
5863       if (MD->isUserProvided()) {
5864         // Instantiate non-default class member functions ...
5865 
5866         // .. except for certain kinds of template specializations.
5867         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5868           continue;
5869 
5870         S.MarkFunctionReferenced(Class->getLocation(), MD);
5871 
5872         // The function will be passed to the consumer when its definition is
5873         // encountered.
5874       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5875                  MD->isCopyAssignmentOperator() ||
5876                  MD->isMoveAssignmentOperator()) {
5877         // Synthesize and instantiate non-trivial implicit methods, explicitly
5878         // defaulted methods, and the copy and move assignment operators. The
5879         // latter are exported even if they are trivial, because the address of
5880         // an operator can be taken and should compare equal across libraries.
5881         S.MarkFunctionReferenced(Class->getLocation(), MD);
5882 
5883         // There is no later point when we will see the definition of this
5884         // function, so pass it to the consumer now.
5885         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5886       }
5887     }
5888   }
5889 }
5890 
5891 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5892                                                         CXXRecordDecl *Class) {
5893   // Only the MS ABI has default constructor closures, so we don't need to do
5894   // this semantic checking anywhere else.
5895   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5896     return;
5897 
5898   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5899   for (Decl *Member : Class->decls()) {
5900     // Look for exported default constructors.
5901     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5902     if (!CD || !CD->isDefaultConstructor())
5903       continue;
5904     auto *Attr = CD->getAttr<DLLExportAttr>();
5905     if (!Attr)
5906       continue;
5907 
5908     // If the class is non-dependent, mark the default arguments as ODR-used so
5909     // that we can properly codegen the constructor closure.
5910     if (!Class->isDependentContext()) {
5911       for (ParmVarDecl *PD : CD->parameters()) {
5912         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5913         S.DiscardCleanupsInEvaluationContext();
5914       }
5915     }
5916 
5917     if (LastExportedDefaultCtor) {
5918       S.Diag(LastExportedDefaultCtor->getLocation(),
5919              diag::err_attribute_dll_ambiguous_default_ctor)
5920           << Class;
5921       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5922           << CD->getDeclName();
5923       return;
5924     }
5925     LastExportedDefaultCtor = CD;
5926   }
5927 }
5928 
5929 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5930                                                        CXXRecordDecl *Class) {
5931   bool ErrorReported = false;
5932   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5933                                                      ClassTemplateDecl *TD) {
5934     if (ErrorReported)
5935       return;
5936     S.Diag(TD->getLocation(),
5937            diag::err_cuda_device_builtin_surftex_cls_template)
5938         << /*surface*/ 0 << TD;
5939     ErrorReported = true;
5940   };
5941 
5942   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5943   if (!TD) {
5944     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5945     if (!SD) {
5946       S.Diag(Class->getLocation(),
5947              diag::err_cuda_device_builtin_surftex_ref_decl)
5948           << /*surface*/ 0 << Class;
5949       S.Diag(Class->getLocation(),
5950              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5951           << Class;
5952       return;
5953     }
5954     TD = SD->getSpecializedTemplate();
5955   }
5956 
5957   TemplateParameterList *Params = TD->getTemplateParameters();
5958   unsigned N = Params->size();
5959 
5960   if (N != 2) {
5961     reportIllegalClassTemplate(S, TD);
5962     S.Diag(TD->getLocation(),
5963            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5964         << TD << 2;
5965   }
5966   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5967     reportIllegalClassTemplate(S, TD);
5968     S.Diag(TD->getLocation(),
5969            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5970         << TD << /*1st*/ 0 << /*type*/ 0;
5971   }
5972   if (N > 1) {
5973     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5974     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5975       reportIllegalClassTemplate(S, TD);
5976       S.Diag(TD->getLocation(),
5977              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5978           << TD << /*2nd*/ 1 << /*integer*/ 1;
5979     }
5980   }
5981 }
5982 
5983 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5984                                                        CXXRecordDecl *Class) {
5985   bool ErrorReported = false;
5986   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5987                                                      ClassTemplateDecl *TD) {
5988     if (ErrorReported)
5989       return;
5990     S.Diag(TD->getLocation(),
5991            diag::err_cuda_device_builtin_surftex_cls_template)
5992         << /*texture*/ 1 << TD;
5993     ErrorReported = true;
5994   };
5995 
5996   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5997   if (!TD) {
5998     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5999     if (!SD) {
6000       S.Diag(Class->getLocation(),
6001              diag::err_cuda_device_builtin_surftex_ref_decl)
6002           << /*texture*/ 1 << Class;
6003       S.Diag(Class->getLocation(),
6004              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6005           << Class;
6006       return;
6007     }
6008     TD = SD->getSpecializedTemplate();
6009   }
6010 
6011   TemplateParameterList *Params = TD->getTemplateParameters();
6012   unsigned N = Params->size();
6013 
6014   if (N != 3) {
6015     reportIllegalClassTemplate(S, TD);
6016     S.Diag(TD->getLocation(),
6017            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6018         << TD << 3;
6019   }
6020   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6021     reportIllegalClassTemplate(S, TD);
6022     S.Diag(TD->getLocation(),
6023            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6024         << TD << /*1st*/ 0 << /*type*/ 0;
6025   }
6026   if (N > 1) {
6027     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6028     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6029       reportIllegalClassTemplate(S, TD);
6030       S.Diag(TD->getLocation(),
6031              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6032           << TD << /*2nd*/ 1 << /*integer*/ 1;
6033     }
6034   }
6035   if (N > 2) {
6036     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6037     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6038       reportIllegalClassTemplate(S, TD);
6039       S.Diag(TD->getLocation(),
6040              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6041           << TD << /*3rd*/ 2 << /*integer*/ 1;
6042     }
6043   }
6044 }
6045 
6046 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6047   // Mark any compiler-generated routines with the implicit code_seg attribute.
6048   for (auto *Method : Class->methods()) {
6049     if (Method->isUserProvided())
6050       continue;
6051     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6052       Method->addAttr(A);
6053   }
6054 }
6055 
6056 /// Check class-level dllimport/dllexport attribute.
6057 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6058   Attr *ClassAttr = getDLLAttr(Class);
6059 
6060   // MSVC inherits DLL attributes to partial class template specializations.
6061   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
6062     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6063       if (Attr *TemplateAttr =
6064               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6065         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6066         A->setInherited(true);
6067         ClassAttr = A;
6068       }
6069     }
6070   }
6071 
6072   if (!ClassAttr)
6073     return;
6074 
6075   if (!Class->isExternallyVisible()) {
6076     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6077         << Class << ClassAttr;
6078     return;
6079   }
6080 
6081   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6082       !ClassAttr->isInherited()) {
6083     // Diagnose dll attributes on members of class with dll attribute.
6084     for (Decl *Member : Class->decls()) {
6085       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6086         continue;
6087       InheritableAttr *MemberAttr = getDLLAttr(Member);
6088       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6089         continue;
6090 
6091       Diag(MemberAttr->getLocation(),
6092              diag::err_attribute_dll_member_of_dll_class)
6093           << MemberAttr << ClassAttr;
6094       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6095       Member->setInvalidDecl();
6096     }
6097   }
6098 
6099   if (Class->getDescribedClassTemplate())
6100     // Don't inherit dll attribute until the template is instantiated.
6101     return;
6102 
6103   // The class is either imported or exported.
6104   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6105 
6106   // Check if this was a dllimport attribute propagated from a derived class to
6107   // a base class template specialization. We don't apply these attributes to
6108   // static data members.
6109   const bool PropagatedImport =
6110       !ClassExported &&
6111       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6112 
6113   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6114 
6115   // Ignore explicit dllexport on explicit class template instantiation
6116   // declarations, except in MinGW mode.
6117   if (ClassExported && !ClassAttr->isInherited() &&
6118       TSK == TSK_ExplicitInstantiationDeclaration &&
6119       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6120     Class->dropAttr<DLLExportAttr>();
6121     return;
6122   }
6123 
6124   // Force declaration of implicit members so they can inherit the attribute.
6125   ForceDeclarationOfImplicitMembers(Class);
6126 
6127   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6128   // seem to be true in practice?
6129 
6130   for (Decl *Member : Class->decls()) {
6131     VarDecl *VD = dyn_cast<VarDecl>(Member);
6132     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6133 
6134     // Only methods and static fields inherit the attributes.
6135     if (!VD && !MD)
6136       continue;
6137 
6138     if (MD) {
6139       // Don't process deleted methods.
6140       if (MD->isDeleted())
6141         continue;
6142 
6143       if (MD->isInlined()) {
6144         // MinGW does not import or export inline methods. But do it for
6145         // template instantiations.
6146         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6147             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6148             TSK != TSK_ExplicitInstantiationDeclaration &&
6149             TSK != TSK_ExplicitInstantiationDefinition)
6150           continue;
6151 
6152         // MSVC versions before 2015 don't export the move assignment operators
6153         // and move constructor, so don't attempt to import/export them if
6154         // we have a definition.
6155         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6156         if ((MD->isMoveAssignmentOperator() ||
6157              (Ctor && Ctor->isMoveConstructor())) &&
6158             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6159           continue;
6160 
6161         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6162         // operator is exported anyway.
6163         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6164             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6165           continue;
6166       }
6167     }
6168 
6169     // Don't apply dllimport attributes to static data members of class template
6170     // instantiations when the attribute is propagated from a derived class.
6171     if (VD && PropagatedImport)
6172       continue;
6173 
6174     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6175       continue;
6176 
6177     if (!getDLLAttr(Member)) {
6178       InheritableAttr *NewAttr = nullptr;
6179 
6180       // Do not export/import inline function when -fno-dllexport-inlines is
6181       // passed. But add attribute for later local static var check.
6182       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6183           TSK != TSK_ExplicitInstantiationDeclaration &&
6184           TSK != TSK_ExplicitInstantiationDefinition) {
6185         if (ClassExported) {
6186           NewAttr = ::new (getASTContext())
6187               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6188         } else {
6189           NewAttr = ::new (getASTContext())
6190               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6191         }
6192       } else {
6193         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6194       }
6195 
6196       NewAttr->setInherited(true);
6197       Member->addAttr(NewAttr);
6198 
6199       if (MD) {
6200         // Propagate DLLAttr to friend re-declarations of MD that have already
6201         // been constructed.
6202         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6203              FD = FD->getPreviousDecl()) {
6204           if (FD->getFriendObjectKind() == Decl::FOK_None)
6205             continue;
6206           assert(!getDLLAttr(FD) &&
6207                  "friend re-decl should not already have a DLLAttr");
6208           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6209           NewAttr->setInherited(true);
6210           FD->addAttr(NewAttr);
6211         }
6212       }
6213     }
6214   }
6215 
6216   if (ClassExported)
6217     DelayedDllExportClasses.push_back(Class);
6218 }
6219 
6220 /// Perform propagation of DLL attributes from a derived class to a
6221 /// templated base class for MS compatibility.
6222 void Sema::propagateDLLAttrToBaseClassTemplate(
6223     CXXRecordDecl *Class, Attr *ClassAttr,
6224     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6225   if (getDLLAttr(
6226           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6227     // If the base class template has a DLL attribute, don't try to change it.
6228     return;
6229   }
6230 
6231   auto TSK = BaseTemplateSpec->getSpecializationKind();
6232   if (!getDLLAttr(BaseTemplateSpec) &&
6233       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6234        TSK == TSK_ImplicitInstantiation)) {
6235     // The template hasn't been instantiated yet (or it has, but only as an
6236     // explicit instantiation declaration or implicit instantiation, which means
6237     // we haven't codegenned any members yet), so propagate the attribute.
6238     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6239     NewAttr->setInherited(true);
6240     BaseTemplateSpec->addAttr(NewAttr);
6241 
6242     // If this was an import, mark that we propagated it from a derived class to
6243     // a base class template specialization.
6244     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6245       ImportAttr->setPropagatedToBaseTemplate();
6246 
6247     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6248     // needs to be run again to work see the new attribute. Otherwise this will
6249     // get run whenever the template is instantiated.
6250     if (TSK != TSK_Undeclared)
6251       checkClassLevelDLLAttribute(BaseTemplateSpec);
6252 
6253     return;
6254   }
6255 
6256   if (getDLLAttr(BaseTemplateSpec)) {
6257     // The template has already been specialized or instantiated with an
6258     // attribute, explicitly or through propagation. We should not try to change
6259     // it.
6260     return;
6261   }
6262 
6263   // The template was previously instantiated or explicitly specialized without
6264   // a dll attribute, It's too late for us to add an attribute, so warn that
6265   // this is unsupported.
6266   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6267       << BaseTemplateSpec->isExplicitSpecialization();
6268   Diag(ClassAttr->getLocation(), diag::note_attribute);
6269   if (BaseTemplateSpec->isExplicitSpecialization()) {
6270     Diag(BaseTemplateSpec->getLocation(),
6271            diag::note_template_class_explicit_specialization_was_here)
6272         << BaseTemplateSpec;
6273   } else {
6274     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6275            diag::note_template_class_instantiation_was_here)
6276         << BaseTemplateSpec;
6277   }
6278 }
6279 
6280 /// Determine the kind of defaulting that would be done for a given function.
6281 ///
6282 /// If the function is both a default constructor and a copy / move constructor
6283 /// (due to having a default argument for the first parameter), this picks
6284 /// CXXDefaultConstructor.
6285 ///
6286 /// FIXME: Check that case is properly handled by all callers.
6287 Sema::DefaultedFunctionKind
6288 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6289   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6290     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6291       if (Ctor->isDefaultConstructor())
6292         return Sema::CXXDefaultConstructor;
6293 
6294       if (Ctor->isCopyConstructor())
6295         return Sema::CXXCopyConstructor;
6296 
6297       if (Ctor->isMoveConstructor())
6298         return Sema::CXXMoveConstructor;
6299     }
6300 
6301     if (MD->isCopyAssignmentOperator())
6302       return Sema::CXXCopyAssignment;
6303 
6304     if (MD->isMoveAssignmentOperator())
6305       return Sema::CXXMoveAssignment;
6306 
6307     if (isa<CXXDestructorDecl>(FD))
6308       return Sema::CXXDestructor;
6309   }
6310 
6311   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6312   case OO_EqualEqual:
6313     return DefaultedComparisonKind::Equal;
6314 
6315   case OO_ExclaimEqual:
6316     return DefaultedComparisonKind::NotEqual;
6317 
6318   case OO_Spaceship:
6319     // No point allowing this if <=> doesn't exist in the current language mode.
6320     if (!getLangOpts().CPlusPlus20)
6321       break;
6322     return DefaultedComparisonKind::ThreeWay;
6323 
6324   case OO_Less:
6325   case OO_LessEqual:
6326   case OO_Greater:
6327   case OO_GreaterEqual:
6328     // No point allowing this if <=> doesn't exist in the current language mode.
6329     if (!getLangOpts().CPlusPlus20)
6330       break;
6331     return DefaultedComparisonKind::Relational;
6332 
6333   default:
6334     break;
6335   }
6336 
6337   // Not defaultable.
6338   return DefaultedFunctionKind();
6339 }
6340 
6341 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6342                                     SourceLocation DefaultLoc) {
6343   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6344   if (DFK.isComparison())
6345     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6346 
6347   switch (DFK.asSpecialMember()) {
6348   case Sema::CXXDefaultConstructor:
6349     S.DefineImplicitDefaultConstructor(DefaultLoc,
6350                                        cast<CXXConstructorDecl>(FD));
6351     break;
6352   case Sema::CXXCopyConstructor:
6353     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6354     break;
6355   case Sema::CXXCopyAssignment:
6356     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6357     break;
6358   case Sema::CXXDestructor:
6359     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6360     break;
6361   case Sema::CXXMoveConstructor:
6362     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6363     break;
6364   case Sema::CXXMoveAssignment:
6365     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6366     break;
6367   case Sema::CXXInvalid:
6368     llvm_unreachable("Invalid special member.");
6369   }
6370 }
6371 
6372 /// Determine whether a type is permitted to be passed or returned in
6373 /// registers, per C++ [class.temporary]p3.
6374 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6375                                TargetInfo::CallingConvKind CCK) {
6376   if (D->isDependentType() || D->isInvalidDecl())
6377     return false;
6378 
6379   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6380   // The PS4 platform ABI follows the behavior of Clang 3.2.
6381   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6382     return !D->hasNonTrivialDestructorForCall() &&
6383            !D->hasNonTrivialCopyConstructorForCall();
6384 
6385   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6386     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6387     bool DtorIsTrivialForCall = false;
6388 
6389     // If a class has at least one non-deleted, trivial copy constructor, it
6390     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6391     //
6392     // Note: This permits classes with non-trivial copy or move ctors to be
6393     // passed in registers, so long as they *also* have a trivial copy ctor,
6394     // which is non-conforming.
6395     if (D->needsImplicitCopyConstructor()) {
6396       if (!D->defaultedCopyConstructorIsDeleted()) {
6397         if (D->hasTrivialCopyConstructor())
6398           CopyCtorIsTrivial = true;
6399         if (D->hasTrivialCopyConstructorForCall())
6400           CopyCtorIsTrivialForCall = true;
6401       }
6402     } else {
6403       for (const CXXConstructorDecl *CD : D->ctors()) {
6404         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6405           if (CD->isTrivial())
6406             CopyCtorIsTrivial = true;
6407           if (CD->isTrivialForCall())
6408             CopyCtorIsTrivialForCall = true;
6409         }
6410       }
6411     }
6412 
6413     if (D->needsImplicitDestructor()) {
6414       if (!D->defaultedDestructorIsDeleted() &&
6415           D->hasTrivialDestructorForCall())
6416         DtorIsTrivialForCall = true;
6417     } else if (const auto *DD = D->getDestructor()) {
6418       if (!DD->isDeleted() && DD->isTrivialForCall())
6419         DtorIsTrivialForCall = true;
6420     }
6421 
6422     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6423     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6424       return true;
6425 
6426     // If a class has a destructor, we'd really like to pass it indirectly
6427     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6428     // impossible for small types, which it will pass in a single register or
6429     // stack slot. Most objects with dtors are large-ish, so handle that early.
6430     // We can't call out all large objects as being indirect because there are
6431     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6432     // how we pass large POD types.
6433 
6434     // Note: This permits small classes with nontrivial destructors to be
6435     // passed in registers, which is non-conforming.
6436     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6437     uint64_t TypeSize = isAArch64 ? 128 : 64;
6438 
6439     if (CopyCtorIsTrivial &&
6440         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6441       return true;
6442     return false;
6443   }
6444 
6445   // Per C++ [class.temporary]p3, the relevant condition is:
6446   //   each copy constructor, move constructor, and destructor of X is
6447   //   either trivial or deleted, and X has at least one non-deleted copy
6448   //   or move constructor
6449   bool HasNonDeletedCopyOrMove = false;
6450 
6451   if (D->needsImplicitCopyConstructor() &&
6452       !D->defaultedCopyConstructorIsDeleted()) {
6453     if (!D->hasTrivialCopyConstructorForCall())
6454       return false;
6455     HasNonDeletedCopyOrMove = true;
6456   }
6457 
6458   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6459       !D->defaultedMoveConstructorIsDeleted()) {
6460     if (!D->hasTrivialMoveConstructorForCall())
6461       return false;
6462     HasNonDeletedCopyOrMove = true;
6463   }
6464 
6465   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6466       !D->hasTrivialDestructorForCall())
6467     return false;
6468 
6469   for (const CXXMethodDecl *MD : D->methods()) {
6470     if (MD->isDeleted())
6471       continue;
6472 
6473     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6474     if (CD && CD->isCopyOrMoveConstructor())
6475       HasNonDeletedCopyOrMove = true;
6476     else if (!isa<CXXDestructorDecl>(MD))
6477       continue;
6478 
6479     if (!MD->isTrivialForCall())
6480       return false;
6481   }
6482 
6483   return HasNonDeletedCopyOrMove;
6484 }
6485 
6486 /// Report an error regarding overriding, along with any relevant
6487 /// overridden methods.
6488 ///
6489 /// \param DiagID the primary error to report.
6490 /// \param MD the overriding method.
6491 static bool
6492 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6493                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6494   bool IssuedDiagnostic = false;
6495   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6496     if (Report(O)) {
6497       if (!IssuedDiagnostic) {
6498         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6499         IssuedDiagnostic = true;
6500       }
6501       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6502     }
6503   }
6504   return IssuedDiagnostic;
6505 }
6506 
6507 /// Perform semantic checks on a class definition that has been
6508 /// completing, introducing implicitly-declared members, checking for
6509 /// abstract types, etc.
6510 ///
6511 /// \param S The scope in which the class was parsed. Null if we didn't just
6512 ///        parse a class definition.
6513 /// \param Record The completed class.
6514 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6515   if (!Record)
6516     return;
6517 
6518   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6519     AbstractUsageInfo Info(*this, Record);
6520     CheckAbstractClassUsage(Info, Record);
6521   }
6522 
6523   // If this is not an aggregate type and has no user-declared constructor,
6524   // complain about any non-static data members of reference or const scalar
6525   // type, since they will never get initializers.
6526   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6527       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6528       !Record->isLambda()) {
6529     bool Complained = false;
6530     for (const auto *F : Record->fields()) {
6531       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6532         continue;
6533 
6534       if (F->getType()->isReferenceType() ||
6535           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6536         if (!Complained) {
6537           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6538             << Record->getTagKind() << Record;
6539           Complained = true;
6540         }
6541 
6542         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6543           << F->getType()->isReferenceType()
6544           << F->getDeclName();
6545       }
6546     }
6547   }
6548 
6549   if (Record->getIdentifier()) {
6550     // C++ [class.mem]p13:
6551     //   If T is the name of a class, then each of the following shall have a
6552     //   name different from T:
6553     //     - every member of every anonymous union that is a member of class T.
6554     //
6555     // C++ [class.mem]p14:
6556     //   In addition, if class T has a user-declared constructor (12.1), every
6557     //   non-static data member of class T shall have a name different from T.
6558     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6559     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6560          ++I) {
6561       NamedDecl *D = (*I)->getUnderlyingDecl();
6562       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6563            Record->hasUserDeclaredConstructor()) ||
6564           isa<IndirectFieldDecl>(D)) {
6565         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6566           << D->getDeclName();
6567         break;
6568       }
6569     }
6570   }
6571 
6572   // Warn if the class has virtual methods but non-virtual public destructor.
6573   if (Record->isPolymorphic() && !Record->isDependentType()) {
6574     CXXDestructorDecl *dtor = Record->getDestructor();
6575     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6576         !Record->hasAttr<FinalAttr>())
6577       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6578            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6579   }
6580 
6581   if (Record->isAbstract()) {
6582     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6583       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6584         << FA->isSpelledAsSealed();
6585       DiagnoseAbstractType(Record);
6586     }
6587   }
6588 
6589   // Warn if the class has a final destructor but is not itself marked final.
6590   if (!Record->hasAttr<FinalAttr>()) {
6591     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6592       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6593         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6594             << FA->isSpelledAsSealed()
6595             << FixItHint::CreateInsertion(
6596                    getLocForEndOfToken(Record->getLocation()),
6597                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6598         Diag(Record->getLocation(),
6599              diag::note_final_dtor_non_final_class_silence)
6600             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6601       }
6602     }
6603   }
6604 
6605   // See if trivial_abi has to be dropped.
6606   if (Record->hasAttr<TrivialABIAttr>())
6607     checkIllFormedTrivialABIStruct(*Record);
6608 
6609   // Set HasTrivialSpecialMemberForCall if the record has attribute
6610   // "trivial_abi".
6611   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6612 
6613   if (HasTrivialABI)
6614     Record->setHasTrivialSpecialMemberForCall();
6615 
6616   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6617   // We check these last because they can depend on the properties of the
6618   // primary comparison functions (==, <=>).
6619   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6620 
6621   // Perform checks that can't be done until we know all the properties of a
6622   // member function (whether it's defaulted, deleted, virtual, overriding,
6623   // ...).
6624   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6625     // A static function cannot override anything.
6626     if (MD->getStorageClass() == SC_Static) {
6627       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6628                           [](const CXXMethodDecl *) { return true; }))
6629         return;
6630     }
6631 
6632     // A deleted function cannot override a non-deleted function and vice
6633     // versa.
6634     if (ReportOverrides(*this,
6635                         MD->isDeleted() ? diag::err_deleted_override
6636                                         : diag::err_non_deleted_override,
6637                         MD, [&](const CXXMethodDecl *V) {
6638                           return MD->isDeleted() != V->isDeleted();
6639                         })) {
6640       if (MD->isDefaulted() && MD->isDeleted())
6641         // Explain why this defaulted function was deleted.
6642         DiagnoseDeletedDefaultedFunction(MD);
6643       return;
6644     }
6645 
6646     // A consteval function cannot override a non-consteval function and vice
6647     // versa.
6648     if (ReportOverrides(*this,
6649                         MD->isConsteval() ? diag::err_consteval_override
6650                                           : diag::err_non_consteval_override,
6651                         MD, [&](const CXXMethodDecl *V) {
6652                           return MD->isConsteval() != V->isConsteval();
6653                         })) {
6654       if (MD->isDefaulted() && MD->isDeleted())
6655         // Explain why this defaulted function was deleted.
6656         DiagnoseDeletedDefaultedFunction(MD);
6657       return;
6658     }
6659   };
6660 
6661   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6662     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6663       return false;
6664 
6665     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6666     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6667         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6668       DefaultedSecondaryComparisons.push_back(FD);
6669       return true;
6670     }
6671 
6672     CheckExplicitlyDefaultedFunction(S, FD);
6673     return false;
6674   };
6675 
6676   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6677     // Check whether the explicitly-defaulted members are valid.
6678     bool Incomplete = CheckForDefaultedFunction(M);
6679 
6680     // Skip the rest of the checks for a member of a dependent class.
6681     if (Record->isDependentType())
6682       return;
6683 
6684     // For an explicitly defaulted or deleted special member, we defer
6685     // determining triviality until the class is complete. That time is now!
6686     CXXSpecialMember CSM = getSpecialMember(M);
6687     if (!M->isImplicit() && !M->isUserProvided()) {
6688       if (CSM != CXXInvalid) {
6689         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6690         // Inform the class that we've finished declaring this member.
6691         Record->finishedDefaultedOrDeletedMember(M);
6692         M->setTrivialForCall(
6693             HasTrivialABI ||
6694             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6695         Record->setTrivialForCallFlags(M);
6696       }
6697     }
6698 
6699     // Set triviality for the purpose of calls if this is a user-provided
6700     // copy/move constructor or destructor.
6701     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6702          CSM == CXXDestructor) && M->isUserProvided()) {
6703       M->setTrivialForCall(HasTrivialABI);
6704       Record->setTrivialForCallFlags(M);
6705     }
6706 
6707     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6708         M->hasAttr<DLLExportAttr>()) {
6709       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6710           M->isTrivial() &&
6711           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6712            CSM == CXXDestructor))
6713         M->dropAttr<DLLExportAttr>();
6714 
6715       if (M->hasAttr<DLLExportAttr>()) {
6716         // Define after any fields with in-class initializers have been parsed.
6717         DelayedDllExportMemberFunctions.push_back(M);
6718       }
6719     }
6720 
6721     // Define defaulted constexpr virtual functions that override a base class
6722     // function right away.
6723     // FIXME: We can defer doing this until the vtable is marked as used.
6724     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6725       DefineDefaultedFunction(*this, M, M->getLocation());
6726 
6727     if (!Incomplete)
6728       CheckCompletedMemberFunction(M);
6729   };
6730 
6731   // Check the destructor before any other member function. We need to
6732   // determine whether it's trivial in order to determine whether the claas
6733   // type is a literal type, which is a prerequisite for determining whether
6734   // other special member functions are valid and whether they're implicitly
6735   // 'constexpr'.
6736   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6737     CompleteMemberFunction(Dtor);
6738 
6739   bool HasMethodWithOverrideControl = false,
6740        HasOverridingMethodWithoutOverrideControl = false;
6741   for (auto *D : Record->decls()) {
6742     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6743       // FIXME: We could do this check for dependent types with non-dependent
6744       // bases.
6745       if (!Record->isDependentType()) {
6746         // See if a method overloads virtual methods in a base
6747         // class without overriding any.
6748         if (!M->isStatic())
6749           DiagnoseHiddenVirtualMethods(M);
6750         if (M->hasAttr<OverrideAttr>())
6751           HasMethodWithOverrideControl = true;
6752         else if (M->size_overridden_methods() > 0)
6753           HasOverridingMethodWithoutOverrideControl = true;
6754       }
6755 
6756       if (!isa<CXXDestructorDecl>(M))
6757         CompleteMemberFunction(M);
6758     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6759       CheckForDefaultedFunction(
6760           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6761     }
6762   }
6763 
6764   if (HasOverridingMethodWithoutOverrideControl) {
6765     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6766     for (auto *M : Record->methods())
6767       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6768   }
6769 
6770   // Check the defaulted secondary comparisons after any other member functions.
6771   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6772     CheckExplicitlyDefaultedFunction(S, FD);
6773 
6774     // If this is a member function, we deferred checking it until now.
6775     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6776       CheckCompletedMemberFunction(MD);
6777   }
6778 
6779   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6780   // whether this class uses any C++ features that are implemented
6781   // completely differently in MSVC, and if so, emit a diagnostic.
6782   // That diagnostic defaults to an error, but we allow projects to
6783   // map it down to a warning (or ignore it).  It's a fairly common
6784   // practice among users of the ms_struct pragma to mass-annotate
6785   // headers, sweeping up a bunch of types that the project doesn't
6786   // really rely on MSVC-compatible layout for.  We must therefore
6787   // support "ms_struct except for C++ stuff" as a secondary ABI.
6788   // Don't emit this diagnostic if the feature was enabled as a
6789   // language option (as opposed to via a pragma or attribute), as
6790   // the option -mms-bitfields otherwise essentially makes it impossible
6791   // to build C++ code, unless this diagnostic is turned off.
6792   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6793       (Record->isPolymorphic() || Record->getNumBases())) {
6794     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6795   }
6796 
6797   checkClassLevelDLLAttribute(Record);
6798   checkClassLevelCodeSegAttribute(Record);
6799 
6800   bool ClangABICompat4 =
6801       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6802   TargetInfo::CallingConvKind CCK =
6803       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6804   bool CanPass = canPassInRegisters(*this, Record, CCK);
6805 
6806   // Do not change ArgPassingRestrictions if it has already been set to
6807   // APK_CanNeverPassInRegs.
6808   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6809     Record->setArgPassingRestrictions(CanPass
6810                                           ? RecordDecl::APK_CanPassInRegs
6811                                           : RecordDecl::APK_CannotPassInRegs);
6812 
6813   // If canPassInRegisters returns true despite the record having a non-trivial
6814   // destructor, the record is destructed in the callee. This happens only when
6815   // the record or one of its subobjects has a field annotated with trivial_abi
6816   // or a field qualified with ObjC __strong/__weak.
6817   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6818     Record->setParamDestroyedInCallee(true);
6819   else if (Record->hasNonTrivialDestructor())
6820     Record->setParamDestroyedInCallee(CanPass);
6821 
6822   if (getLangOpts().ForceEmitVTables) {
6823     // If we want to emit all the vtables, we need to mark it as used.  This
6824     // is especially required for cases like vtable assumption loads.
6825     MarkVTableUsed(Record->getInnerLocStart(), Record);
6826   }
6827 
6828   if (getLangOpts().CUDA) {
6829     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6830       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6831     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6832       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6833   }
6834 }
6835 
6836 /// Look up the special member function that would be called by a special
6837 /// member function for a subobject of class type.
6838 ///
6839 /// \param Class The class type of the subobject.
6840 /// \param CSM The kind of special member function.
6841 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6842 /// \param ConstRHS True if this is a copy operation with a const object
6843 ///        on its RHS, that is, if the argument to the outer special member
6844 ///        function is 'const' and this is not a field marked 'mutable'.
6845 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6846     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6847     unsigned FieldQuals, bool ConstRHS) {
6848   unsigned LHSQuals = 0;
6849   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6850     LHSQuals = FieldQuals;
6851 
6852   unsigned RHSQuals = FieldQuals;
6853   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6854     RHSQuals = 0;
6855   else if (ConstRHS)
6856     RHSQuals |= Qualifiers::Const;
6857 
6858   return S.LookupSpecialMember(Class, CSM,
6859                                RHSQuals & Qualifiers::Const,
6860                                RHSQuals & Qualifiers::Volatile,
6861                                false,
6862                                LHSQuals & Qualifiers::Const,
6863                                LHSQuals & Qualifiers::Volatile);
6864 }
6865 
6866 class Sema::InheritedConstructorInfo {
6867   Sema &S;
6868   SourceLocation UseLoc;
6869 
6870   /// A mapping from the base classes through which the constructor was
6871   /// inherited to the using shadow declaration in that base class (or a null
6872   /// pointer if the constructor was declared in that base class).
6873   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6874       InheritedFromBases;
6875 
6876 public:
6877   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6878                            ConstructorUsingShadowDecl *Shadow)
6879       : S(S), UseLoc(UseLoc) {
6880     bool DiagnosedMultipleConstructedBases = false;
6881     CXXRecordDecl *ConstructedBase = nullptr;
6882     UsingDecl *ConstructedBaseUsing = nullptr;
6883 
6884     // Find the set of such base class subobjects and check that there's a
6885     // unique constructed subobject.
6886     for (auto *D : Shadow->redecls()) {
6887       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6888       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6889       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6890 
6891       InheritedFromBases.insert(
6892           std::make_pair(DNominatedBase->getCanonicalDecl(),
6893                          DShadow->getNominatedBaseClassShadowDecl()));
6894       if (DShadow->constructsVirtualBase())
6895         InheritedFromBases.insert(
6896             std::make_pair(DConstructedBase->getCanonicalDecl(),
6897                            DShadow->getConstructedBaseClassShadowDecl()));
6898       else
6899         assert(DNominatedBase == DConstructedBase);
6900 
6901       // [class.inhctor.init]p2:
6902       //   If the constructor was inherited from multiple base class subobjects
6903       //   of type B, the program is ill-formed.
6904       if (!ConstructedBase) {
6905         ConstructedBase = DConstructedBase;
6906         ConstructedBaseUsing = D->getUsingDecl();
6907       } else if (ConstructedBase != DConstructedBase &&
6908                  !Shadow->isInvalidDecl()) {
6909         if (!DiagnosedMultipleConstructedBases) {
6910           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6911               << Shadow->getTargetDecl();
6912           S.Diag(ConstructedBaseUsing->getLocation(),
6913                diag::note_ambiguous_inherited_constructor_using)
6914               << ConstructedBase;
6915           DiagnosedMultipleConstructedBases = true;
6916         }
6917         S.Diag(D->getUsingDecl()->getLocation(),
6918                diag::note_ambiguous_inherited_constructor_using)
6919             << DConstructedBase;
6920       }
6921     }
6922 
6923     if (DiagnosedMultipleConstructedBases)
6924       Shadow->setInvalidDecl();
6925   }
6926 
6927   /// Find the constructor to use for inherited construction of a base class,
6928   /// and whether that base class constructor inherits the constructor from a
6929   /// virtual base class (in which case it won't actually invoke it).
6930   std::pair<CXXConstructorDecl *, bool>
6931   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6932     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6933     if (It == InheritedFromBases.end())
6934       return std::make_pair(nullptr, false);
6935 
6936     // This is an intermediary class.
6937     if (It->second)
6938       return std::make_pair(
6939           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6940           It->second->constructsVirtualBase());
6941 
6942     // This is the base class from which the constructor was inherited.
6943     return std::make_pair(Ctor, false);
6944   }
6945 };
6946 
6947 /// Is the special member function which would be selected to perform the
6948 /// specified operation on the specified class type a constexpr constructor?
6949 static bool
6950 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6951                          Sema::CXXSpecialMember CSM, unsigned Quals,
6952                          bool ConstRHS,
6953                          CXXConstructorDecl *InheritedCtor = nullptr,
6954                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6955   // If we're inheriting a constructor, see if we need to call it for this base
6956   // class.
6957   if (InheritedCtor) {
6958     assert(CSM == Sema::CXXDefaultConstructor);
6959     auto BaseCtor =
6960         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6961     if (BaseCtor)
6962       return BaseCtor->isConstexpr();
6963   }
6964 
6965   if (CSM == Sema::CXXDefaultConstructor)
6966     return ClassDecl->hasConstexprDefaultConstructor();
6967   if (CSM == Sema::CXXDestructor)
6968     return ClassDecl->hasConstexprDestructor();
6969 
6970   Sema::SpecialMemberOverloadResult SMOR =
6971       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6972   if (!SMOR.getMethod())
6973     // A constructor we wouldn't select can't be "involved in initializing"
6974     // anything.
6975     return true;
6976   return SMOR.getMethod()->isConstexpr();
6977 }
6978 
6979 /// Determine whether the specified special member function would be constexpr
6980 /// if it were implicitly defined.
6981 static bool defaultedSpecialMemberIsConstexpr(
6982     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6983     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6984     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6985   if (!S.getLangOpts().CPlusPlus11)
6986     return false;
6987 
6988   // C++11 [dcl.constexpr]p4:
6989   // In the definition of a constexpr constructor [...]
6990   bool Ctor = true;
6991   switch (CSM) {
6992   case Sema::CXXDefaultConstructor:
6993     if (Inherited)
6994       break;
6995     // Since default constructor lookup is essentially trivial (and cannot
6996     // involve, for instance, template instantiation), we compute whether a
6997     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6998     //
6999     // This is important for performance; we need to know whether the default
7000     // constructor is constexpr to determine whether the type is a literal type.
7001     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7002 
7003   case Sema::CXXCopyConstructor:
7004   case Sema::CXXMoveConstructor:
7005     // For copy or move constructors, we need to perform overload resolution.
7006     break;
7007 
7008   case Sema::CXXCopyAssignment:
7009   case Sema::CXXMoveAssignment:
7010     if (!S.getLangOpts().CPlusPlus14)
7011       return false;
7012     // In C++1y, we need to perform overload resolution.
7013     Ctor = false;
7014     break;
7015 
7016   case Sema::CXXDestructor:
7017     return ClassDecl->defaultedDestructorIsConstexpr();
7018 
7019   case Sema::CXXInvalid:
7020     return false;
7021   }
7022 
7023   //   -- if the class is a non-empty union, or for each non-empty anonymous
7024   //      union member of a non-union class, exactly one non-static data member
7025   //      shall be initialized; [DR1359]
7026   //
7027   // If we squint, this is guaranteed, since exactly one non-static data member
7028   // will be initialized (if the constructor isn't deleted), we just don't know
7029   // which one.
7030   if (Ctor && ClassDecl->isUnion())
7031     return CSM == Sema::CXXDefaultConstructor
7032                ? ClassDecl->hasInClassInitializer() ||
7033                      !ClassDecl->hasVariantMembers()
7034                : true;
7035 
7036   //   -- the class shall not have any virtual base classes;
7037   if (Ctor && ClassDecl->getNumVBases())
7038     return false;
7039 
7040   // C++1y [class.copy]p26:
7041   //   -- [the class] is a literal type, and
7042   if (!Ctor && !ClassDecl->isLiteral())
7043     return false;
7044 
7045   //   -- every constructor involved in initializing [...] base class
7046   //      sub-objects shall be a constexpr constructor;
7047   //   -- the assignment operator selected to copy/move each direct base
7048   //      class is a constexpr function, and
7049   for (const auto &B : ClassDecl->bases()) {
7050     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7051     if (!BaseType) continue;
7052 
7053     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7054     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7055                                   InheritedCtor, Inherited))
7056       return false;
7057   }
7058 
7059   //   -- every constructor involved in initializing non-static data members
7060   //      [...] shall be a constexpr constructor;
7061   //   -- every non-static data member and base class sub-object shall be
7062   //      initialized
7063   //   -- for each non-static data member of X that is of class type (or array
7064   //      thereof), the assignment operator selected to copy/move that member is
7065   //      a constexpr function
7066   for (const auto *F : ClassDecl->fields()) {
7067     if (F->isInvalidDecl())
7068       continue;
7069     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7070       continue;
7071     QualType BaseType = S.Context.getBaseElementType(F->getType());
7072     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7073       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7074       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7075                                     BaseType.getCVRQualifiers(),
7076                                     ConstArg && !F->isMutable()))
7077         return false;
7078     } else if (CSM == Sema::CXXDefaultConstructor) {
7079       return false;
7080     }
7081   }
7082 
7083   // All OK, it's constexpr!
7084   return true;
7085 }
7086 
7087 namespace {
7088 /// RAII object to register a defaulted function as having its exception
7089 /// specification computed.
7090 struct ComputingExceptionSpec {
7091   Sema &S;
7092 
7093   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7094       : S(S) {
7095     Sema::CodeSynthesisContext Ctx;
7096     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7097     Ctx.PointOfInstantiation = Loc;
7098     Ctx.Entity = FD;
7099     S.pushCodeSynthesisContext(Ctx);
7100   }
7101   ~ComputingExceptionSpec() {
7102     S.popCodeSynthesisContext();
7103   }
7104 };
7105 }
7106 
7107 static Sema::ImplicitExceptionSpecification
7108 ComputeDefaultedSpecialMemberExceptionSpec(
7109     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7110     Sema::InheritedConstructorInfo *ICI);
7111 
7112 static Sema::ImplicitExceptionSpecification
7113 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7114                                         FunctionDecl *FD,
7115                                         Sema::DefaultedComparisonKind DCK);
7116 
7117 static Sema::ImplicitExceptionSpecification
7118 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7119   auto DFK = S.getDefaultedFunctionKind(FD);
7120   if (DFK.isSpecialMember())
7121     return ComputeDefaultedSpecialMemberExceptionSpec(
7122         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7123   if (DFK.isComparison())
7124     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7125                                                    DFK.asComparison());
7126 
7127   auto *CD = cast<CXXConstructorDecl>(FD);
7128   assert(CD->getInheritedConstructor() &&
7129          "only defaulted functions and inherited constructors have implicit "
7130          "exception specs");
7131   Sema::InheritedConstructorInfo ICI(
7132       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7133   return ComputeDefaultedSpecialMemberExceptionSpec(
7134       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7135 }
7136 
7137 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7138                                                             CXXMethodDecl *MD) {
7139   FunctionProtoType::ExtProtoInfo EPI;
7140 
7141   // Build an exception specification pointing back at this member.
7142   EPI.ExceptionSpec.Type = EST_Unevaluated;
7143   EPI.ExceptionSpec.SourceDecl = MD;
7144 
7145   // Set the calling convention to the default for C++ instance methods.
7146   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7147       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7148                                             /*IsCXXMethod=*/true));
7149   return EPI;
7150 }
7151 
7152 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7153   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7154   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7155     return;
7156 
7157   // Evaluate the exception specification.
7158   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7159   auto ESI = IES.getExceptionSpec();
7160 
7161   // Update the type of the special member to use it.
7162   UpdateExceptionSpec(FD, ESI);
7163 }
7164 
7165 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7166   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7167 
7168   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7169   if (!DefKind) {
7170     assert(FD->getDeclContext()->isDependentContext());
7171     return;
7172   }
7173 
7174   if (DefKind.isSpecialMember()
7175           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7176                                                   DefKind.asSpecialMember())
7177           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7178     FD->setInvalidDecl();
7179 }
7180 
7181 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7182                                                  CXXSpecialMember CSM) {
7183   CXXRecordDecl *RD = MD->getParent();
7184 
7185   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7186          "not an explicitly-defaulted special member");
7187 
7188   // Defer all checking for special members of a dependent type.
7189   if (RD->isDependentType())
7190     return false;
7191 
7192   // Whether this was the first-declared instance of the constructor.
7193   // This affects whether we implicitly add an exception spec and constexpr.
7194   bool First = MD == MD->getCanonicalDecl();
7195 
7196   bool HadError = false;
7197 
7198   // C++11 [dcl.fct.def.default]p1:
7199   //   A function that is explicitly defaulted shall
7200   //     -- be a special member function [...] (checked elsewhere),
7201   //     -- have the same type (except for ref-qualifiers, and except that a
7202   //        copy operation can take a non-const reference) as an implicit
7203   //        declaration, and
7204   //     -- not have default arguments.
7205   // C++2a changes the second bullet to instead delete the function if it's
7206   // defaulted on its first declaration, unless it's "an assignment operator,
7207   // and its return type differs or its parameter type is not a reference".
7208   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7209   bool ShouldDeleteForTypeMismatch = false;
7210   unsigned ExpectedParams = 1;
7211   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7212     ExpectedParams = 0;
7213   if (MD->getNumParams() != ExpectedParams) {
7214     // This checks for default arguments: a copy or move constructor with a
7215     // default argument is classified as a default constructor, and assignment
7216     // operations and destructors can't have default arguments.
7217     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7218       << CSM << MD->getSourceRange();
7219     HadError = true;
7220   } else if (MD->isVariadic()) {
7221     if (DeleteOnTypeMismatch)
7222       ShouldDeleteForTypeMismatch = true;
7223     else {
7224       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7225         << CSM << MD->getSourceRange();
7226       HadError = true;
7227     }
7228   }
7229 
7230   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7231 
7232   bool CanHaveConstParam = false;
7233   if (CSM == CXXCopyConstructor)
7234     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7235   else if (CSM == CXXCopyAssignment)
7236     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7237 
7238   QualType ReturnType = Context.VoidTy;
7239   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7240     // Check for return type matching.
7241     ReturnType = Type->getReturnType();
7242 
7243     QualType DeclType = Context.getTypeDeclType(RD);
7244     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7245     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7246 
7247     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7248       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7249         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7250       HadError = true;
7251     }
7252 
7253     // A defaulted special member cannot have cv-qualifiers.
7254     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7255       if (DeleteOnTypeMismatch)
7256         ShouldDeleteForTypeMismatch = true;
7257       else {
7258         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7259           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7260         HadError = true;
7261       }
7262     }
7263   }
7264 
7265   // Check for parameter type matching.
7266   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7267   bool HasConstParam = false;
7268   if (ExpectedParams && ArgType->isReferenceType()) {
7269     // Argument must be reference to possibly-const T.
7270     QualType ReferentType = ArgType->getPointeeType();
7271     HasConstParam = ReferentType.isConstQualified();
7272 
7273     if (ReferentType.isVolatileQualified()) {
7274       if (DeleteOnTypeMismatch)
7275         ShouldDeleteForTypeMismatch = true;
7276       else {
7277         Diag(MD->getLocation(),
7278              diag::err_defaulted_special_member_volatile_param) << CSM;
7279         HadError = true;
7280       }
7281     }
7282 
7283     if (HasConstParam && !CanHaveConstParam) {
7284       if (DeleteOnTypeMismatch)
7285         ShouldDeleteForTypeMismatch = true;
7286       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7287         Diag(MD->getLocation(),
7288              diag::err_defaulted_special_member_copy_const_param)
7289           << (CSM == CXXCopyAssignment);
7290         // FIXME: Explain why this special member can't be const.
7291         HadError = true;
7292       } else {
7293         Diag(MD->getLocation(),
7294              diag::err_defaulted_special_member_move_const_param)
7295           << (CSM == CXXMoveAssignment);
7296         HadError = true;
7297       }
7298     }
7299   } else if (ExpectedParams) {
7300     // A copy assignment operator can take its argument by value, but a
7301     // defaulted one cannot.
7302     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7303     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7304     HadError = true;
7305   }
7306 
7307   // C++11 [dcl.fct.def.default]p2:
7308   //   An explicitly-defaulted function may be declared constexpr only if it
7309   //   would have been implicitly declared as constexpr,
7310   // Do not apply this rule to members of class templates, since core issue 1358
7311   // makes such functions always instantiate to constexpr functions. For
7312   // functions which cannot be constexpr (for non-constructors in C++11 and for
7313   // destructors in C++14 and C++17), this is checked elsewhere.
7314   //
7315   // FIXME: This should not apply if the member is deleted.
7316   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7317                                                      HasConstParam);
7318   if ((getLangOpts().CPlusPlus20 ||
7319        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7320                                   : isa<CXXConstructorDecl>(MD))) &&
7321       MD->isConstexpr() && !Constexpr &&
7322       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7323     Diag(MD->getBeginLoc(), MD->isConsteval()
7324                                 ? diag::err_incorrect_defaulted_consteval
7325                                 : diag::err_incorrect_defaulted_constexpr)
7326         << CSM;
7327     // FIXME: Explain why the special member can't be constexpr.
7328     HadError = true;
7329   }
7330 
7331   if (First) {
7332     // C++2a [dcl.fct.def.default]p3:
7333     //   If a function is explicitly defaulted on its first declaration, it is
7334     //   implicitly considered to be constexpr if the implicit declaration
7335     //   would be.
7336     MD->setConstexprKind(
7337         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7338                   : CSK_unspecified);
7339 
7340     if (!Type->hasExceptionSpec()) {
7341       // C++2a [except.spec]p3:
7342       //   If a declaration of a function does not have a noexcept-specifier
7343       //   [and] is defaulted on its first declaration, [...] the exception
7344       //   specification is as specified below
7345       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7346       EPI.ExceptionSpec.Type = EST_Unevaluated;
7347       EPI.ExceptionSpec.SourceDecl = MD;
7348       MD->setType(Context.getFunctionType(ReturnType,
7349                                           llvm::makeArrayRef(&ArgType,
7350                                                              ExpectedParams),
7351                                           EPI));
7352     }
7353   }
7354 
7355   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7356     if (First) {
7357       SetDeclDeleted(MD, MD->getLocation());
7358       if (!inTemplateInstantiation() && !HadError) {
7359         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7360         if (ShouldDeleteForTypeMismatch) {
7361           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7362         } else {
7363           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7364         }
7365       }
7366       if (ShouldDeleteForTypeMismatch && !HadError) {
7367         Diag(MD->getLocation(),
7368              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7369       }
7370     } else {
7371       // C++11 [dcl.fct.def.default]p4:
7372       //   [For a] user-provided explicitly-defaulted function [...] if such a
7373       //   function is implicitly defined as deleted, the program is ill-formed.
7374       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7375       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7376       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7377       HadError = true;
7378     }
7379   }
7380 
7381   return HadError;
7382 }
7383 
7384 namespace {
7385 /// Helper class for building and checking a defaulted comparison.
7386 ///
7387 /// Defaulted functions are built in two phases:
7388 ///
7389 ///  * First, the set of operations that the function will perform are
7390 ///    identified, and some of them are checked. If any of the checked
7391 ///    operations is invalid in certain ways, the comparison function is
7392 ///    defined as deleted and no body is built.
7393 ///  * Then, if the function is not defined as deleted, the body is built.
7394 ///
7395 /// This is accomplished by performing two visitation steps over the eventual
7396 /// body of the function.
7397 template<typename Derived, typename ResultList, typename Result,
7398          typename Subobject>
7399 class DefaultedComparisonVisitor {
7400 public:
7401   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7402 
7403   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7404                              DefaultedComparisonKind DCK)
7405       : S(S), RD(RD), FD(FD), DCK(DCK) {
7406     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7407       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7408       // UnresolvedSet to avoid this copy.
7409       Fns.assign(Info->getUnqualifiedLookups().begin(),
7410                  Info->getUnqualifiedLookups().end());
7411     }
7412   }
7413 
7414   ResultList visit() {
7415     // The type of an lvalue naming a parameter of this function.
7416     QualType ParamLvalType =
7417         FD->getParamDecl(0)->getType().getNonReferenceType();
7418 
7419     ResultList Results;
7420 
7421     switch (DCK) {
7422     case DefaultedComparisonKind::None:
7423       llvm_unreachable("not a defaulted comparison");
7424 
7425     case DefaultedComparisonKind::Equal:
7426     case DefaultedComparisonKind::ThreeWay:
7427       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7428       return Results;
7429 
7430     case DefaultedComparisonKind::NotEqual:
7431     case DefaultedComparisonKind::Relational:
7432       Results.add(getDerived().visitExpandedSubobject(
7433           ParamLvalType, getDerived().getCompleteObject()));
7434       return Results;
7435     }
7436     llvm_unreachable("");
7437   }
7438 
7439 protected:
7440   Derived &getDerived() { return static_cast<Derived&>(*this); }
7441 
7442   /// Visit the expanded list of subobjects of the given type, as specified in
7443   /// C++2a [class.compare.default].
7444   ///
7445   /// \return \c true if the ResultList object said we're done, \c false if not.
7446   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7447                        Qualifiers Quals) {
7448     // C++2a [class.compare.default]p4:
7449     //   The direct base class subobjects of C
7450     for (CXXBaseSpecifier &Base : Record->bases())
7451       if (Results.add(getDerived().visitSubobject(
7452               S.Context.getQualifiedType(Base.getType(), Quals),
7453               getDerived().getBase(&Base))))
7454         return true;
7455 
7456     //   followed by the non-static data members of C
7457     for (FieldDecl *Field : Record->fields()) {
7458       // Recursively expand anonymous structs.
7459       if (Field->isAnonymousStructOrUnion()) {
7460         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7461                             Quals))
7462           return true;
7463         continue;
7464       }
7465 
7466       // Figure out the type of an lvalue denoting this field.
7467       Qualifiers FieldQuals = Quals;
7468       if (Field->isMutable())
7469         FieldQuals.removeConst();
7470       QualType FieldType =
7471           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7472 
7473       if (Results.add(getDerived().visitSubobject(
7474               FieldType, getDerived().getField(Field))))
7475         return true;
7476     }
7477 
7478     //   form a list of subobjects.
7479     return false;
7480   }
7481 
7482   Result visitSubobject(QualType Type, Subobject Subobj) {
7483     //   In that list, any subobject of array type is recursively expanded
7484     const ArrayType *AT = S.Context.getAsArrayType(Type);
7485     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7486       return getDerived().visitSubobjectArray(CAT->getElementType(),
7487                                               CAT->getSize(), Subobj);
7488     return getDerived().visitExpandedSubobject(Type, Subobj);
7489   }
7490 
7491   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7492                              Subobject Subobj) {
7493     return getDerived().visitSubobject(Type, Subobj);
7494   }
7495 
7496 protected:
7497   Sema &S;
7498   CXXRecordDecl *RD;
7499   FunctionDecl *FD;
7500   DefaultedComparisonKind DCK;
7501   UnresolvedSet<16> Fns;
7502 };
7503 
7504 /// Information about a defaulted comparison, as determined by
7505 /// DefaultedComparisonAnalyzer.
7506 struct DefaultedComparisonInfo {
7507   bool Deleted = false;
7508   bool Constexpr = true;
7509   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7510 
7511   static DefaultedComparisonInfo deleted() {
7512     DefaultedComparisonInfo Deleted;
7513     Deleted.Deleted = true;
7514     return Deleted;
7515   }
7516 
7517   bool add(const DefaultedComparisonInfo &R) {
7518     Deleted |= R.Deleted;
7519     Constexpr &= R.Constexpr;
7520     Category = commonComparisonType(Category, R.Category);
7521     return Deleted;
7522   }
7523 };
7524 
7525 /// An element in the expanded list of subobjects of a defaulted comparison, as
7526 /// specified in C++2a [class.compare.default]p4.
7527 struct DefaultedComparisonSubobject {
7528   enum { CompleteObject, Member, Base } Kind;
7529   NamedDecl *Decl;
7530   SourceLocation Loc;
7531 };
7532 
7533 /// A visitor over the notional body of a defaulted comparison that determines
7534 /// whether that body would be deleted or constexpr.
7535 class DefaultedComparisonAnalyzer
7536     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7537                                         DefaultedComparisonInfo,
7538                                         DefaultedComparisonInfo,
7539                                         DefaultedComparisonSubobject> {
7540 public:
7541   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7542 
7543 private:
7544   DiagnosticKind Diagnose;
7545 
7546 public:
7547   using Base = DefaultedComparisonVisitor;
7548   using Result = DefaultedComparisonInfo;
7549   using Subobject = DefaultedComparisonSubobject;
7550 
7551   friend Base;
7552 
7553   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7554                               DefaultedComparisonKind DCK,
7555                               DiagnosticKind Diagnose = NoDiagnostics)
7556       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7557 
7558   Result visit() {
7559     if ((DCK == DefaultedComparisonKind::Equal ||
7560          DCK == DefaultedComparisonKind::ThreeWay) &&
7561         RD->hasVariantMembers()) {
7562       // C++2a [class.compare.default]p2 [P2002R0]:
7563       //   A defaulted comparison operator function for class C is defined as
7564       //   deleted if [...] C has variant members.
7565       if (Diagnose == ExplainDeleted) {
7566         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7567           << FD << RD->isUnion() << RD;
7568       }
7569       return Result::deleted();
7570     }
7571 
7572     return Base::visit();
7573   }
7574 
7575 private:
7576   Subobject getCompleteObject() {
7577     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7578   }
7579 
7580   Subobject getBase(CXXBaseSpecifier *Base) {
7581     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7582                      Base->getBaseTypeLoc()};
7583   }
7584 
7585   Subobject getField(FieldDecl *Field) {
7586     return Subobject{Subobject::Member, Field, Field->getLocation()};
7587   }
7588 
7589   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7590     // C++2a [class.compare.default]p2 [P2002R0]:
7591     //   A defaulted <=> or == operator function for class C is defined as
7592     //   deleted if any non-static data member of C is of reference type
7593     if (Type->isReferenceType()) {
7594       if (Diagnose == ExplainDeleted) {
7595         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7596             << FD << RD;
7597       }
7598       return Result::deleted();
7599     }
7600 
7601     // [...] Let xi be an lvalue denoting the ith element [...]
7602     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7603     Expr *Args[] = {&Xi, &Xi};
7604 
7605     // All operators start by trying to apply that same operator recursively.
7606     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7607     assert(OO != OO_None && "not an overloaded operator!");
7608     return visitBinaryOperator(OO, Args, Subobj);
7609   }
7610 
7611   Result
7612   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7613                       Subobject Subobj,
7614                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7615     // Note that there is no need to consider rewritten candidates here if
7616     // we've already found there is no viable 'operator<=>' candidate (and are
7617     // considering synthesizing a '<=>' from '==' and '<').
7618     OverloadCandidateSet CandidateSet(
7619         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7620         OverloadCandidateSet::OperatorRewriteInfo(
7621             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7622 
7623     /// C++2a [class.compare.default]p1 [P2002R0]:
7624     ///   [...] the defaulted function itself is never a candidate for overload
7625     ///   resolution [...]
7626     CandidateSet.exclude(FD);
7627 
7628     if (Args[0]->getType()->isOverloadableType())
7629       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7630     else {
7631       // FIXME: We determine whether this is a valid expression by checking to
7632       // see if there's a viable builtin operator candidate for it. That isn't
7633       // really what the rules ask us to do, but should give the right results.
7634       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7635     }
7636 
7637     Result R;
7638 
7639     OverloadCandidateSet::iterator Best;
7640     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7641     case OR_Success: {
7642       // C++2a [class.compare.secondary]p2 [P2002R0]:
7643       //   The operator function [...] is defined as deleted if [...] the
7644       //   candidate selected by overload resolution is not a rewritten
7645       //   candidate.
7646       if ((DCK == DefaultedComparisonKind::NotEqual ||
7647            DCK == DefaultedComparisonKind::Relational) &&
7648           !Best->RewriteKind) {
7649         if (Diagnose == ExplainDeleted) {
7650           S.Diag(Best->Function->getLocation(),
7651                  diag::note_defaulted_comparison_not_rewritten_callee)
7652               << FD;
7653         }
7654         return Result::deleted();
7655       }
7656 
7657       // Throughout C++2a [class.compare]: if overload resolution does not
7658       // result in a usable function, the candidate function is defined as
7659       // deleted. This requires that we selected an accessible function.
7660       //
7661       // Note that this only considers the access of the function when named
7662       // within the type of the subobject, and not the access path for any
7663       // derived-to-base conversion.
7664       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7665       if (ArgClass && Best->FoundDecl.getDecl() &&
7666           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7667         QualType ObjectType = Subobj.Kind == Subobject::Member
7668                                   ? Args[0]->getType()
7669                                   : S.Context.getRecordType(RD);
7670         if (!S.isMemberAccessibleForDeletion(
7671                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7672                 Diagnose == ExplainDeleted
7673                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7674                           << FD << Subobj.Kind << Subobj.Decl
7675                     : S.PDiag()))
7676           return Result::deleted();
7677       }
7678 
7679       // C++2a [class.compare.default]p3 [P2002R0]:
7680       //   A defaulted comparison function is constexpr-compatible if [...]
7681       //   no overlod resolution performed [...] results in a non-constexpr
7682       //   function.
7683       if (FunctionDecl *BestFD = Best->Function) {
7684         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7685         // If it's not constexpr, explain why not.
7686         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7687           if (Subobj.Kind != Subobject::CompleteObject)
7688             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7689               << Subobj.Kind << Subobj.Decl;
7690           S.Diag(BestFD->getLocation(),
7691                  diag::note_defaulted_comparison_not_constexpr_here);
7692           // Bail out after explaining; we don't want any more notes.
7693           return Result::deleted();
7694         }
7695         R.Constexpr &= BestFD->isConstexpr();
7696       }
7697 
7698       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7699         if (auto *BestFD = Best->Function) {
7700           // If any callee has an undeduced return type, deduce it now.
7701           // FIXME: It's not clear how a failure here should be handled. For
7702           // now, we produce an eager diagnostic, because that is forward
7703           // compatible with most (all?) other reasonable options.
7704           if (BestFD->getReturnType()->isUndeducedType() &&
7705               S.DeduceReturnType(BestFD, FD->getLocation(),
7706                                  /*Diagnose=*/false)) {
7707             // Don't produce a duplicate error when asked to explain why the
7708             // comparison is deleted: we diagnosed that when initially checking
7709             // the defaulted operator.
7710             if (Diagnose == NoDiagnostics) {
7711               S.Diag(
7712                   FD->getLocation(),
7713                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7714                   << Subobj.Kind << Subobj.Decl;
7715               S.Diag(
7716                   Subobj.Loc,
7717                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7718                   << Subobj.Kind << Subobj.Decl;
7719               S.Diag(BestFD->getLocation(),
7720                      diag::note_defaulted_comparison_cannot_deduce_callee)
7721                   << Subobj.Kind << Subobj.Decl;
7722             }
7723             return Result::deleted();
7724           }
7725           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7726               BestFD->getCallResultType())) {
7727             R.Category = Info->Kind;
7728           } else {
7729             if (Diagnose == ExplainDeleted) {
7730               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7731                   << Subobj.Kind << Subobj.Decl
7732                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7733               S.Diag(BestFD->getLocation(),
7734                      diag::note_defaulted_comparison_cannot_deduce_callee)
7735                   << Subobj.Kind << Subobj.Decl;
7736             }
7737             return Result::deleted();
7738           }
7739         } else {
7740           Optional<ComparisonCategoryType> Cat =
7741               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7742           assert(Cat && "no category for builtin comparison?");
7743           R.Category = *Cat;
7744         }
7745       }
7746 
7747       // Note that we might be rewriting to a different operator. That call is
7748       // not considered until we come to actually build the comparison function.
7749       break;
7750     }
7751 
7752     case OR_Ambiguous:
7753       if (Diagnose == ExplainDeleted) {
7754         unsigned Kind = 0;
7755         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7756           Kind = OO == OO_EqualEqual ? 1 : 2;
7757         CandidateSet.NoteCandidates(
7758             PartialDiagnosticAt(
7759                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7760                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7761             S, OCD_AmbiguousCandidates, Args);
7762       }
7763       R = Result::deleted();
7764       break;
7765 
7766     case OR_Deleted:
7767       if (Diagnose == ExplainDeleted) {
7768         if ((DCK == DefaultedComparisonKind::NotEqual ||
7769              DCK == DefaultedComparisonKind::Relational) &&
7770             !Best->RewriteKind) {
7771           S.Diag(Best->Function->getLocation(),
7772                  diag::note_defaulted_comparison_not_rewritten_callee)
7773               << FD;
7774         } else {
7775           S.Diag(Subobj.Loc,
7776                  diag::note_defaulted_comparison_calls_deleted)
7777               << FD << Subobj.Kind << Subobj.Decl;
7778           S.NoteDeletedFunction(Best->Function);
7779         }
7780       }
7781       R = Result::deleted();
7782       break;
7783 
7784     case OR_No_Viable_Function:
7785       // If there's no usable candidate, we're done unless we can rewrite a
7786       // '<=>' in terms of '==' and '<'.
7787       if (OO == OO_Spaceship &&
7788           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7789         // For any kind of comparison category return type, we need a usable
7790         // '==' and a usable '<'.
7791         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7792                                        &CandidateSet)))
7793           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7794         break;
7795       }
7796 
7797       if (Diagnose == ExplainDeleted) {
7798         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7799             << FD << Subobj.Kind << Subobj.Decl;
7800 
7801         // For a three-way comparison, list both the candidates for the
7802         // original operator and the candidates for the synthesized operator.
7803         if (SpaceshipCandidates) {
7804           SpaceshipCandidates->NoteCandidates(
7805               S, Args,
7806               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7807                                                       Args, FD->getLocation()));
7808           S.Diag(Subobj.Loc,
7809                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7810               << (OO == OO_EqualEqual ? 0 : 1);
7811         }
7812 
7813         CandidateSet.NoteCandidates(
7814             S, Args,
7815             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7816                                             FD->getLocation()));
7817       }
7818       R = Result::deleted();
7819       break;
7820     }
7821 
7822     return R;
7823   }
7824 };
7825 
7826 /// A list of statements.
7827 struct StmtListResult {
7828   bool IsInvalid = false;
7829   llvm::SmallVector<Stmt*, 16> Stmts;
7830 
7831   bool add(const StmtResult &S) {
7832     IsInvalid |= S.isInvalid();
7833     if (IsInvalid)
7834       return true;
7835     Stmts.push_back(S.get());
7836     return false;
7837   }
7838 };
7839 
7840 /// A visitor over the notional body of a defaulted comparison that synthesizes
7841 /// the actual body.
7842 class DefaultedComparisonSynthesizer
7843     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7844                                         StmtListResult, StmtResult,
7845                                         std::pair<ExprResult, ExprResult>> {
7846   SourceLocation Loc;
7847   unsigned ArrayDepth = 0;
7848 
7849 public:
7850   using Base = DefaultedComparisonVisitor;
7851   using ExprPair = std::pair<ExprResult, ExprResult>;
7852 
7853   friend Base;
7854 
7855   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7856                                  DefaultedComparisonKind DCK,
7857                                  SourceLocation BodyLoc)
7858       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7859 
7860   /// Build a suitable function body for this defaulted comparison operator.
7861   StmtResult build() {
7862     Sema::CompoundScopeRAII CompoundScope(S);
7863 
7864     StmtListResult Stmts = visit();
7865     if (Stmts.IsInvalid)
7866       return StmtError();
7867 
7868     ExprResult RetVal;
7869     switch (DCK) {
7870     case DefaultedComparisonKind::None:
7871       llvm_unreachable("not a defaulted comparison");
7872 
7873     case DefaultedComparisonKind::Equal: {
7874       // C++2a [class.eq]p3:
7875       //   [...] compar[e] the corresponding elements [...] until the first
7876       //   index i where xi == yi yields [...] false. If no such index exists,
7877       //   V is true. Otherwise, V is false.
7878       //
7879       // Join the comparisons with '&&'s and return the result. Use a right
7880       // fold (traversing the conditions right-to-left), because that
7881       // short-circuits more naturally.
7882       auto OldStmts = std::move(Stmts.Stmts);
7883       Stmts.Stmts.clear();
7884       ExprResult CmpSoFar;
7885       // Finish a particular comparison chain.
7886       auto FinishCmp = [&] {
7887         if (Expr *Prior = CmpSoFar.get()) {
7888           // Convert the last expression to 'return ...;'
7889           if (RetVal.isUnset() && Stmts.Stmts.empty())
7890             RetVal = CmpSoFar;
7891           // Convert any prior comparison to 'if (!(...)) return false;'
7892           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7893             return true;
7894           CmpSoFar = ExprResult();
7895         }
7896         return false;
7897       };
7898       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7899         Expr *E = dyn_cast<Expr>(EAsStmt);
7900         if (!E) {
7901           // Found an array comparison.
7902           if (FinishCmp() || Stmts.add(EAsStmt))
7903             return StmtError();
7904           continue;
7905         }
7906 
7907         if (CmpSoFar.isUnset()) {
7908           CmpSoFar = E;
7909           continue;
7910         }
7911         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7912         if (CmpSoFar.isInvalid())
7913           return StmtError();
7914       }
7915       if (FinishCmp())
7916         return StmtError();
7917       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7918       //   If no such index exists, V is true.
7919       if (RetVal.isUnset())
7920         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7921       break;
7922     }
7923 
7924     case DefaultedComparisonKind::ThreeWay: {
7925       // Per C++2a [class.spaceship]p3, as a fallback add:
7926       // return static_cast<R>(std::strong_ordering::equal);
7927       QualType StrongOrdering = S.CheckComparisonCategoryType(
7928           ComparisonCategoryType::StrongOrdering, Loc,
7929           Sema::ComparisonCategoryUsage::DefaultedOperator);
7930       if (StrongOrdering.isNull())
7931         return StmtError();
7932       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7933                              .getValueInfo(ComparisonCategoryResult::Equal)
7934                              ->VD;
7935       RetVal = getDecl(EqualVD);
7936       if (RetVal.isInvalid())
7937         return StmtError();
7938       RetVal = buildStaticCastToR(RetVal.get());
7939       break;
7940     }
7941 
7942     case DefaultedComparisonKind::NotEqual:
7943     case DefaultedComparisonKind::Relational:
7944       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7945       break;
7946     }
7947 
7948     // Build the final return statement.
7949     if (RetVal.isInvalid())
7950       return StmtError();
7951     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7952     if (ReturnStmt.isInvalid())
7953       return StmtError();
7954     Stmts.Stmts.push_back(ReturnStmt.get());
7955 
7956     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7957   }
7958 
7959 private:
7960   ExprResult getDecl(ValueDecl *VD) {
7961     return S.BuildDeclarationNameExpr(
7962         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7963   }
7964 
7965   ExprResult getParam(unsigned I) {
7966     ParmVarDecl *PD = FD->getParamDecl(I);
7967     return getDecl(PD);
7968   }
7969 
7970   ExprPair getCompleteObject() {
7971     unsigned Param = 0;
7972     ExprResult LHS;
7973     if (isa<CXXMethodDecl>(FD)) {
7974       // LHS is '*this'.
7975       LHS = S.ActOnCXXThis(Loc);
7976       if (!LHS.isInvalid())
7977         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7978     } else {
7979       LHS = getParam(Param++);
7980     }
7981     ExprResult RHS = getParam(Param++);
7982     assert(Param == FD->getNumParams());
7983     return {LHS, RHS};
7984   }
7985 
7986   ExprPair getBase(CXXBaseSpecifier *Base) {
7987     ExprPair Obj = getCompleteObject();
7988     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7989       return {ExprError(), ExprError()};
7990     CXXCastPath Path = {Base};
7991     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7992                                 CK_DerivedToBase, VK_LValue, &Path),
7993             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7994                                 CK_DerivedToBase, VK_LValue, &Path)};
7995   }
7996 
7997   ExprPair getField(FieldDecl *Field) {
7998     ExprPair Obj = getCompleteObject();
7999     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8000       return {ExprError(), ExprError()};
8001 
8002     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8003     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8004     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8005                                       CXXScopeSpec(), Field, Found, NameInfo),
8006             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8007                                       CXXScopeSpec(), Field, Found, NameInfo)};
8008   }
8009 
8010   // FIXME: When expanding a subobject, register a note in the code synthesis
8011   // stack to say which subobject we're comparing.
8012 
8013   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8014     if (Cond.isInvalid())
8015       return StmtError();
8016 
8017     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8018     if (NotCond.isInvalid())
8019       return StmtError();
8020 
8021     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8022     assert(!False.isInvalid() && "should never fail");
8023     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8024     if (ReturnFalse.isInvalid())
8025       return StmtError();
8026 
8027     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8028                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8029                                           Sema::ConditionKind::Boolean),
8030                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8031   }
8032 
8033   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8034                                  ExprPair Subobj) {
8035     QualType SizeType = S.Context.getSizeType();
8036     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8037 
8038     // Build 'size_t i$n = 0'.
8039     IdentifierInfo *IterationVarName = nullptr;
8040     {
8041       SmallString<8> Str;
8042       llvm::raw_svector_ostream OS(Str);
8043       OS << "i" << ArrayDepth;
8044       IterationVarName = &S.Context.Idents.get(OS.str());
8045     }
8046     VarDecl *IterationVar = VarDecl::Create(
8047         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8048         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8049     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8050     IterationVar->setInit(
8051         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8052     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8053 
8054     auto IterRef = [&] {
8055       ExprResult Ref = S.BuildDeclarationNameExpr(
8056           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8057           IterationVar);
8058       assert(!Ref.isInvalid() && "can't reference our own variable?");
8059       return Ref.get();
8060     };
8061 
8062     // Build 'i$n != Size'.
8063     ExprResult Cond = S.CreateBuiltinBinOp(
8064         Loc, BO_NE, IterRef(),
8065         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8066     assert(!Cond.isInvalid() && "should never fail");
8067 
8068     // Build '++i$n'.
8069     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8070     assert(!Inc.isInvalid() && "should never fail");
8071 
8072     // Build 'a[i$n]' and 'b[i$n]'.
8073     auto Index = [&](ExprResult E) {
8074       if (E.isInvalid())
8075         return ExprError();
8076       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8077     };
8078     Subobj.first = Index(Subobj.first);
8079     Subobj.second = Index(Subobj.second);
8080 
8081     // Compare the array elements.
8082     ++ArrayDepth;
8083     StmtResult Substmt = visitSubobject(Type, Subobj);
8084     --ArrayDepth;
8085 
8086     if (Substmt.isInvalid())
8087       return StmtError();
8088 
8089     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8090     // For outer levels or for an 'operator<=>' we already have a suitable
8091     // statement that returns as necessary.
8092     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8093       assert(DCK == DefaultedComparisonKind::Equal &&
8094              "should have non-expression statement");
8095       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8096       if (Substmt.isInvalid())
8097         return StmtError();
8098     }
8099 
8100     // Build 'for (...) ...'
8101     return S.ActOnForStmt(Loc, Loc, Init,
8102                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8103                                            Sema::ConditionKind::Boolean),
8104                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8105                           Substmt.get());
8106   }
8107 
8108   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8109     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8110       return StmtError();
8111 
8112     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8113     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8114     ExprResult Op;
8115     if (Type->isOverloadableType())
8116       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8117                                    Obj.second.get(), /*PerformADL=*/true,
8118                                    /*AllowRewrittenCandidates=*/true, FD);
8119     else
8120       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8121     if (Op.isInvalid())
8122       return StmtError();
8123 
8124     switch (DCK) {
8125     case DefaultedComparisonKind::None:
8126       llvm_unreachable("not a defaulted comparison");
8127 
8128     case DefaultedComparisonKind::Equal:
8129       // Per C++2a [class.eq]p2, each comparison is individually contextually
8130       // converted to bool.
8131       Op = S.PerformContextuallyConvertToBool(Op.get());
8132       if (Op.isInvalid())
8133         return StmtError();
8134       return Op.get();
8135 
8136     case DefaultedComparisonKind::ThreeWay: {
8137       // Per C++2a [class.spaceship]p3, form:
8138       //   if (R cmp = static_cast<R>(op); cmp != 0)
8139       //     return cmp;
8140       QualType R = FD->getReturnType();
8141       Op = buildStaticCastToR(Op.get());
8142       if (Op.isInvalid())
8143         return StmtError();
8144 
8145       // R cmp = ...;
8146       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8147       VarDecl *VD =
8148           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8149                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8150       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8151       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8152 
8153       // cmp != 0
8154       ExprResult VDRef = getDecl(VD);
8155       if (VDRef.isInvalid())
8156         return StmtError();
8157       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8158       Expr *Zero =
8159           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8160       ExprResult Comp;
8161       if (VDRef.get()->getType()->isOverloadableType())
8162         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8163                                        true, FD);
8164       else
8165         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8166       if (Comp.isInvalid())
8167         return StmtError();
8168       Sema::ConditionResult Cond = S.ActOnCondition(
8169           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8170       if (Cond.isInvalid())
8171         return StmtError();
8172 
8173       // return cmp;
8174       VDRef = getDecl(VD);
8175       if (VDRef.isInvalid())
8176         return StmtError();
8177       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8178       if (ReturnStmt.isInvalid())
8179         return StmtError();
8180 
8181       // if (...)
8182       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8183                            ReturnStmt.get(),
8184                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8185     }
8186 
8187     case DefaultedComparisonKind::NotEqual:
8188     case DefaultedComparisonKind::Relational:
8189       // C++2a [class.compare.secondary]p2:
8190       //   Otherwise, the operator function yields x @ y.
8191       return Op.get();
8192     }
8193     llvm_unreachable("");
8194   }
8195 
8196   /// Build "static_cast<R>(E)".
8197   ExprResult buildStaticCastToR(Expr *E) {
8198     QualType R = FD->getReturnType();
8199     assert(!R->isUndeducedType() && "type should have been deduced already");
8200 
8201     // Don't bother forming a no-op cast in the common case.
8202     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8203       return E;
8204     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8205                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8206                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8207   }
8208 };
8209 }
8210 
8211 /// Perform the unqualified lookups that might be needed to form a defaulted
8212 /// comparison function for the given operator.
8213 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8214                                                   UnresolvedSetImpl &Operators,
8215                                                   OverloadedOperatorKind Op) {
8216   auto Lookup = [&](OverloadedOperatorKind OO) {
8217     Self.LookupOverloadedOperatorName(OO, S, Operators);
8218   };
8219 
8220   // Every defaulted operator looks up itself.
8221   Lookup(Op);
8222   // ... and the rewritten form of itself, if any.
8223   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8224     Lookup(ExtraOp);
8225 
8226   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8227   // synthesize a three-way comparison from '<' and '=='. In a dependent
8228   // context, we also need to look up '==' in case we implicitly declare a
8229   // defaulted 'operator=='.
8230   if (Op == OO_Spaceship) {
8231     Lookup(OO_ExclaimEqual);
8232     Lookup(OO_Less);
8233     Lookup(OO_EqualEqual);
8234   }
8235 }
8236 
8237 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8238                                               DefaultedComparisonKind DCK) {
8239   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8240 
8241   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8242   assert(RD && "defaulted comparison is not defaulted in a class");
8243 
8244   // Perform any unqualified lookups we're going to need to default this
8245   // function.
8246   if (S) {
8247     UnresolvedSet<32> Operators;
8248     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8249                                           FD->getOverloadedOperator());
8250     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8251         Context, Operators.pairs()));
8252   }
8253 
8254   // C++2a [class.compare.default]p1:
8255   //   A defaulted comparison operator function for some class C shall be a
8256   //   non-template function declared in the member-specification of C that is
8257   //    -- a non-static const member of C having one parameter of type
8258   //       const C&, or
8259   //    -- a friend of C having two parameters of type const C& or two
8260   //       parameters of type C.
8261   QualType ExpectedParmType1 = Context.getRecordType(RD);
8262   QualType ExpectedParmType2 =
8263       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8264   if (isa<CXXMethodDecl>(FD))
8265     ExpectedParmType1 = ExpectedParmType2;
8266   for (const ParmVarDecl *Param : FD->parameters()) {
8267     if (!Param->getType()->isDependentType() &&
8268         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8269         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8270       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8271       // corresponding defaulted 'operator<=>' already.
8272       if (!FD->isImplicit()) {
8273         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8274             << (int)DCK << Param->getType() << ExpectedParmType1
8275             << !isa<CXXMethodDecl>(FD)
8276             << ExpectedParmType2 << Param->getSourceRange();
8277       }
8278       return true;
8279     }
8280   }
8281   if (FD->getNumParams() == 2 &&
8282       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8283                            FD->getParamDecl(1)->getType())) {
8284     if (!FD->isImplicit()) {
8285       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8286           << (int)DCK
8287           << FD->getParamDecl(0)->getType()
8288           << FD->getParamDecl(0)->getSourceRange()
8289           << FD->getParamDecl(1)->getType()
8290           << FD->getParamDecl(1)->getSourceRange();
8291     }
8292     return true;
8293   }
8294 
8295   // ... non-static const member ...
8296   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8297     assert(!MD->isStatic() && "comparison function cannot be a static member");
8298     if (!MD->isConst()) {
8299       SourceLocation InsertLoc;
8300       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8301         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8302       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8303       // corresponding defaulted 'operator<=>' already.
8304       if (!MD->isImplicit()) {
8305         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8306           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8307       }
8308 
8309       // Add the 'const' to the type to recover.
8310       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8311       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8312       EPI.TypeQuals.addConst();
8313       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8314                                           FPT->getParamTypes(), EPI));
8315     }
8316   } else {
8317     // A non-member function declared in a class must be a friend.
8318     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8319   }
8320 
8321   // C++2a [class.eq]p1, [class.rel]p1:
8322   //   A [defaulted comparison other than <=>] shall have a declared return
8323   //   type bool.
8324   if (DCK != DefaultedComparisonKind::ThreeWay &&
8325       !FD->getDeclaredReturnType()->isDependentType() &&
8326       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8327     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8328         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8329         << FD->getReturnTypeSourceRange();
8330     return true;
8331   }
8332   // C++2a [class.spaceship]p2 [P2002R0]:
8333   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8334   //   R shall not contain a placeholder type.
8335   if (DCK == DefaultedComparisonKind::ThreeWay &&
8336       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8337       !Context.hasSameType(FD->getDeclaredReturnType(),
8338                            Context.getAutoDeductType())) {
8339     Diag(FD->getLocation(),
8340          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8341         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8342         << FD->getReturnTypeSourceRange();
8343     return true;
8344   }
8345 
8346   // For a defaulted function in a dependent class, defer all remaining checks
8347   // until instantiation.
8348   if (RD->isDependentType())
8349     return false;
8350 
8351   // Determine whether the function should be defined as deleted.
8352   DefaultedComparisonInfo Info =
8353       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8354 
8355   bool First = FD == FD->getCanonicalDecl();
8356 
8357   // If we want to delete the function, then do so; there's nothing else to
8358   // check in that case.
8359   if (Info.Deleted) {
8360     if (!First) {
8361       // C++11 [dcl.fct.def.default]p4:
8362       //   [For a] user-provided explicitly-defaulted function [...] if such a
8363       //   function is implicitly defined as deleted, the program is ill-formed.
8364       //
8365       // This is really just a consequence of the general rule that you can
8366       // only delete a function on its first declaration.
8367       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8368           << FD->isImplicit() << (int)DCK;
8369       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8370                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8371           .visit();
8372       return true;
8373     }
8374 
8375     SetDeclDeleted(FD, FD->getLocation());
8376     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8377       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8378           << (int)DCK;
8379       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8380                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8381           .visit();
8382     }
8383     return false;
8384   }
8385 
8386   // C++2a [class.spaceship]p2:
8387   //   The return type is deduced as the common comparison type of R0, R1, ...
8388   if (DCK == DefaultedComparisonKind::ThreeWay &&
8389       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8390     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8391     if (RetLoc.isInvalid())
8392       RetLoc = FD->getBeginLoc();
8393     // FIXME: Should we really care whether we have the complete type and the
8394     // 'enumerator' constants here? A forward declaration seems sufficient.
8395     QualType Cat = CheckComparisonCategoryType(
8396         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8397     if (Cat.isNull())
8398       return true;
8399     Context.adjustDeducedFunctionResultType(
8400         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8401   }
8402 
8403   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8404   //   An explicitly-defaulted function that is not defined as deleted may be
8405   //   declared constexpr or consteval only if it is constexpr-compatible.
8406   // C++2a [class.compare.default]p3 [P2002R0]:
8407   //   A defaulted comparison function is constexpr-compatible if it satisfies
8408   //   the requirements for a constexpr function [...]
8409   // The only relevant requirements are that the parameter and return types are
8410   // literal types. The remaining conditions are checked by the analyzer.
8411   if (FD->isConstexpr()) {
8412     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8413         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8414         !Info.Constexpr) {
8415       Diag(FD->getBeginLoc(),
8416            diag::err_incorrect_defaulted_comparison_constexpr)
8417           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8418       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8419                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8420           .visit();
8421     }
8422   }
8423 
8424   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8425   //   If a constexpr-compatible function is explicitly defaulted on its first
8426   //   declaration, it is implicitly considered to be constexpr.
8427   // FIXME: Only applying this to the first declaration seems problematic, as
8428   // simple reorderings can affect the meaning of the program.
8429   if (First && !FD->isConstexpr() && Info.Constexpr)
8430     FD->setConstexprKind(CSK_constexpr);
8431 
8432   // C++2a [except.spec]p3:
8433   //   If a declaration of a function does not have a noexcept-specifier
8434   //   [and] is defaulted on its first declaration, [...] the exception
8435   //   specification is as specified below
8436   if (FD->getExceptionSpecType() == EST_None) {
8437     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8438     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8439     EPI.ExceptionSpec.Type = EST_Unevaluated;
8440     EPI.ExceptionSpec.SourceDecl = FD;
8441     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8442                                         FPT->getParamTypes(), EPI));
8443   }
8444 
8445   return false;
8446 }
8447 
8448 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8449                                              FunctionDecl *Spaceship) {
8450   Sema::CodeSynthesisContext Ctx;
8451   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8452   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8453   Ctx.Entity = Spaceship;
8454   pushCodeSynthesisContext(Ctx);
8455 
8456   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8457     EqualEqual->setImplicit();
8458 
8459   popCodeSynthesisContext();
8460 }
8461 
8462 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8463                                      DefaultedComparisonKind DCK) {
8464   assert(FD->isDefaulted() && !FD->isDeleted() &&
8465          !FD->doesThisDeclarationHaveABody());
8466   if (FD->willHaveBody() || FD->isInvalidDecl())
8467     return;
8468 
8469   SynthesizedFunctionScope Scope(*this, FD);
8470 
8471   // Add a context note for diagnostics produced after this point.
8472   Scope.addContextNote(UseLoc);
8473 
8474   {
8475     // Build and set up the function body.
8476     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8477     SourceLocation BodyLoc =
8478         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8479     StmtResult Body =
8480         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8481     if (Body.isInvalid()) {
8482       FD->setInvalidDecl();
8483       return;
8484     }
8485     FD->setBody(Body.get());
8486     FD->markUsed(Context);
8487   }
8488 
8489   // The exception specification is needed because we are defining the
8490   // function. Note that this will reuse the body we just built.
8491   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8492 
8493   if (ASTMutationListener *L = getASTMutationListener())
8494     L->CompletedImplicitDefinition(FD);
8495 }
8496 
8497 static Sema::ImplicitExceptionSpecification
8498 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8499                                         FunctionDecl *FD,
8500                                         Sema::DefaultedComparisonKind DCK) {
8501   ComputingExceptionSpec CES(S, FD, Loc);
8502   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8503 
8504   if (FD->isInvalidDecl())
8505     return ExceptSpec;
8506 
8507   // The common case is that we just defined the comparison function. In that
8508   // case, just look at whether the body can throw.
8509   if (FD->hasBody()) {
8510     ExceptSpec.CalledStmt(FD->getBody());
8511   } else {
8512     // Otherwise, build a body so we can check it. This should ideally only
8513     // happen when we're not actually marking the function referenced. (This is
8514     // only really important for efficiency: we don't want to build and throw
8515     // away bodies for comparison functions more than we strictly need to.)
8516 
8517     // Pretend to synthesize the function body in an unevaluated context.
8518     // Note that we can't actually just go ahead and define the function here:
8519     // we are not permitted to mark its callees as referenced.
8520     Sema::SynthesizedFunctionScope Scope(S, FD);
8521     EnterExpressionEvaluationContext Context(
8522         S, Sema::ExpressionEvaluationContext::Unevaluated);
8523 
8524     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8525     SourceLocation BodyLoc =
8526         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8527     StmtResult Body =
8528         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8529     if (!Body.isInvalid())
8530       ExceptSpec.CalledStmt(Body.get());
8531 
8532     // FIXME: Can we hold onto this body and just transform it to potentially
8533     // evaluated when we're asked to define the function rather than rebuilding
8534     // it? Either that, or we should only build the bits of the body that we
8535     // need (the expressions, not the statements).
8536   }
8537 
8538   return ExceptSpec;
8539 }
8540 
8541 void Sema::CheckDelayedMemberExceptionSpecs() {
8542   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8543   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8544 
8545   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8546   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8547 
8548   // Perform any deferred checking of exception specifications for virtual
8549   // destructors.
8550   for (auto &Check : Overriding)
8551     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8552 
8553   // Perform any deferred checking of exception specifications for befriended
8554   // special members.
8555   for (auto &Check : Equivalent)
8556     CheckEquivalentExceptionSpec(Check.second, Check.first);
8557 }
8558 
8559 namespace {
8560 /// CRTP base class for visiting operations performed by a special member
8561 /// function (or inherited constructor).
8562 template<typename Derived>
8563 struct SpecialMemberVisitor {
8564   Sema &S;
8565   CXXMethodDecl *MD;
8566   Sema::CXXSpecialMember CSM;
8567   Sema::InheritedConstructorInfo *ICI;
8568 
8569   // Properties of the special member, computed for convenience.
8570   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8571 
8572   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8573                        Sema::InheritedConstructorInfo *ICI)
8574       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8575     switch (CSM) {
8576     case Sema::CXXDefaultConstructor:
8577     case Sema::CXXCopyConstructor:
8578     case Sema::CXXMoveConstructor:
8579       IsConstructor = true;
8580       break;
8581     case Sema::CXXCopyAssignment:
8582     case Sema::CXXMoveAssignment:
8583       IsAssignment = true;
8584       break;
8585     case Sema::CXXDestructor:
8586       break;
8587     case Sema::CXXInvalid:
8588       llvm_unreachable("invalid special member kind");
8589     }
8590 
8591     if (MD->getNumParams()) {
8592       if (const ReferenceType *RT =
8593               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8594         ConstArg = RT->getPointeeType().isConstQualified();
8595     }
8596   }
8597 
8598   Derived &getDerived() { return static_cast<Derived&>(*this); }
8599 
8600   /// Is this a "move" special member?
8601   bool isMove() const {
8602     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8603   }
8604 
8605   /// Look up the corresponding special member in the given class.
8606   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8607                                              unsigned Quals, bool IsMutable) {
8608     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8609                                        ConstArg && !IsMutable);
8610   }
8611 
8612   /// Look up the constructor for the specified base class to see if it's
8613   /// overridden due to this being an inherited constructor.
8614   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8615     if (!ICI)
8616       return {};
8617     assert(CSM == Sema::CXXDefaultConstructor);
8618     auto *BaseCtor =
8619       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8620     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8621       return MD;
8622     return {};
8623   }
8624 
8625   /// A base or member subobject.
8626   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8627 
8628   /// Get the location to use for a subobject in diagnostics.
8629   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8630     // FIXME: For an indirect virtual base, the direct base leading to
8631     // the indirect virtual base would be a more useful choice.
8632     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8633       return B->getBaseTypeLoc();
8634     else
8635       return Subobj.get<FieldDecl*>()->getLocation();
8636   }
8637 
8638   enum BasesToVisit {
8639     /// Visit all non-virtual (direct) bases.
8640     VisitNonVirtualBases,
8641     /// Visit all direct bases, virtual or not.
8642     VisitDirectBases,
8643     /// Visit all non-virtual bases, and all virtual bases if the class
8644     /// is not abstract.
8645     VisitPotentiallyConstructedBases,
8646     /// Visit all direct or virtual bases.
8647     VisitAllBases
8648   };
8649 
8650   // Visit the bases and members of the class.
8651   bool visit(BasesToVisit Bases) {
8652     CXXRecordDecl *RD = MD->getParent();
8653 
8654     if (Bases == VisitPotentiallyConstructedBases)
8655       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8656 
8657     for (auto &B : RD->bases())
8658       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8659           getDerived().visitBase(&B))
8660         return true;
8661 
8662     if (Bases == VisitAllBases)
8663       for (auto &B : RD->vbases())
8664         if (getDerived().visitBase(&B))
8665           return true;
8666 
8667     for (auto *F : RD->fields())
8668       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8669           getDerived().visitField(F))
8670         return true;
8671 
8672     return false;
8673   }
8674 };
8675 }
8676 
8677 namespace {
8678 struct SpecialMemberDeletionInfo
8679     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8680   bool Diagnose;
8681 
8682   SourceLocation Loc;
8683 
8684   bool AllFieldsAreConst;
8685 
8686   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8687                             Sema::CXXSpecialMember CSM,
8688                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8689       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8690         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8691 
8692   bool inUnion() const { return MD->getParent()->isUnion(); }
8693 
8694   Sema::CXXSpecialMember getEffectiveCSM() {
8695     return ICI ? Sema::CXXInvalid : CSM;
8696   }
8697 
8698   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8699 
8700   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8701   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8702 
8703   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8704   bool shouldDeleteForField(FieldDecl *FD);
8705   bool shouldDeleteForAllConstMembers();
8706 
8707   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8708                                      unsigned Quals);
8709   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8710                                     Sema::SpecialMemberOverloadResult SMOR,
8711                                     bool IsDtorCallInCtor);
8712 
8713   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8714 };
8715 }
8716 
8717 /// Is the given special member inaccessible when used on the given
8718 /// sub-object.
8719 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8720                                              CXXMethodDecl *target) {
8721   /// If we're operating on a base class, the object type is the
8722   /// type of this special member.
8723   QualType objectTy;
8724   AccessSpecifier access = target->getAccess();
8725   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8726     objectTy = S.Context.getTypeDeclType(MD->getParent());
8727     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8728 
8729   // If we're operating on a field, the object type is the type of the field.
8730   } else {
8731     objectTy = S.Context.getTypeDeclType(target->getParent());
8732   }
8733 
8734   return S.isMemberAccessibleForDeletion(
8735       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8736 }
8737 
8738 /// Check whether we should delete a special member due to the implicit
8739 /// definition containing a call to a special member of a subobject.
8740 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8741     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8742     bool IsDtorCallInCtor) {
8743   CXXMethodDecl *Decl = SMOR.getMethod();
8744   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8745 
8746   int DiagKind = -1;
8747 
8748   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8749     DiagKind = !Decl ? 0 : 1;
8750   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8751     DiagKind = 2;
8752   else if (!isAccessible(Subobj, Decl))
8753     DiagKind = 3;
8754   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8755            !Decl->isTrivial()) {
8756     // A member of a union must have a trivial corresponding special member.
8757     // As a weird special case, a destructor call from a union's constructor
8758     // must be accessible and non-deleted, but need not be trivial. Such a
8759     // destructor is never actually called, but is semantically checked as
8760     // if it were.
8761     DiagKind = 4;
8762   }
8763 
8764   if (DiagKind == -1)
8765     return false;
8766 
8767   if (Diagnose) {
8768     if (Field) {
8769       S.Diag(Field->getLocation(),
8770              diag::note_deleted_special_member_class_subobject)
8771         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8772         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8773     } else {
8774       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8775       S.Diag(Base->getBeginLoc(),
8776              diag::note_deleted_special_member_class_subobject)
8777           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8778           << Base->getType() << DiagKind << IsDtorCallInCtor
8779           << /*IsObjCPtr*/false;
8780     }
8781 
8782     if (DiagKind == 1)
8783       S.NoteDeletedFunction(Decl);
8784     // FIXME: Explain inaccessibility if DiagKind == 3.
8785   }
8786 
8787   return true;
8788 }
8789 
8790 /// Check whether we should delete a special member function due to having a
8791 /// direct or virtual base class or non-static data member of class type M.
8792 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8793     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8794   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8795   bool IsMutable = Field && Field->isMutable();
8796 
8797   // C++11 [class.ctor]p5:
8798   // -- any direct or virtual base class, or non-static data member with no
8799   //    brace-or-equal-initializer, has class type M (or array thereof) and
8800   //    either M has no default constructor or overload resolution as applied
8801   //    to M's default constructor results in an ambiguity or in a function
8802   //    that is deleted or inaccessible
8803   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8804   // -- a direct or virtual base class B that cannot be copied/moved because
8805   //    overload resolution, as applied to B's corresponding special member,
8806   //    results in an ambiguity or a function that is deleted or inaccessible
8807   //    from the defaulted special member
8808   // C++11 [class.dtor]p5:
8809   // -- any direct or virtual base class [...] has a type with a destructor
8810   //    that is deleted or inaccessible
8811   if (!(CSM == Sema::CXXDefaultConstructor &&
8812         Field && Field->hasInClassInitializer()) &&
8813       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8814                                    false))
8815     return true;
8816 
8817   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8818   // -- any direct or virtual base class or non-static data member has a
8819   //    type with a destructor that is deleted or inaccessible
8820   if (IsConstructor) {
8821     Sema::SpecialMemberOverloadResult SMOR =
8822         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8823                               false, false, false, false, false);
8824     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8825       return true;
8826   }
8827 
8828   return false;
8829 }
8830 
8831 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8832     FieldDecl *FD, QualType FieldType) {
8833   // The defaulted special functions are defined as deleted if this is a variant
8834   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8835   // type under ARC.
8836   if (!FieldType.hasNonTrivialObjCLifetime())
8837     return false;
8838 
8839   // Don't make the defaulted default constructor defined as deleted if the
8840   // member has an in-class initializer.
8841   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8842     return false;
8843 
8844   if (Diagnose) {
8845     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8846     S.Diag(FD->getLocation(),
8847            diag::note_deleted_special_member_class_subobject)
8848         << getEffectiveCSM() << ParentClass << /*IsField*/true
8849         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8850   }
8851 
8852   return true;
8853 }
8854 
8855 /// Check whether we should delete a special member function due to the class
8856 /// having a particular direct or virtual base class.
8857 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8858   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8859   // If program is correct, BaseClass cannot be null, but if it is, the error
8860   // must be reported elsewhere.
8861   if (!BaseClass)
8862     return false;
8863   // If we have an inheriting constructor, check whether we're calling an
8864   // inherited constructor instead of a default constructor.
8865   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8866   if (auto *BaseCtor = SMOR.getMethod()) {
8867     // Note that we do not check access along this path; other than that,
8868     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8869     // FIXME: Check that the base has a usable destructor! Sink this into
8870     // shouldDeleteForClassSubobject.
8871     if (BaseCtor->isDeleted() && Diagnose) {
8872       S.Diag(Base->getBeginLoc(),
8873              diag::note_deleted_special_member_class_subobject)
8874           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8875           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8876           << /*IsObjCPtr*/false;
8877       S.NoteDeletedFunction(BaseCtor);
8878     }
8879     return BaseCtor->isDeleted();
8880   }
8881   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8882 }
8883 
8884 /// Check whether we should delete a special member function due to the class
8885 /// having a particular non-static data member.
8886 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8887   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8888   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8889 
8890   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8891     return true;
8892 
8893   if (CSM == Sema::CXXDefaultConstructor) {
8894     // For a default constructor, all references must be initialized in-class
8895     // and, if a union, it must have a non-const member.
8896     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8897       if (Diagnose)
8898         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8899           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8900       return true;
8901     }
8902     // C++11 [class.ctor]p5: any non-variant non-static data member of
8903     // const-qualified type (or array thereof) with no
8904     // brace-or-equal-initializer does not have a user-provided default
8905     // constructor.
8906     if (!inUnion() && FieldType.isConstQualified() &&
8907         !FD->hasInClassInitializer() &&
8908         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8909       if (Diagnose)
8910         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8911           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8912       return true;
8913     }
8914 
8915     if (inUnion() && !FieldType.isConstQualified())
8916       AllFieldsAreConst = false;
8917   } else if (CSM == Sema::CXXCopyConstructor) {
8918     // For a copy constructor, data members must not be of rvalue reference
8919     // type.
8920     if (FieldType->isRValueReferenceType()) {
8921       if (Diagnose)
8922         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8923           << MD->getParent() << FD << FieldType;
8924       return true;
8925     }
8926   } else if (IsAssignment) {
8927     // For an assignment operator, data members must not be of reference type.
8928     if (FieldType->isReferenceType()) {
8929       if (Diagnose)
8930         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8931           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8932       return true;
8933     }
8934     if (!FieldRecord && FieldType.isConstQualified()) {
8935       // C++11 [class.copy]p23:
8936       // -- a non-static data member of const non-class type (or array thereof)
8937       if (Diagnose)
8938         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8939           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8940       return true;
8941     }
8942   }
8943 
8944   if (FieldRecord) {
8945     // Some additional restrictions exist on the variant members.
8946     if (!inUnion() && FieldRecord->isUnion() &&
8947         FieldRecord->isAnonymousStructOrUnion()) {
8948       bool AllVariantFieldsAreConst = true;
8949 
8950       // FIXME: Handle anonymous unions declared within anonymous unions.
8951       for (auto *UI : FieldRecord->fields()) {
8952         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8953 
8954         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8955           return true;
8956 
8957         if (!UnionFieldType.isConstQualified())
8958           AllVariantFieldsAreConst = false;
8959 
8960         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8961         if (UnionFieldRecord &&
8962             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8963                                           UnionFieldType.getCVRQualifiers()))
8964           return true;
8965       }
8966 
8967       // At least one member in each anonymous union must be non-const
8968       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8969           !FieldRecord->field_empty()) {
8970         if (Diagnose)
8971           S.Diag(FieldRecord->getLocation(),
8972                  diag::note_deleted_default_ctor_all_const)
8973             << !!ICI << MD->getParent() << /*anonymous union*/1;
8974         return true;
8975       }
8976 
8977       // Don't check the implicit member of the anonymous union type.
8978       // This is technically non-conformant, but sanity demands it.
8979       return false;
8980     }
8981 
8982     if (shouldDeleteForClassSubobject(FieldRecord, FD,
8983                                       FieldType.getCVRQualifiers()))
8984       return true;
8985   }
8986 
8987   return false;
8988 }
8989 
8990 /// C++11 [class.ctor] p5:
8991 ///   A defaulted default constructor for a class X is defined as deleted if
8992 /// X is a union and all of its variant members are of const-qualified type.
8993 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8994   // This is a silly definition, because it gives an empty union a deleted
8995   // default constructor. Don't do that.
8996   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
8997     bool AnyFields = false;
8998     for (auto *F : MD->getParent()->fields())
8999       if ((AnyFields = !F->isUnnamedBitfield()))
9000         break;
9001     if (!AnyFields)
9002       return false;
9003     if (Diagnose)
9004       S.Diag(MD->getParent()->getLocation(),
9005              diag::note_deleted_default_ctor_all_const)
9006         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9007     return true;
9008   }
9009   return false;
9010 }
9011 
9012 /// Determine whether a defaulted special member function should be defined as
9013 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9014 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9015 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9016                                      InheritedConstructorInfo *ICI,
9017                                      bool Diagnose) {
9018   if (MD->isInvalidDecl())
9019     return false;
9020   CXXRecordDecl *RD = MD->getParent();
9021   assert(!RD->isDependentType() && "do deletion after instantiation");
9022   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9023     return false;
9024 
9025   // C++11 [expr.lambda.prim]p19:
9026   //   The closure type associated with a lambda-expression has a
9027   //   deleted (8.4.3) default constructor and a deleted copy
9028   //   assignment operator.
9029   // C++2a adds back these operators if the lambda has no lambda-capture.
9030   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9031       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9032     if (Diagnose)
9033       Diag(RD->getLocation(), diag::note_lambda_decl);
9034     return true;
9035   }
9036 
9037   // For an anonymous struct or union, the copy and assignment special members
9038   // will never be used, so skip the check. For an anonymous union declared at
9039   // namespace scope, the constructor and destructor are used.
9040   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9041       RD->isAnonymousStructOrUnion())
9042     return false;
9043 
9044   // C++11 [class.copy]p7, p18:
9045   //   If the class definition declares a move constructor or move assignment
9046   //   operator, an implicitly declared copy constructor or copy assignment
9047   //   operator is defined as deleted.
9048   if (MD->isImplicit() &&
9049       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9050     CXXMethodDecl *UserDeclaredMove = nullptr;
9051 
9052     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9053     // deletion of the corresponding copy operation, not both copy operations.
9054     // MSVC 2015 has adopted the standards conforming behavior.
9055     bool DeletesOnlyMatchingCopy =
9056         getLangOpts().MSVCCompat &&
9057         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9058 
9059     if (RD->hasUserDeclaredMoveConstructor() &&
9060         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9061       if (!Diagnose) return true;
9062 
9063       // Find any user-declared move constructor.
9064       for (auto *I : RD->ctors()) {
9065         if (I->isMoveConstructor()) {
9066           UserDeclaredMove = I;
9067           break;
9068         }
9069       }
9070       assert(UserDeclaredMove);
9071     } else if (RD->hasUserDeclaredMoveAssignment() &&
9072                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9073       if (!Diagnose) return true;
9074 
9075       // Find any user-declared move assignment operator.
9076       for (auto *I : RD->methods()) {
9077         if (I->isMoveAssignmentOperator()) {
9078           UserDeclaredMove = I;
9079           break;
9080         }
9081       }
9082       assert(UserDeclaredMove);
9083     }
9084 
9085     if (UserDeclaredMove) {
9086       Diag(UserDeclaredMove->getLocation(),
9087            diag::note_deleted_copy_user_declared_move)
9088         << (CSM == CXXCopyAssignment) << RD
9089         << UserDeclaredMove->isMoveAssignmentOperator();
9090       return true;
9091     }
9092   }
9093 
9094   // Do access control from the special member function
9095   ContextRAII MethodContext(*this, MD);
9096 
9097   // C++11 [class.dtor]p5:
9098   // -- for a virtual destructor, lookup of the non-array deallocation function
9099   //    results in an ambiguity or in a function that is deleted or inaccessible
9100   if (CSM == CXXDestructor && MD->isVirtual()) {
9101     FunctionDecl *OperatorDelete = nullptr;
9102     DeclarationName Name =
9103       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9104     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9105                                  OperatorDelete, /*Diagnose*/false)) {
9106       if (Diagnose)
9107         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9108       return true;
9109     }
9110   }
9111 
9112   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9113 
9114   // Per DR1611, do not consider virtual bases of constructors of abstract
9115   // classes, since we are not going to construct them.
9116   // Per DR1658, do not consider virtual bases of destructors of abstract
9117   // classes either.
9118   // Per DR2180, for assignment operators we only assign (and thus only
9119   // consider) direct bases.
9120   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9121                                  : SMI.VisitPotentiallyConstructedBases))
9122     return true;
9123 
9124   if (SMI.shouldDeleteForAllConstMembers())
9125     return true;
9126 
9127   if (getLangOpts().CUDA) {
9128     // We should delete the special member in CUDA mode if target inference
9129     // failed.
9130     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9131     // is treated as certain special member, which may not reflect what special
9132     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9133     // expects CSM to match MD, therefore recalculate CSM.
9134     assert(ICI || CSM == getSpecialMember(MD));
9135     auto RealCSM = CSM;
9136     if (ICI)
9137       RealCSM = getSpecialMember(MD);
9138 
9139     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9140                                                    SMI.ConstArg, Diagnose);
9141   }
9142 
9143   return false;
9144 }
9145 
9146 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9147   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9148   assert(DFK && "not a defaultable function");
9149   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9150 
9151   if (DFK.isSpecialMember()) {
9152     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9153                               nullptr, /*Diagnose=*/true);
9154   } else {
9155     DefaultedComparisonAnalyzer(
9156         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9157         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9158         .visit();
9159   }
9160 }
9161 
9162 /// Perform lookup for a special member of the specified kind, and determine
9163 /// whether it is trivial. If the triviality can be determined without the
9164 /// lookup, skip it. This is intended for use when determining whether a
9165 /// special member of a containing object is trivial, and thus does not ever
9166 /// perform overload resolution for default constructors.
9167 ///
9168 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9169 /// member that was most likely to be intended to be trivial, if any.
9170 ///
9171 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9172 /// determine whether the special member is trivial.
9173 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9174                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9175                                      bool ConstRHS,
9176                                      Sema::TrivialABIHandling TAH,
9177                                      CXXMethodDecl **Selected) {
9178   if (Selected)
9179     *Selected = nullptr;
9180 
9181   switch (CSM) {
9182   case Sema::CXXInvalid:
9183     llvm_unreachable("not a special member");
9184 
9185   case Sema::CXXDefaultConstructor:
9186     // C++11 [class.ctor]p5:
9187     //   A default constructor is trivial if:
9188     //    - all the [direct subobjects] have trivial default constructors
9189     //
9190     // Note, no overload resolution is performed in this case.
9191     if (RD->hasTrivialDefaultConstructor())
9192       return true;
9193 
9194     if (Selected) {
9195       // If there's a default constructor which could have been trivial, dig it
9196       // out. Otherwise, if there's any user-provided default constructor, point
9197       // to that as an example of why there's not a trivial one.
9198       CXXConstructorDecl *DefCtor = nullptr;
9199       if (RD->needsImplicitDefaultConstructor())
9200         S.DeclareImplicitDefaultConstructor(RD);
9201       for (auto *CI : RD->ctors()) {
9202         if (!CI->isDefaultConstructor())
9203           continue;
9204         DefCtor = CI;
9205         if (!DefCtor->isUserProvided())
9206           break;
9207       }
9208 
9209       *Selected = DefCtor;
9210     }
9211 
9212     return false;
9213 
9214   case Sema::CXXDestructor:
9215     // C++11 [class.dtor]p5:
9216     //   A destructor is trivial if:
9217     //    - all the direct [subobjects] have trivial destructors
9218     if (RD->hasTrivialDestructor() ||
9219         (TAH == Sema::TAH_ConsiderTrivialABI &&
9220          RD->hasTrivialDestructorForCall()))
9221       return true;
9222 
9223     if (Selected) {
9224       if (RD->needsImplicitDestructor())
9225         S.DeclareImplicitDestructor(RD);
9226       *Selected = RD->getDestructor();
9227     }
9228 
9229     return false;
9230 
9231   case Sema::CXXCopyConstructor:
9232     // C++11 [class.copy]p12:
9233     //   A copy constructor is trivial if:
9234     //    - the constructor selected to copy each direct [subobject] is trivial
9235     if (RD->hasTrivialCopyConstructor() ||
9236         (TAH == Sema::TAH_ConsiderTrivialABI &&
9237          RD->hasTrivialCopyConstructorForCall())) {
9238       if (Quals == Qualifiers::Const)
9239         // We must either select the trivial copy constructor or reach an
9240         // ambiguity; no need to actually perform overload resolution.
9241         return true;
9242     } else if (!Selected) {
9243       return false;
9244     }
9245     // In C++98, we are not supposed to perform overload resolution here, but we
9246     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9247     // cases like B as having a non-trivial copy constructor:
9248     //   struct A { template<typename T> A(T&); };
9249     //   struct B { mutable A a; };
9250     goto NeedOverloadResolution;
9251 
9252   case Sema::CXXCopyAssignment:
9253     // C++11 [class.copy]p25:
9254     //   A copy assignment operator is trivial if:
9255     //    - the assignment operator selected to copy each direct [subobject] is
9256     //      trivial
9257     if (RD->hasTrivialCopyAssignment()) {
9258       if (Quals == Qualifiers::Const)
9259         return true;
9260     } else if (!Selected) {
9261       return false;
9262     }
9263     // In C++98, we are not supposed to perform overload resolution here, but we
9264     // treat that as a language defect.
9265     goto NeedOverloadResolution;
9266 
9267   case Sema::CXXMoveConstructor:
9268   case Sema::CXXMoveAssignment:
9269   NeedOverloadResolution:
9270     Sema::SpecialMemberOverloadResult SMOR =
9271         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9272 
9273     // The standard doesn't describe how to behave if the lookup is ambiguous.
9274     // We treat it as not making the member non-trivial, just like the standard
9275     // mandates for the default constructor. This should rarely matter, because
9276     // the member will also be deleted.
9277     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9278       return true;
9279 
9280     if (!SMOR.getMethod()) {
9281       assert(SMOR.getKind() ==
9282              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9283       return false;
9284     }
9285 
9286     // We deliberately don't check if we found a deleted special member. We're
9287     // not supposed to!
9288     if (Selected)
9289       *Selected = SMOR.getMethod();
9290 
9291     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9292         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9293       return SMOR.getMethod()->isTrivialForCall();
9294     return SMOR.getMethod()->isTrivial();
9295   }
9296 
9297   llvm_unreachable("unknown special method kind");
9298 }
9299 
9300 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9301   for (auto *CI : RD->ctors())
9302     if (!CI->isImplicit())
9303       return CI;
9304 
9305   // Look for constructor templates.
9306   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9307   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9308     if (CXXConstructorDecl *CD =
9309           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9310       return CD;
9311   }
9312 
9313   return nullptr;
9314 }
9315 
9316 /// The kind of subobject we are checking for triviality. The values of this
9317 /// enumeration are used in diagnostics.
9318 enum TrivialSubobjectKind {
9319   /// The subobject is a base class.
9320   TSK_BaseClass,
9321   /// The subobject is a non-static data member.
9322   TSK_Field,
9323   /// The object is actually the complete object.
9324   TSK_CompleteObject
9325 };
9326 
9327 /// Check whether the special member selected for a given type would be trivial.
9328 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9329                                       QualType SubType, bool ConstRHS,
9330                                       Sema::CXXSpecialMember CSM,
9331                                       TrivialSubobjectKind Kind,
9332                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9333   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9334   if (!SubRD)
9335     return true;
9336 
9337   CXXMethodDecl *Selected;
9338   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9339                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9340     return true;
9341 
9342   if (Diagnose) {
9343     if (ConstRHS)
9344       SubType.addConst();
9345 
9346     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9347       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9348         << Kind << SubType.getUnqualifiedType();
9349       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9350         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9351     } else if (!Selected)
9352       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9353         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9354     else if (Selected->isUserProvided()) {
9355       if (Kind == TSK_CompleteObject)
9356         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9357           << Kind << SubType.getUnqualifiedType() << CSM;
9358       else {
9359         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9360           << Kind << SubType.getUnqualifiedType() << CSM;
9361         S.Diag(Selected->getLocation(), diag::note_declared_at);
9362       }
9363     } else {
9364       if (Kind != TSK_CompleteObject)
9365         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9366           << Kind << SubType.getUnqualifiedType() << CSM;
9367 
9368       // Explain why the defaulted or deleted special member isn't trivial.
9369       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9370                                Diagnose);
9371     }
9372   }
9373 
9374   return false;
9375 }
9376 
9377 /// Check whether the members of a class type allow a special member to be
9378 /// trivial.
9379 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9380                                      Sema::CXXSpecialMember CSM,
9381                                      bool ConstArg,
9382                                      Sema::TrivialABIHandling TAH,
9383                                      bool Diagnose) {
9384   for (const auto *FI : RD->fields()) {
9385     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9386       continue;
9387 
9388     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9389 
9390     // Pretend anonymous struct or union members are members of this class.
9391     if (FI->isAnonymousStructOrUnion()) {
9392       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9393                                     CSM, ConstArg, TAH, Diagnose))
9394         return false;
9395       continue;
9396     }
9397 
9398     // C++11 [class.ctor]p5:
9399     //   A default constructor is trivial if [...]
9400     //    -- no non-static data member of its class has a
9401     //       brace-or-equal-initializer
9402     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9403       if (Diagnose)
9404         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
9405       return false;
9406     }
9407 
9408     // Objective C ARC 4.3.5:
9409     //   [...] nontrivally ownership-qualified types are [...] not trivially
9410     //   default constructible, copy constructible, move constructible, copy
9411     //   assignable, move assignable, or destructible [...]
9412     if (FieldType.hasNonTrivialObjCLifetime()) {
9413       if (Diagnose)
9414         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9415           << RD << FieldType.getObjCLifetime();
9416       return false;
9417     }
9418 
9419     bool ConstRHS = ConstArg && !FI->isMutable();
9420     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9421                                    CSM, TSK_Field, TAH, Diagnose))
9422       return false;
9423   }
9424 
9425   return true;
9426 }
9427 
9428 /// Diagnose why the specified class does not have a trivial special member of
9429 /// the given kind.
9430 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9431   QualType Ty = Context.getRecordType(RD);
9432 
9433   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9434   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9435                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9436                             /*Diagnose*/true);
9437 }
9438 
9439 /// Determine whether a defaulted or deleted special member function is trivial,
9440 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9441 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9442 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9443                                   TrivialABIHandling TAH, bool Diagnose) {
9444   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9445 
9446   CXXRecordDecl *RD = MD->getParent();
9447 
9448   bool ConstArg = false;
9449 
9450   // C++11 [class.copy]p12, p25: [DR1593]
9451   //   A [special member] is trivial if [...] its parameter-type-list is
9452   //   equivalent to the parameter-type-list of an implicit declaration [...]
9453   switch (CSM) {
9454   case CXXDefaultConstructor:
9455   case CXXDestructor:
9456     // Trivial default constructors and destructors cannot have parameters.
9457     break;
9458 
9459   case CXXCopyConstructor:
9460   case CXXCopyAssignment: {
9461     // Trivial copy operations always have const, non-volatile parameter types.
9462     ConstArg = true;
9463     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9464     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9465     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9466       if (Diagnose)
9467         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9468           << Param0->getSourceRange() << Param0->getType()
9469           << Context.getLValueReferenceType(
9470                Context.getRecordType(RD).withConst());
9471       return false;
9472     }
9473     break;
9474   }
9475 
9476   case CXXMoveConstructor:
9477   case CXXMoveAssignment: {
9478     // Trivial move operations always have non-cv-qualified parameters.
9479     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9480     const RValueReferenceType *RT =
9481       Param0->getType()->getAs<RValueReferenceType>();
9482     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9483       if (Diagnose)
9484         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9485           << Param0->getSourceRange() << Param0->getType()
9486           << Context.getRValueReferenceType(Context.getRecordType(RD));
9487       return false;
9488     }
9489     break;
9490   }
9491 
9492   case CXXInvalid:
9493     llvm_unreachable("not a special member");
9494   }
9495 
9496   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9497     if (Diagnose)
9498       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9499            diag::note_nontrivial_default_arg)
9500         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9501     return false;
9502   }
9503   if (MD->isVariadic()) {
9504     if (Diagnose)
9505       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9506     return false;
9507   }
9508 
9509   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9510   //   A copy/move [constructor or assignment operator] is trivial if
9511   //    -- the [member] selected to copy/move each direct base class subobject
9512   //       is trivial
9513   //
9514   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9515   //   A [default constructor or destructor] is trivial if
9516   //    -- all the direct base classes have trivial [default constructors or
9517   //       destructors]
9518   for (const auto &BI : RD->bases())
9519     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9520                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9521       return false;
9522 
9523   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9524   //   A copy/move [constructor or assignment operator] for a class X is
9525   //   trivial if
9526   //    -- for each non-static data member of X that is of class type (or array
9527   //       thereof), the constructor selected to copy/move that member is
9528   //       trivial
9529   //
9530   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9531   //   A [default constructor or destructor] is trivial if
9532   //    -- for all of the non-static data members of its class that are of class
9533   //       type (or array thereof), each such class has a trivial [default
9534   //       constructor or destructor]
9535   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9536     return false;
9537 
9538   // C++11 [class.dtor]p5:
9539   //   A destructor is trivial if [...]
9540   //    -- the destructor is not virtual
9541   if (CSM == CXXDestructor && MD->isVirtual()) {
9542     if (Diagnose)
9543       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9544     return false;
9545   }
9546 
9547   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9548   //   A [special member] for class X is trivial if [...]
9549   //    -- class X has no virtual functions and no virtual base classes
9550   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9551     if (!Diagnose)
9552       return false;
9553 
9554     if (RD->getNumVBases()) {
9555       // Check for virtual bases. We already know that the corresponding
9556       // member in all bases is trivial, so vbases must all be direct.
9557       CXXBaseSpecifier &BS = *RD->vbases_begin();
9558       assert(BS.isVirtual());
9559       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9560       return false;
9561     }
9562 
9563     // Must have a virtual method.
9564     for (const auto *MI : RD->methods()) {
9565       if (MI->isVirtual()) {
9566         SourceLocation MLoc = MI->getBeginLoc();
9567         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9568         return false;
9569       }
9570     }
9571 
9572     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9573   }
9574 
9575   // Looks like it's trivial!
9576   return true;
9577 }
9578 
9579 namespace {
9580 struct FindHiddenVirtualMethod {
9581   Sema *S;
9582   CXXMethodDecl *Method;
9583   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9584   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9585 
9586 private:
9587   /// Check whether any most overridden method from MD in Methods
9588   static bool CheckMostOverridenMethods(
9589       const CXXMethodDecl *MD,
9590       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9591     if (MD->size_overridden_methods() == 0)
9592       return Methods.count(MD->getCanonicalDecl());
9593     for (const CXXMethodDecl *O : MD->overridden_methods())
9594       if (CheckMostOverridenMethods(O, Methods))
9595         return true;
9596     return false;
9597   }
9598 
9599 public:
9600   /// Member lookup function that determines whether a given C++
9601   /// method overloads virtual methods in a base class without overriding any,
9602   /// to be used with CXXRecordDecl::lookupInBases().
9603   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9604     RecordDecl *BaseRecord =
9605         Specifier->getType()->castAs<RecordType>()->getDecl();
9606 
9607     DeclarationName Name = Method->getDeclName();
9608     assert(Name.getNameKind() == DeclarationName::Identifier);
9609 
9610     bool foundSameNameMethod = false;
9611     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9612     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9613          Path.Decls = Path.Decls.slice(1)) {
9614       NamedDecl *D = Path.Decls.front();
9615       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9616         MD = MD->getCanonicalDecl();
9617         foundSameNameMethod = true;
9618         // Interested only in hidden virtual methods.
9619         if (!MD->isVirtual())
9620           continue;
9621         // If the method we are checking overrides a method from its base
9622         // don't warn about the other overloaded methods. Clang deviates from
9623         // GCC by only diagnosing overloads of inherited virtual functions that
9624         // do not override any other virtual functions in the base. GCC's
9625         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9626         // function from a base class. These cases may be better served by a
9627         // warning (not specific to virtual functions) on call sites when the
9628         // call would select a different function from the base class, were it
9629         // visible.
9630         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9631         if (!S->IsOverload(Method, MD, false))
9632           return true;
9633         // Collect the overload only if its hidden.
9634         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9635           overloadedMethods.push_back(MD);
9636       }
9637     }
9638 
9639     if (foundSameNameMethod)
9640       OverloadedMethods.append(overloadedMethods.begin(),
9641                                overloadedMethods.end());
9642     return foundSameNameMethod;
9643   }
9644 };
9645 } // end anonymous namespace
9646 
9647 /// Add the most overriden methods from MD to Methods
9648 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9649                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9650   if (MD->size_overridden_methods() == 0)
9651     Methods.insert(MD->getCanonicalDecl());
9652   else
9653     for (const CXXMethodDecl *O : MD->overridden_methods())
9654       AddMostOverridenMethods(O, Methods);
9655 }
9656 
9657 /// Check if a method overloads virtual methods in a base class without
9658 /// overriding any.
9659 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9660                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9661   if (!MD->getDeclName().isIdentifier())
9662     return;
9663 
9664   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9665                      /*bool RecordPaths=*/false,
9666                      /*bool DetectVirtual=*/false);
9667   FindHiddenVirtualMethod FHVM;
9668   FHVM.Method = MD;
9669   FHVM.S = this;
9670 
9671   // Keep the base methods that were overridden or introduced in the subclass
9672   // by 'using' in a set. A base method not in this set is hidden.
9673   CXXRecordDecl *DC = MD->getParent();
9674   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9675   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9676     NamedDecl *ND = *I;
9677     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9678       ND = shad->getTargetDecl();
9679     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9680       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9681   }
9682 
9683   if (DC->lookupInBases(FHVM, Paths))
9684     OverloadedMethods = FHVM.OverloadedMethods;
9685 }
9686 
9687 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9688                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9689   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9690     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9691     PartialDiagnostic PD = PDiag(
9692          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9693     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9694     Diag(overloadedMD->getLocation(), PD);
9695   }
9696 }
9697 
9698 /// Diagnose methods which overload virtual methods in a base class
9699 /// without overriding any.
9700 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9701   if (MD->isInvalidDecl())
9702     return;
9703 
9704   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9705     return;
9706 
9707   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9708   FindHiddenVirtualMethods(MD, OverloadedMethods);
9709   if (!OverloadedMethods.empty()) {
9710     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9711       << MD << (OverloadedMethods.size() > 1);
9712 
9713     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9714   }
9715 }
9716 
9717 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9718   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9719     // No diagnostics if this is a template instantiation.
9720     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9721       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9722            diag::ext_cannot_use_trivial_abi) << &RD;
9723       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9724            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9725     }
9726     RD.dropAttr<TrivialABIAttr>();
9727   };
9728 
9729   // Ill-formed if the copy and move constructors are deleted.
9730   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9731     // If the type is dependent, then assume it might have
9732     // implicit copy or move ctor because we won't know yet at this point.
9733     if (RD.isDependentType())
9734       return true;
9735     if (RD.needsImplicitCopyConstructor() &&
9736         !RD.defaultedCopyConstructorIsDeleted())
9737       return true;
9738     if (RD.needsImplicitMoveConstructor() &&
9739         !RD.defaultedMoveConstructorIsDeleted())
9740       return true;
9741     for (const CXXConstructorDecl *CD : RD.ctors())
9742       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9743         return true;
9744     return false;
9745   };
9746 
9747   if (!HasNonDeletedCopyOrMoveConstructor()) {
9748     PrintDiagAndRemoveAttr(0);
9749     return;
9750   }
9751 
9752   // Ill-formed if the struct has virtual functions.
9753   if (RD.isPolymorphic()) {
9754     PrintDiagAndRemoveAttr(1);
9755     return;
9756   }
9757 
9758   for (const auto &B : RD.bases()) {
9759     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9760     // virtual base.
9761     if (!B.getType()->isDependentType() &&
9762         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9763       PrintDiagAndRemoveAttr(2);
9764       return;
9765     }
9766 
9767     if (B.isVirtual()) {
9768       PrintDiagAndRemoveAttr(3);
9769       return;
9770     }
9771   }
9772 
9773   for (const auto *FD : RD.fields()) {
9774     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9775     // non-trivial for the purpose of calls.
9776     QualType FT = FD->getType();
9777     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9778       PrintDiagAndRemoveAttr(4);
9779       return;
9780     }
9781 
9782     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9783       if (!RT->isDependentType() &&
9784           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9785         PrintDiagAndRemoveAttr(5);
9786         return;
9787       }
9788   }
9789 }
9790 
9791 void Sema::ActOnFinishCXXMemberSpecification(
9792     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9793     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9794   if (!TagDecl)
9795     return;
9796 
9797   AdjustDeclIfTemplate(TagDecl);
9798 
9799   for (const ParsedAttr &AL : AttrList) {
9800     if (AL.getKind() != ParsedAttr::AT_Visibility)
9801       continue;
9802     AL.setInvalid();
9803     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9804   }
9805 
9806   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9807               // strict aliasing violation!
9808               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9809               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9810 
9811   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9812 }
9813 
9814 /// Find the equality comparison functions that should be implicitly declared
9815 /// in a given class definition, per C++2a [class.compare.default]p3.
9816 static void findImplicitlyDeclaredEqualityComparisons(
9817     ASTContext &Ctx, CXXRecordDecl *RD,
9818     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9819   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9820   if (!RD->lookup(EqEq).empty())
9821     // Member operator== explicitly declared: no implicit operator==s.
9822     return;
9823 
9824   // Traverse friends looking for an '==' or a '<=>'.
9825   for (FriendDecl *Friend : RD->friends()) {
9826     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9827     if (!FD) continue;
9828 
9829     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9830       // Friend operator== explicitly declared: no implicit operator==s.
9831       Spaceships.clear();
9832       return;
9833     }
9834 
9835     if (FD->getOverloadedOperator() == OO_Spaceship &&
9836         FD->isExplicitlyDefaulted())
9837       Spaceships.push_back(FD);
9838   }
9839 
9840   // Look for members named 'operator<=>'.
9841   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9842   for (NamedDecl *ND : RD->lookup(Cmp)) {
9843     // Note that we could find a non-function here (either a function template
9844     // or a using-declaration). Neither case results in an implicit
9845     // 'operator=='.
9846     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9847       if (FD->isExplicitlyDefaulted())
9848         Spaceships.push_back(FD);
9849   }
9850 }
9851 
9852 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9853 /// special functions, such as the default constructor, copy
9854 /// constructor, or destructor, to the given C++ class (C++
9855 /// [special]p1).  This routine can only be executed just before the
9856 /// definition of the class is complete.
9857 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9858   // Don't add implicit special members to templated classes.
9859   // FIXME: This means unqualified lookups for 'operator=' within a class
9860   // template don't work properly.
9861   if (!ClassDecl->isDependentType()) {
9862     if (ClassDecl->needsImplicitDefaultConstructor()) {
9863       ++getASTContext().NumImplicitDefaultConstructors;
9864 
9865       if (ClassDecl->hasInheritedConstructor())
9866         DeclareImplicitDefaultConstructor(ClassDecl);
9867     }
9868 
9869     if (ClassDecl->needsImplicitCopyConstructor()) {
9870       ++getASTContext().NumImplicitCopyConstructors;
9871 
9872       // If the properties or semantics of the copy constructor couldn't be
9873       // determined while the class was being declared, force a declaration
9874       // of it now.
9875       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9876           ClassDecl->hasInheritedConstructor())
9877         DeclareImplicitCopyConstructor(ClassDecl);
9878       // For the MS ABI we need to know whether the copy ctor is deleted. A
9879       // prerequisite for deleting the implicit copy ctor is that the class has
9880       // a move ctor or move assignment that is either user-declared or whose
9881       // semantics are inherited from a subobject. FIXME: We should provide a
9882       // more direct way for CodeGen to ask whether the constructor was deleted.
9883       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9884                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9885                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9886                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9887                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9888         DeclareImplicitCopyConstructor(ClassDecl);
9889     }
9890 
9891     if (getLangOpts().CPlusPlus11 &&
9892         ClassDecl->needsImplicitMoveConstructor()) {
9893       ++getASTContext().NumImplicitMoveConstructors;
9894 
9895       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9896           ClassDecl->hasInheritedConstructor())
9897         DeclareImplicitMoveConstructor(ClassDecl);
9898     }
9899 
9900     if (ClassDecl->needsImplicitCopyAssignment()) {
9901       ++getASTContext().NumImplicitCopyAssignmentOperators;
9902 
9903       // If we have a dynamic class, then the copy assignment operator may be
9904       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9905       // it shows up in the right place in the vtable and that we diagnose
9906       // problems with the implicit exception specification.
9907       if (ClassDecl->isDynamicClass() ||
9908           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9909           ClassDecl->hasInheritedAssignment())
9910         DeclareImplicitCopyAssignment(ClassDecl);
9911     }
9912 
9913     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9914       ++getASTContext().NumImplicitMoveAssignmentOperators;
9915 
9916       // Likewise for the move assignment operator.
9917       if (ClassDecl->isDynamicClass() ||
9918           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9919           ClassDecl->hasInheritedAssignment())
9920         DeclareImplicitMoveAssignment(ClassDecl);
9921     }
9922 
9923     if (ClassDecl->needsImplicitDestructor()) {
9924       ++getASTContext().NumImplicitDestructors;
9925 
9926       // If we have a dynamic class, then the destructor may be virtual, so we
9927       // have to declare the destructor immediately. This ensures that, e.g., it
9928       // shows up in the right place in the vtable and that we diagnose problems
9929       // with the implicit exception specification.
9930       if (ClassDecl->isDynamicClass() ||
9931           ClassDecl->needsOverloadResolutionForDestructor())
9932         DeclareImplicitDestructor(ClassDecl);
9933     }
9934   }
9935 
9936   // C++2a [class.compare.default]p3:
9937   //   If the member-specification does not explicitly declare any member or
9938   //   friend named operator==, an == operator function is declared implicitly
9939   //   for each defaulted three-way comparison operator function defined in
9940   //   the member-specification
9941   // FIXME: Consider doing this lazily.
9942   // We do this during the initial parse for a class template, not during
9943   // instantiation, so that we can handle unqualified lookups for 'operator=='
9944   // when parsing the template.
9945   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9946     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9947     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9948                                               DefaultedSpaceships);
9949     for (auto *FD : DefaultedSpaceships)
9950       DeclareImplicitEqualityComparison(ClassDecl, FD);
9951   }
9952 }
9953 
9954 unsigned
9955 Sema::ActOnReenterTemplateScope(Decl *D,
9956                                 llvm::function_ref<Scope *()> EnterScope) {
9957   if (!D)
9958     return 0;
9959   AdjustDeclIfTemplate(D);
9960 
9961   // In order to get name lookup right, reenter template scopes in order from
9962   // outermost to innermost.
9963   SmallVector<TemplateParameterList *, 4> ParameterLists;
9964   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9965 
9966   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9967     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9968       ParameterLists.push_back(DD->getTemplateParameterList(i));
9969 
9970     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9971       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9972         ParameterLists.push_back(FTD->getTemplateParameters());
9973     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
9974       LookupDC = VD->getDeclContext();
9975 
9976       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
9977         ParameterLists.push_back(VTD->getTemplateParameters());
9978       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
9979         ParameterLists.push_back(PSD->getTemplateParameters());
9980     }
9981   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9982     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9983       ParameterLists.push_back(TD->getTemplateParameterList(i));
9984 
9985     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9986       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9987         ParameterLists.push_back(CTD->getTemplateParameters());
9988       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9989         ParameterLists.push_back(PSD->getTemplateParameters());
9990     }
9991   }
9992   // FIXME: Alias declarations and concepts.
9993 
9994   unsigned Count = 0;
9995   Scope *InnermostTemplateScope = nullptr;
9996   for (TemplateParameterList *Params : ParameterLists) {
9997     // Ignore explicit specializations; they don't contribute to the template
9998     // depth.
9999     if (Params->size() == 0)
10000       continue;
10001 
10002     InnermostTemplateScope = EnterScope();
10003     for (NamedDecl *Param : *Params) {
10004       if (Param->getDeclName()) {
10005         InnermostTemplateScope->AddDecl(Param);
10006         IdResolver.AddDecl(Param);
10007       }
10008     }
10009     ++Count;
10010   }
10011 
10012   // Associate the new template scopes with the corresponding entities.
10013   if (InnermostTemplateScope) {
10014     assert(LookupDC && "no enclosing DeclContext for template lookup");
10015     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10016   }
10017 
10018   return Count;
10019 }
10020 
10021 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10022   if (!RecordD) return;
10023   AdjustDeclIfTemplate(RecordD);
10024   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10025   PushDeclContext(S, Record);
10026 }
10027 
10028 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10029   if (!RecordD) return;
10030   PopDeclContext();
10031 }
10032 
10033 /// This is used to implement the constant expression evaluation part of the
10034 /// attribute enable_if extension. There is nothing in standard C++ which would
10035 /// require reentering parameters.
10036 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10037   if (!Param)
10038     return;
10039 
10040   S->AddDecl(Param);
10041   if (Param->getDeclName())
10042     IdResolver.AddDecl(Param);
10043 }
10044 
10045 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10046 /// parsing a top-level (non-nested) C++ class, and we are now
10047 /// parsing those parts of the given Method declaration that could
10048 /// not be parsed earlier (C++ [class.mem]p2), such as default
10049 /// arguments. This action should enter the scope of the given
10050 /// Method declaration as if we had just parsed the qualified method
10051 /// name. However, it should not bring the parameters into scope;
10052 /// that will be performed by ActOnDelayedCXXMethodParameter.
10053 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10054 }
10055 
10056 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10057 /// C++ method declaration. We're (re-)introducing the given
10058 /// function parameter into scope for use in parsing later parts of
10059 /// the method declaration. For example, we could see an
10060 /// ActOnParamDefaultArgument event for this parameter.
10061 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10062   if (!ParamD)
10063     return;
10064 
10065   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10066 
10067   S->AddDecl(Param);
10068   if (Param->getDeclName())
10069     IdResolver.AddDecl(Param);
10070 }
10071 
10072 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10073 /// processing the delayed method declaration for Method. The method
10074 /// declaration is now considered finished. There may be a separate
10075 /// ActOnStartOfFunctionDef action later (not necessarily
10076 /// immediately!) for this method, if it was also defined inside the
10077 /// class body.
10078 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10079   if (!MethodD)
10080     return;
10081 
10082   AdjustDeclIfTemplate(MethodD);
10083 
10084   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10085 
10086   // Now that we have our default arguments, check the constructor
10087   // again. It could produce additional diagnostics or affect whether
10088   // the class has implicitly-declared destructors, among other
10089   // things.
10090   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10091     CheckConstructor(Constructor);
10092 
10093   // Check the default arguments, which we may have added.
10094   if (!Method->isInvalidDecl())
10095     CheckCXXDefaultArguments(Method);
10096 }
10097 
10098 // Emit the given diagnostic for each non-address-space qualifier.
10099 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10100 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10101   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10102   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10103     bool DiagOccured = false;
10104     FTI.MethodQualifiers->forEachQualifier(
10105         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10106                                    SourceLocation SL) {
10107           // This diagnostic should be emitted on any qualifier except an addr
10108           // space qualifier. However, forEachQualifier currently doesn't visit
10109           // addr space qualifiers, so there's no way to write this condition
10110           // right now; we just diagnose on everything.
10111           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10112           DiagOccured = true;
10113         });
10114     if (DiagOccured)
10115       D.setInvalidType();
10116   }
10117 }
10118 
10119 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10120 /// the well-formedness of the constructor declarator @p D with type @p
10121 /// R. If there are any errors in the declarator, this routine will
10122 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10123 /// will be updated to reflect a well-formed type for the constructor and
10124 /// returned.
10125 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10126                                           StorageClass &SC) {
10127   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10128 
10129   // C++ [class.ctor]p3:
10130   //   A constructor shall not be virtual (10.3) or static (9.4). A
10131   //   constructor can be invoked for a const, volatile or const
10132   //   volatile object. A constructor shall not be declared const,
10133   //   volatile, or const volatile (9.3.2).
10134   if (isVirtual) {
10135     if (!D.isInvalidType())
10136       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10137         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10138         << SourceRange(D.getIdentifierLoc());
10139     D.setInvalidType();
10140   }
10141   if (SC == SC_Static) {
10142     if (!D.isInvalidType())
10143       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10144         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10145         << SourceRange(D.getIdentifierLoc());
10146     D.setInvalidType();
10147     SC = SC_None;
10148   }
10149 
10150   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10151     diagnoseIgnoredQualifiers(
10152         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10153         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10154         D.getDeclSpec().getRestrictSpecLoc(),
10155         D.getDeclSpec().getAtomicSpecLoc());
10156     D.setInvalidType();
10157   }
10158 
10159   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10160 
10161   // C++0x [class.ctor]p4:
10162   //   A constructor shall not be declared with a ref-qualifier.
10163   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10164   if (FTI.hasRefQualifier()) {
10165     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10166       << FTI.RefQualifierIsLValueRef
10167       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10168     D.setInvalidType();
10169   }
10170 
10171   // Rebuild the function type "R" without any type qualifiers (in
10172   // case any of the errors above fired) and with "void" as the
10173   // return type, since constructors don't have return types.
10174   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10175   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10176     return R;
10177 
10178   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10179   EPI.TypeQuals = Qualifiers();
10180   EPI.RefQualifier = RQ_None;
10181 
10182   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10183 }
10184 
10185 /// CheckConstructor - Checks a fully-formed constructor for
10186 /// well-formedness, issuing any diagnostics required. Returns true if
10187 /// the constructor declarator is invalid.
10188 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10189   CXXRecordDecl *ClassDecl
10190     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10191   if (!ClassDecl)
10192     return Constructor->setInvalidDecl();
10193 
10194   // C++ [class.copy]p3:
10195   //   A declaration of a constructor for a class X is ill-formed if
10196   //   its first parameter is of type (optionally cv-qualified) X and
10197   //   either there are no other parameters or else all other
10198   //   parameters have default arguments.
10199   if (!Constructor->isInvalidDecl() &&
10200       Constructor->hasOneParamOrDefaultArgs() &&
10201       Constructor->getTemplateSpecializationKind() !=
10202           TSK_ImplicitInstantiation) {
10203     QualType ParamType = Constructor->getParamDecl(0)->getType();
10204     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10205     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10206       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10207       const char *ConstRef
10208         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10209                                                         : " const &";
10210       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10211         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10212 
10213       // FIXME: Rather that making the constructor invalid, we should endeavor
10214       // to fix the type.
10215       Constructor->setInvalidDecl();
10216     }
10217   }
10218 }
10219 
10220 /// CheckDestructor - Checks a fully-formed destructor definition for
10221 /// well-formedness, issuing any diagnostics required.  Returns true
10222 /// on error.
10223 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10224   CXXRecordDecl *RD = Destructor->getParent();
10225 
10226   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10227     SourceLocation Loc;
10228 
10229     if (!Destructor->isImplicit())
10230       Loc = Destructor->getLocation();
10231     else
10232       Loc = RD->getLocation();
10233 
10234     // If we have a virtual destructor, look up the deallocation function
10235     if (FunctionDecl *OperatorDelete =
10236             FindDeallocationFunctionForDestructor(Loc, RD)) {
10237       Expr *ThisArg = nullptr;
10238 
10239       // If the notional 'delete this' expression requires a non-trivial
10240       // conversion from 'this' to the type of a destroying operator delete's
10241       // first parameter, perform that conversion now.
10242       if (OperatorDelete->isDestroyingOperatorDelete()) {
10243         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10244         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10245           // C++ [class.dtor]p13:
10246           //   ... as if for the expression 'delete this' appearing in a
10247           //   non-virtual destructor of the destructor's class.
10248           ContextRAII SwitchContext(*this, Destructor);
10249           ExprResult This =
10250               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10251           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10252           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10253           if (This.isInvalid()) {
10254             // FIXME: Register this as a context note so that it comes out
10255             // in the right order.
10256             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10257             return true;
10258           }
10259           ThisArg = This.get();
10260         }
10261       }
10262 
10263       DiagnoseUseOfDecl(OperatorDelete, Loc);
10264       MarkFunctionReferenced(Loc, OperatorDelete);
10265       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10266     }
10267   }
10268 
10269   return false;
10270 }
10271 
10272 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10273 /// the well-formednes of the destructor declarator @p D with type @p
10274 /// R. If there are any errors in the declarator, this routine will
10275 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10276 /// will be updated to reflect a well-formed type for the destructor and
10277 /// returned.
10278 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10279                                          StorageClass& SC) {
10280   // C++ [class.dtor]p1:
10281   //   [...] A typedef-name that names a class is a class-name
10282   //   (7.1.3); however, a typedef-name that names a class shall not
10283   //   be used as the identifier in the declarator for a destructor
10284   //   declaration.
10285   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10286   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10287     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10288       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10289   else if (const TemplateSpecializationType *TST =
10290              DeclaratorType->getAs<TemplateSpecializationType>())
10291     if (TST->isTypeAlias())
10292       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10293         << DeclaratorType << 1;
10294 
10295   // C++ [class.dtor]p2:
10296   //   A destructor is used to destroy objects of its class type. A
10297   //   destructor takes no parameters, and no return type can be
10298   //   specified for it (not even void). The address of a destructor
10299   //   shall not be taken. A destructor shall not be static. A
10300   //   destructor can be invoked for a const, volatile or const
10301   //   volatile object. A destructor shall not be declared const,
10302   //   volatile or const volatile (9.3.2).
10303   if (SC == SC_Static) {
10304     if (!D.isInvalidType())
10305       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10306         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10307         << SourceRange(D.getIdentifierLoc())
10308         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10309 
10310     SC = SC_None;
10311   }
10312   if (!D.isInvalidType()) {
10313     // Destructors don't have return types, but the parser will
10314     // happily parse something like:
10315     //
10316     //   class X {
10317     //     float ~X();
10318     //   };
10319     //
10320     // The return type will be eliminated later.
10321     if (D.getDeclSpec().hasTypeSpecifier())
10322       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10323         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10324         << SourceRange(D.getIdentifierLoc());
10325     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10326       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10327                                 SourceLocation(),
10328                                 D.getDeclSpec().getConstSpecLoc(),
10329                                 D.getDeclSpec().getVolatileSpecLoc(),
10330                                 D.getDeclSpec().getRestrictSpecLoc(),
10331                                 D.getDeclSpec().getAtomicSpecLoc());
10332       D.setInvalidType();
10333     }
10334   }
10335 
10336   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10337 
10338   // C++0x [class.dtor]p2:
10339   //   A destructor shall not be declared with a ref-qualifier.
10340   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10341   if (FTI.hasRefQualifier()) {
10342     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10343       << FTI.RefQualifierIsLValueRef
10344       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10345     D.setInvalidType();
10346   }
10347 
10348   // Make sure we don't have any parameters.
10349   if (FTIHasNonVoidParameters(FTI)) {
10350     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10351 
10352     // Delete the parameters.
10353     FTI.freeParams();
10354     D.setInvalidType();
10355   }
10356 
10357   // Make sure the destructor isn't variadic.
10358   if (FTI.isVariadic) {
10359     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10360     D.setInvalidType();
10361   }
10362 
10363   // Rebuild the function type "R" without any type qualifiers or
10364   // parameters (in case any of the errors above fired) and with
10365   // "void" as the return type, since destructors don't have return
10366   // types.
10367   if (!D.isInvalidType())
10368     return R;
10369 
10370   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10371   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10372   EPI.Variadic = false;
10373   EPI.TypeQuals = Qualifiers();
10374   EPI.RefQualifier = RQ_None;
10375   return Context.getFunctionType(Context.VoidTy, None, EPI);
10376 }
10377 
10378 static void extendLeft(SourceRange &R, SourceRange Before) {
10379   if (Before.isInvalid())
10380     return;
10381   R.setBegin(Before.getBegin());
10382   if (R.getEnd().isInvalid())
10383     R.setEnd(Before.getEnd());
10384 }
10385 
10386 static void extendRight(SourceRange &R, SourceRange After) {
10387   if (After.isInvalid())
10388     return;
10389   if (R.getBegin().isInvalid())
10390     R.setBegin(After.getBegin());
10391   R.setEnd(After.getEnd());
10392 }
10393 
10394 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10395 /// well-formednes of the conversion function declarator @p D with
10396 /// type @p R. If there are any errors in the declarator, this routine
10397 /// will emit diagnostics and return true. Otherwise, it will return
10398 /// false. Either way, the type @p R will be updated to reflect a
10399 /// well-formed type for the conversion operator.
10400 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10401                                      StorageClass& SC) {
10402   // C++ [class.conv.fct]p1:
10403   //   Neither parameter types nor return type can be specified. The
10404   //   type of a conversion function (8.3.5) is "function taking no
10405   //   parameter returning conversion-type-id."
10406   if (SC == SC_Static) {
10407     if (!D.isInvalidType())
10408       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10409         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10410         << D.getName().getSourceRange();
10411     D.setInvalidType();
10412     SC = SC_None;
10413   }
10414 
10415   TypeSourceInfo *ConvTSI = nullptr;
10416   QualType ConvType =
10417       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10418 
10419   const DeclSpec &DS = D.getDeclSpec();
10420   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10421     // Conversion functions don't have return types, but the parser will
10422     // happily parse something like:
10423     //
10424     //   class X {
10425     //     float operator bool();
10426     //   };
10427     //
10428     // The return type will be changed later anyway.
10429     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10430       << SourceRange(DS.getTypeSpecTypeLoc())
10431       << SourceRange(D.getIdentifierLoc());
10432     D.setInvalidType();
10433   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10434     // It's also plausible that the user writes type qualifiers in the wrong
10435     // place, such as:
10436     //   struct S { const operator int(); };
10437     // FIXME: we could provide a fixit to move the qualifiers onto the
10438     // conversion type.
10439     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10440         << SourceRange(D.getIdentifierLoc()) << 0;
10441     D.setInvalidType();
10442   }
10443 
10444   const auto *Proto = R->castAs<FunctionProtoType>();
10445 
10446   // Make sure we don't have any parameters.
10447   if (Proto->getNumParams() > 0) {
10448     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10449 
10450     // Delete the parameters.
10451     D.getFunctionTypeInfo().freeParams();
10452     D.setInvalidType();
10453   } else if (Proto->isVariadic()) {
10454     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10455     D.setInvalidType();
10456   }
10457 
10458   // Diagnose "&operator bool()" and other such nonsense.  This
10459   // is actually a gcc extension which we don't support.
10460   if (Proto->getReturnType() != ConvType) {
10461     bool NeedsTypedef = false;
10462     SourceRange Before, After;
10463 
10464     // Walk the chunks and extract information on them for our diagnostic.
10465     bool PastFunctionChunk = false;
10466     for (auto &Chunk : D.type_objects()) {
10467       switch (Chunk.Kind) {
10468       case DeclaratorChunk::Function:
10469         if (!PastFunctionChunk) {
10470           if (Chunk.Fun.HasTrailingReturnType) {
10471             TypeSourceInfo *TRT = nullptr;
10472             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10473             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10474           }
10475           PastFunctionChunk = true;
10476           break;
10477         }
10478         LLVM_FALLTHROUGH;
10479       case DeclaratorChunk::Array:
10480         NeedsTypedef = true;
10481         extendRight(After, Chunk.getSourceRange());
10482         break;
10483 
10484       case DeclaratorChunk::Pointer:
10485       case DeclaratorChunk::BlockPointer:
10486       case DeclaratorChunk::Reference:
10487       case DeclaratorChunk::MemberPointer:
10488       case DeclaratorChunk::Pipe:
10489         extendLeft(Before, Chunk.getSourceRange());
10490         break;
10491 
10492       case DeclaratorChunk::Paren:
10493         extendLeft(Before, Chunk.Loc);
10494         extendRight(After, Chunk.EndLoc);
10495         break;
10496       }
10497     }
10498 
10499     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10500                          After.isValid()  ? After.getBegin() :
10501                                             D.getIdentifierLoc();
10502     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10503     DB << Before << After;
10504 
10505     if (!NeedsTypedef) {
10506       DB << /*don't need a typedef*/0;
10507 
10508       // If we can provide a correct fix-it hint, do so.
10509       if (After.isInvalid() && ConvTSI) {
10510         SourceLocation InsertLoc =
10511             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10512         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10513            << FixItHint::CreateInsertionFromRange(
10514                   InsertLoc, CharSourceRange::getTokenRange(Before))
10515            << FixItHint::CreateRemoval(Before);
10516       }
10517     } else if (!Proto->getReturnType()->isDependentType()) {
10518       DB << /*typedef*/1 << Proto->getReturnType();
10519     } else if (getLangOpts().CPlusPlus11) {
10520       DB << /*alias template*/2 << Proto->getReturnType();
10521     } else {
10522       DB << /*might not be fixable*/3;
10523     }
10524 
10525     // Recover by incorporating the other type chunks into the result type.
10526     // Note, this does *not* change the name of the function. This is compatible
10527     // with the GCC extension:
10528     //   struct S { &operator int(); } s;
10529     //   int &r = s.operator int(); // ok in GCC
10530     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10531     ConvType = Proto->getReturnType();
10532   }
10533 
10534   // C++ [class.conv.fct]p4:
10535   //   The conversion-type-id shall not represent a function type nor
10536   //   an array type.
10537   if (ConvType->isArrayType()) {
10538     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10539     ConvType = Context.getPointerType(ConvType);
10540     D.setInvalidType();
10541   } else if (ConvType->isFunctionType()) {
10542     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10543     ConvType = Context.getPointerType(ConvType);
10544     D.setInvalidType();
10545   }
10546 
10547   // Rebuild the function type "R" without any parameters (in case any
10548   // of the errors above fired) and with the conversion type as the
10549   // return type.
10550   if (D.isInvalidType())
10551     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10552 
10553   // C++0x explicit conversion operators.
10554   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10555     Diag(DS.getExplicitSpecLoc(),
10556          getLangOpts().CPlusPlus11
10557              ? diag::warn_cxx98_compat_explicit_conversion_functions
10558              : diag::ext_explicit_conversion_functions)
10559         << SourceRange(DS.getExplicitSpecRange());
10560 }
10561 
10562 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10563 /// the declaration of the given C++ conversion function. This routine
10564 /// is responsible for recording the conversion function in the C++
10565 /// class, if possible.
10566 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10567   assert(Conversion && "Expected to receive a conversion function declaration");
10568 
10569   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10570 
10571   // Make sure we aren't redeclaring the conversion function.
10572   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10573   // C++ [class.conv.fct]p1:
10574   //   [...] A conversion function is never used to convert a
10575   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10576   //   same object type (or a reference to it), to a (possibly
10577   //   cv-qualified) base class of that type (or a reference to it),
10578   //   or to (possibly cv-qualified) void.
10579   QualType ClassType
10580     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10581   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10582     ConvType = ConvTypeRef->getPointeeType();
10583   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10584       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10585     /* Suppress diagnostics for instantiations. */;
10586   else if (Conversion->size_overridden_methods() != 0)
10587     /* Suppress diagnostics for overriding virtual function in a base class. */;
10588   else if (ConvType->isRecordType()) {
10589     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10590     if (ConvType == ClassType)
10591       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10592         << ClassType;
10593     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10594       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10595         <<  ClassType << ConvType;
10596   } else if (ConvType->isVoidType()) {
10597     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10598       << ClassType << ConvType;
10599   }
10600 
10601   if (FunctionTemplateDecl *ConversionTemplate
10602                                 = Conversion->getDescribedFunctionTemplate())
10603     return ConversionTemplate;
10604 
10605   return Conversion;
10606 }
10607 
10608 namespace {
10609 /// Utility class to accumulate and print a diagnostic listing the invalid
10610 /// specifier(s) on a declaration.
10611 struct BadSpecifierDiagnoser {
10612   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10613       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10614   ~BadSpecifierDiagnoser() {
10615     Diagnostic << Specifiers;
10616   }
10617 
10618   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10619     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10620   }
10621   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10622     return check(SpecLoc,
10623                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10624   }
10625   void check(SourceLocation SpecLoc, const char *Spec) {
10626     if (SpecLoc.isInvalid()) return;
10627     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10628     if (!Specifiers.empty()) Specifiers += " ";
10629     Specifiers += Spec;
10630   }
10631 
10632   Sema &S;
10633   Sema::SemaDiagnosticBuilder Diagnostic;
10634   std::string Specifiers;
10635 };
10636 }
10637 
10638 /// Check the validity of a declarator that we parsed for a deduction-guide.
10639 /// These aren't actually declarators in the grammar, so we need to check that
10640 /// the user didn't specify any pieces that are not part of the deduction-guide
10641 /// grammar.
10642 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10643                                          StorageClass &SC) {
10644   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10645   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10646   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10647 
10648   // C++ [temp.deduct.guide]p3:
10649   //   A deduction-gide shall be declared in the same scope as the
10650   //   corresponding class template.
10651   if (!CurContext->getRedeclContext()->Equals(
10652           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10653     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10654       << GuidedTemplateDecl;
10655     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10656   }
10657 
10658   auto &DS = D.getMutableDeclSpec();
10659   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10660   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10661       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10662       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10663     BadSpecifierDiagnoser Diagnoser(
10664         *this, D.getIdentifierLoc(),
10665         diag::err_deduction_guide_invalid_specifier);
10666 
10667     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10668     DS.ClearStorageClassSpecs();
10669     SC = SC_None;
10670 
10671     // 'explicit' is permitted.
10672     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10673     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10674     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10675     DS.ClearConstexprSpec();
10676 
10677     Diagnoser.check(DS.getConstSpecLoc(), "const");
10678     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10679     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10680     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10681     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10682     DS.ClearTypeQualifiers();
10683 
10684     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10685     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10686     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10687     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10688     DS.ClearTypeSpecType();
10689   }
10690 
10691   if (D.isInvalidType())
10692     return;
10693 
10694   // Check the declarator is simple enough.
10695   bool FoundFunction = false;
10696   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10697     if (Chunk.Kind == DeclaratorChunk::Paren)
10698       continue;
10699     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10700       Diag(D.getDeclSpec().getBeginLoc(),
10701            diag::err_deduction_guide_with_complex_decl)
10702           << D.getSourceRange();
10703       break;
10704     }
10705     if (!Chunk.Fun.hasTrailingReturnType()) {
10706       Diag(D.getName().getBeginLoc(),
10707            diag::err_deduction_guide_no_trailing_return_type);
10708       break;
10709     }
10710 
10711     // Check that the return type is written as a specialization of
10712     // the template specified as the deduction-guide's name.
10713     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10714     TypeSourceInfo *TSI = nullptr;
10715     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10716     assert(TSI && "deduction guide has valid type but invalid return type?");
10717     bool AcceptableReturnType = false;
10718     bool MightInstantiateToSpecialization = false;
10719     if (auto RetTST =
10720             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10721       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10722       bool TemplateMatches =
10723           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10724       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10725         AcceptableReturnType = true;
10726       else {
10727         // This could still instantiate to the right type, unless we know it
10728         // names the wrong class template.
10729         auto *TD = SpecifiedName.getAsTemplateDecl();
10730         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10731                                              !TemplateMatches);
10732       }
10733     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10734       MightInstantiateToSpecialization = true;
10735     }
10736 
10737     if (!AcceptableReturnType) {
10738       Diag(TSI->getTypeLoc().getBeginLoc(),
10739            diag::err_deduction_guide_bad_trailing_return_type)
10740           << GuidedTemplate << TSI->getType()
10741           << MightInstantiateToSpecialization
10742           << TSI->getTypeLoc().getSourceRange();
10743     }
10744 
10745     // Keep going to check that we don't have any inner declarator pieces (we
10746     // could still have a function returning a pointer to a function).
10747     FoundFunction = true;
10748   }
10749 
10750   if (D.isFunctionDefinition())
10751     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10752 }
10753 
10754 //===----------------------------------------------------------------------===//
10755 // Namespace Handling
10756 //===----------------------------------------------------------------------===//
10757 
10758 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10759 /// reopened.
10760 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10761                                             SourceLocation Loc,
10762                                             IdentifierInfo *II, bool *IsInline,
10763                                             NamespaceDecl *PrevNS) {
10764   assert(*IsInline != PrevNS->isInline());
10765 
10766   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10767   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10768   // inline namespaces, with the intention of bringing names into namespace std.
10769   //
10770   // We support this just well enough to get that case working; this is not
10771   // sufficient to support reopening namespaces as inline in general.
10772   if (*IsInline && II && II->getName().startswith("__atomic") &&
10773       S.getSourceManager().isInSystemHeader(Loc)) {
10774     // Mark all prior declarations of the namespace as inline.
10775     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10776          NS = NS->getPreviousDecl())
10777       NS->setInline(*IsInline);
10778     // Patch up the lookup table for the containing namespace. This isn't really
10779     // correct, but it's good enough for this particular case.
10780     for (auto *I : PrevNS->decls())
10781       if (auto *ND = dyn_cast<NamedDecl>(I))
10782         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10783     return;
10784   }
10785 
10786   if (PrevNS->isInline())
10787     // The user probably just forgot the 'inline', so suggest that it
10788     // be added back.
10789     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10790       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10791   else
10792     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10793 
10794   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10795   *IsInline = PrevNS->isInline();
10796 }
10797 
10798 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10799 /// definition.
10800 Decl *Sema::ActOnStartNamespaceDef(
10801     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10802     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10803     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10804   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10805   // For anonymous namespace, take the location of the left brace.
10806   SourceLocation Loc = II ? IdentLoc : LBrace;
10807   bool IsInline = InlineLoc.isValid();
10808   bool IsInvalid = false;
10809   bool IsStd = false;
10810   bool AddToKnown = false;
10811   Scope *DeclRegionScope = NamespcScope->getParent();
10812 
10813   NamespaceDecl *PrevNS = nullptr;
10814   if (II) {
10815     // C++ [namespace.def]p2:
10816     //   The identifier in an original-namespace-definition shall not
10817     //   have been previously defined in the declarative region in
10818     //   which the original-namespace-definition appears. The
10819     //   identifier in an original-namespace-definition is the name of
10820     //   the namespace. Subsequently in that declarative region, it is
10821     //   treated as an original-namespace-name.
10822     //
10823     // Since namespace names are unique in their scope, and we don't
10824     // look through using directives, just look for any ordinary names
10825     // as if by qualified name lookup.
10826     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10827                    ForExternalRedeclaration);
10828     LookupQualifiedName(R, CurContext->getRedeclContext());
10829     NamedDecl *PrevDecl =
10830         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10831     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10832 
10833     if (PrevNS) {
10834       // This is an extended namespace definition.
10835       if (IsInline != PrevNS->isInline())
10836         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10837                                         &IsInline, PrevNS);
10838     } else if (PrevDecl) {
10839       // This is an invalid name redefinition.
10840       Diag(Loc, diag::err_redefinition_different_kind)
10841         << II;
10842       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10843       IsInvalid = true;
10844       // Continue on to push Namespc as current DeclContext and return it.
10845     } else if (II->isStr("std") &&
10846                CurContext->getRedeclContext()->isTranslationUnit()) {
10847       // This is the first "real" definition of the namespace "std", so update
10848       // our cache of the "std" namespace to point at this definition.
10849       PrevNS = getStdNamespace();
10850       IsStd = true;
10851       AddToKnown = !IsInline;
10852     } else {
10853       // We've seen this namespace for the first time.
10854       AddToKnown = !IsInline;
10855     }
10856   } else {
10857     // Anonymous namespaces.
10858 
10859     // Determine whether the parent already has an anonymous namespace.
10860     DeclContext *Parent = CurContext->getRedeclContext();
10861     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10862       PrevNS = TU->getAnonymousNamespace();
10863     } else {
10864       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10865       PrevNS = ND->getAnonymousNamespace();
10866     }
10867 
10868     if (PrevNS && IsInline != PrevNS->isInline())
10869       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10870                                       &IsInline, PrevNS);
10871   }
10872 
10873   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10874                                                  StartLoc, Loc, II, PrevNS);
10875   if (IsInvalid)
10876     Namespc->setInvalidDecl();
10877 
10878   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10879   AddPragmaAttributes(DeclRegionScope, Namespc);
10880 
10881   // FIXME: Should we be merging attributes?
10882   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10883     PushNamespaceVisibilityAttr(Attr, Loc);
10884 
10885   if (IsStd)
10886     StdNamespace = Namespc;
10887   if (AddToKnown)
10888     KnownNamespaces[Namespc] = false;
10889 
10890   if (II) {
10891     PushOnScopeChains(Namespc, DeclRegionScope);
10892   } else {
10893     // Link the anonymous namespace into its parent.
10894     DeclContext *Parent = CurContext->getRedeclContext();
10895     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10896       TU->setAnonymousNamespace(Namespc);
10897     } else {
10898       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10899     }
10900 
10901     CurContext->addDecl(Namespc);
10902 
10903     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10904     //   behaves as if it were replaced by
10905     //     namespace unique { /* empty body */ }
10906     //     using namespace unique;
10907     //     namespace unique { namespace-body }
10908     //   where all occurrences of 'unique' in a translation unit are
10909     //   replaced by the same identifier and this identifier differs
10910     //   from all other identifiers in the entire program.
10911 
10912     // We just create the namespace with an empty name and then add an
10913     // implicit using declaration, just like the standard suggests.
10914     //
10915     // CodeGen enforces the "universally unique" aspect by giving all
10916     // declarations semantically contained within an anonymous
10917     // namespace internal linkage.
10918 
10919     if (!PrevNS) {
10920       UD = UsingDirectiveDecl::Create(Context, Parent,
10921                                       /* 'using' */ LBrace,
10922                                       /* 'namespace' */ SourceLocation(),
10923                                       /* qualifier */ NestedNameSpecifierLoc(),
10924                                       /* identifier */ SourceLocation(),
10925                                       Namespc,
10926                                       /* Ancestor */ Parent);
10927       UD->setImplicit();
10928       Parent->addDecl(UD);
10929     }
10930   }
10931 
10932   ActOnDocumentableDecl(Namespc);
10933 
10934   // Although we could have an invalid decl (i.e. the namespace name is a
10935   // redefinition), push it as current DeclContext and try to continue parsing.
10936   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10937   // for the namespace has the declarations that showed up in that particular
10938   // namespace definition.
10939   PushDeclContext(NamespcScope, Namespc);
10940   return Namespc;
10941 }
10942 
10943 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10944 /// is a namespace alias, returns the namespace it points to.
10945 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10946   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10947     return AD->getNamespace();
10948   return dyn_cast_or_null<NamespaceDecl>(D);
10949 }
10950 
10951 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10952 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10953 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10954   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10955   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10956   Namespc->setRBraceLoc(RBrace);
10957   PopDeclContext();
10958   if (Namespc->hasAttr<VisibilityAttr>())
10959     PopPragmaVisibility(true, RBrace);
10960   // If this namespace contains an export-declaration, export it now.
10961   if (DeferredExportedNamespaces.erase(Namespc))
10962     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10963 }
10964 
10965 CXXRecordDecl *Sema::getStdBadAlloc() const {
10966   return cast_or_null<CXXRecordDecl>(
10967                                   StdBadAlloc.get(Context.getExternalSource()));
10968 }
10969 
10970 EnumDecl *Sema::getStdAlignValT() const {
10971   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10972 }
10973 
10974 NamespaceDecl *Sema::getStdNamespace() const {
10975   return cast_or_null<NamespaceDecl>(
10976                                  StdNamespace.get(Context.getExternalSource()));
10977 }
10978 
10979 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10980   if (!StdExperimentalNamespaceCache) {
10981     if (auto Std = getStdNamespace()) {
10982       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10983                           SourceLocation(), LookupNamespaceName);
10984       if (!LookupQualifiedName(Result, Std) ||
10985           !(StdExperimentalNamespaceCache =
10986                 Result.getAsSingle<NamespaceDecl>()))
10987         Result.suppressDiagnostics();
10988     }
10989   }
10990   return StdExperimentalNamespaceCache;
10991 }
10992 
10993 namespace {
10994 
10995 enum UnsupportedSTLSelect {
10996   USS_InvalidMember,
10997   USS_MissingMember,
10998   USS_NonTrivial,
10999   USS_Other
11000 };
11001 
11002 struct InvalidSTLDiagnoser {
11003   Sema &S;
11004   SourceLocation Loc;
11005   QualType TyForDiags;
11006 
11007   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11008                       const VarDecl *VD = nullptr) {
11009     {
11010       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11011                << TyForDiags << ((int)Sel);
11012       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11013         assert(!Name.empty());
11014         D << Name;
11015       }
11016     }
11017     if (Sel == USS_InvalidMember) {
11018       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11019           << VD << VD->getSourceRange();
11020     }
11021     return QualType();
11022   }
11023 };
11024 } // namespace
11025 
11026 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11027                                            SourceLocation Loc,
11028                                            ComparisonCategoryUsage Usage) {
11029   assert(getLangOpts().CPlusPlus &&
11030          "Looking for comparison category type outside of C++.");
11031 
11032   // Use an elaborated type for diagnostics which has a name containing the
11033   // prepended 'std' namespace but not any inline namespace names.
11034   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11035     auto *NNS =
11036         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11037     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11038   };
11039 
11040   // Check if we've already successfully checked the comparison category type
11041   // before. If so, skip checking it again.
11042   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11043   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11044     // The only thing we need to check is that the type has a reachable
11045     // definition in the current context.
11046     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11047       return QualType();
11048 
11049     return Info->getType();
11050   }
11051 
11052   // If lookup failed
11053   if (!Info) {
11054     std::string NameForDiags = "std::";
11055     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11056     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11057         << NameForDiags << (int)Usage;
11058     return QualType();
11059   }
11060 
11061   assert(Info->Kind == Kind);
11062   assert(Info->Record);
11063 
11064   // Update the Record decl in case we encountered a forward declaration on our
11065   // first pass. FIXME: This is a bit of a hack.
11066   if (Info->Record->hasDefinition())
11067     Info->Record = Info->Record->getDefinition();
11068 
11069   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11070     return QualType();
11071 
11072   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11073 
11074   if (!Info->Record->isTriviallyCopyable())
11075     return UnsupportedSTLError(USS_NonTrivial);
11076 
11077   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11078     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11079     // Tolerate empty base classes.
11080     if (Base->isEmpty())
11081       continue;
11082     // Reject STL implementations which have at least one non-empty base.
11083     return UnsupportedSTLError();
11084   }
11085 
11086   // Check that the STL has implemented the types using a single integer field.
11087   // This expectation allows better codegen for builtin operators. We require:
11088   //   (1) The class has exactly one field.
11089   //   (2) The field is an integral or enumeration type.
11090   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11091   if (std::distance(FIt, FEnd) != 1 ||
11092       !FIt->getType()->isIntegralOrEnumerationType()) {
11093     return UnsupportedSTLError();
11094   }
11095 
11096   // Build each of the require values and store them in Info.
11097   for (ComparisonCategoryResult CCR :
11098        ComparisonCategories::getPossibleResultsForType(Kind)) {
11099     StringRef MemName = ComparisonCategories::getResultString(CCR);
11100     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11101 
11102     if (!ValInfo)
11103       return UnsupportedSTLError(USS_MissingMember, MemName);
11104 
11105     VarDecl *VD = ValInfo->VD;
11106     assert(VD && "should not be null!");
11107 
11108     // Attempt to diagnose reasons why the STL definition of this type
11109     // might be foobar, including it failing to be a constant expression.
11110     // TODO Handle more ways the lookup or result can be invalid.
11111     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11112         !VD->checkInitIsICE())
11113       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11114 
11115     // Attempt to evaluate the var decl as a constant expression and extract
11116     // the value of its first field as a ICE. If this fails, the STL
11117     // implementation is not supported.
11118     if (!ValInfo->hasValidIntValue())
11119       return UnsupportedSTLError();
11120 
11121     MarkVariableReferenced(Loc, VD);
11122   }
11123 
11124   // We've successfully built the required types and expressions. Update
11125   // the cache and return the newly cached value.
11126   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11127   return Info->getType();
11128 }
11129 
11130 /// Retrieve the special "std" namespace, which may require us to
11131 /// implicitly define the namespace.
11132 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11133   if (!StdNamespace) {
11134     // The "std" namespace has not yet been defined, so build one implicitly.
11135     StdNamespace = NamespaceDecl::Create(Context,
11136                                          Context.getTranslationUnitDecl(),
11137                                          /*Inline=*/false,
11138                                          SourceLocation(), SourceLocation(),
11139                                          &PP.getIdentifierTable().get("std"),
11140                                          /*PrevDecl=*/nullptr);
11141     getStdNamespace()->setImplicit(true);
11142   }
11143 
11144   return getStdNamespace();
11145 }
11146 
11147 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11148   assert(getLangOpts().CPlusPlus &&
11149          "Looking for std::initializer_list outside of C++.");
11150 
11151   // We're looking for implicit instantiations of
11152   // template <typename E> class std::initializer_list.
11153 
11154   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11155     return false;
11156 
11157   ClassTemplateDecl *Template = nullptr;
11158   const TemplateArgument *Arguments = nullptr;
11159 
11160   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11161 
11162     ClassTemplateSpecializationDecl *Specialization =
11163         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11164     if (!Specialization)
11165       return false;
11166 
11167     Template = Specialization->getSpecializedTemplate();
11168     Arguments = Specialization->getTemplateArgs().data();
11169   } else if (const TemplateSpecializationType *TST =
11170                  Ty->getAs<TemplateSpecializationType>()) {
11171     Template = dyn_cast_or_null<ClassTemplateDecl>(
11172         TST->getTemplateName().getAsTemplateDecl());
11173     Arguments = TST->getArgs();
11174   }
11175   if (!Template)
11176     return false;
11177 
11178   if (!StdInitializerList) {
11179     // Haven't recognized std::initializer_list yet, maybe this is it.
11180     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11181     if (TemplateClass->getIdentifier() !=
11182             &PP.getIdentifierTable().get("initializer_list") ||
11183         !getStdNamespace()->InEnclosingNamespaceSetOf(
11184             TemplateClass->getDeclContext()))
11185       return false;
11186     // This is a template called std::initializer_list, but is it the right
11187     // template?
11188     TemplateParameterList *Params = Template->getTemplateParameters();
11189     if (Params->getMinRequiredArguments() != 1)
11190       return false;
11191     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11192       return false;
11193 
11194     // It's the right template.
11195     StdInitializerList = Template;
11196   }
11197 
11198   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11199     return false;
11200 
11201   // This is an instance of std::initializer_list. Find the argument type.
11202   if (Element)
11203     *Element = Arguments[0].getAsType();
11204   return true;
11205 }
11206 
11207 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11208   NamespaceDecl *Std = S.getStdNamespace();
11209   if (!Std) {
11210     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11211     return nullptr;
11212   }
11213 
11214   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11215                       Loc, Sema::LookupOrdinaryName);
11216   if (!S.LookupQualifiedName(Result, Std)) {
11217     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11218     return nullptr;
11219   }
11220   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11221   if (!Template) {
11222     Result.suppressDiagnostics();
11223     // We found something weird. Complain about the first thing we found.
11224     NamedDecl *Found = *Result.begin();
11225     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11226     return nullptr;
11227   }
11228 
11229   // We found some template called std::initializer_list. Now verify that it's
11230   // correct.
11231   TemplateParameterList *Params = Template->getTemplateParameters();
11232   if (Params->getMinRequiredArguments() != 1 ||
11233       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11234     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11235     return nullptr;
11236   }
11237 
11238   return Template;
11239 }
11240 
11241 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11242   if (!StdInitializerList) {
11243     StdInitializerList = LookupStdInitializerList(*this, Loc);
11244     if (!StdInitializerList)
11245       return QualType();
11246   }
11247 
11248   TemplateArgumentListInfo Args(Loc, Loc);
11249   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11250                                        Context.getTrivialTypeSourceInfo(Element,
11251                                                                         Loc)));
11252   return Context.getCanonicalType(
11253       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11254 }
11255 
11256 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11257   // C++ [dcl.init.list]p2:
11258   //   A constructor is an initializer-list constructor if its first parameter
11259   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11260   //   std::initializer_list<E> for some type E, and either there are no other
11261   //   parameters or else all other parameters have default arguments.
11262   if (!Ctor->hasOneParamOrDefaultArgs())
11263     return false;
11264 
11265   QualType ArgType = Ctor->getParamDecl(0)->getType();
11266   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11267     ArgType = RT->getPointeeType().getUnqualifiedType();
11268 
11269   return isStdInitializerList(ArgType, nullptr);
11270 }
11271 
11272 /// Determine whether a using statement is in a context where it will be
11273 /// apply in all contexts.
11274 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11275   switch (CurContext->getDeclKind()) {
11276     case Decl::TranslationUnit:
11277       return true;
11278     case Decl::LinkageSpec:
11279       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11280     default:
11281       return false;
11282   }
11283 }
11284 
11285 namespace {
11286 
11287 // Callback to only accept typo corrections that are namespaces.
11288 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11289 public:
11290   bool ValidateCandidate(const TypoCorrection &candidate) override {
11291     if (NamedDecl *ND = candidate.getCorrectionDecl())
11292       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11293     return false;
11294   }
11295 
11296   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11297     return std::make_unique<NamespaceValidatorCCC>(*this);
11298   }
11299 };
11300 
11301 }
11302 
11303 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11304                                        CXXScopeSpec &SS,
11305                                        SourceLocation IdentLoc,
11306                                        IdentifierInfo *Ident) {
11307   R.clear();
11308   NamespaceValidatorCCC CCC{};
11309   if (TypoCorrection Corrected =
11310           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11311                         Sema::CTK_ErrorRecovery)) {
11312     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11313       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11314       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11315                               Ident->getName().equals(CorrectedStr);
11316       S.diagnoseTypo(Corrected,
11317                      S.PDiag(diag::err_using_directive_member_suggest)
11318                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11319                      S.PDiag(diag::note_namespace_defined_here));
11320     } else {
11321       S.diagnoseTypo(Corrected,
11322                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11323                      S.PDiag(diag::note_namespace_defined_here));
11324     }
11325     R.addDecl(Corrected.getFoundDecl());
11326     return true;
11327   }
11328   return false;
11329 }
11330 
11331 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11332                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11333                                 SourceLocation IdentLoc,
11334                                 IdentifierInfo *NamespcName,
11335                                 const ParsedAttributesView &AttrList) {
11336   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11337   assert(NamespcName && "Invalid NamespcName.");
11338   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11339 
11340   // This can only happen along a recovery path.
11341   while (S->isTemplateParamScope())
11342     S = S->getParent();
11343   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11344 
11345   UsingDirectiveDecl *UDir = nullptr;
11346   NestedNameSpecifier *Qualifier = nullptr;
11347   if (SS.isSet())
11348     Qualifier = SS.getScopeRep();
11349 
11350   // Lookup namespace name.
11351   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11352   LookupParsedName(R, S, &SS);
11353   if (R.isAmbiguous())
11354     return nullptr;
11355 
11356   if (R.empty()) {
11357     R.clear();
11358     // Allow "using namespace std;" or "using namespace ::std;" even if
11359     // "std" hasn't been defined yet, for GCC compatibility.
11360     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11361         NamespcName->isStr("std")) {
11362       Diag(IdentLoc, diag::ext_using_undefined_std);
11363       R.addDecl(getOrCreateStdNamespace());
11364       R.resolveKind();
11365     }
11366     // Otherwise, attempt typo correction.
11367     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11368   }
11369 
11370   if (!R.empty()) {
11371     NamedDecl *Named = R.getRepresentativeDecl();
11372     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11373     assert(NS && "expected namespace decl");
11374 
11375     // The use of a nested name specifier may trigger deprecation warnings.
11376     DiagnoseUseOfDecl(Named, IdentLoc);
11377 
11378     // C++ [namespace.udir]p1:
11379     //   A using-directive specifies that the names in the nominated
11380     //   namespace can be used in the scope in which the
11381     //   using-directive appears after the using-directive. During
11382     //   unqualified name lookup (3.4.1), the names appear as if they
11383     //   were declared in the nearest enclosing namespace which
11384     //   contains both the using-directive and the nominated
11385     //   namespace. [Note: in this context, "contains" means "contains
11386     //   directly or indirectly". ]
11387 
11388     // Find enclosing context containing both using-directive and
11389     // nominated namespace.
11390     DeclContext *CommonAncestor = NS;
11391     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11392       CommonAncestor = CommonAncestor->getParent();
11393 
11394     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11395                                       SS.getWithLocInContext(Context),
11396                                       IdentLoc, Named, CommonAncestor);
11397 
11398     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11399         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11400       Diag(IdentLoc, diag::warn_using_directive_in_header);
11401     }
11402 
11403     PushUsingDirective(S, UDir);
11404   } else {
11405     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11406   }
11407 
11408   if (UDir)
11409     ProcessDeclAttributeList(S, UDir, AttrList);
11410 
11411   return UDir;
11412 }
11413 
11414 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11415   // If the scope has an associated entity and the using directive is at
11416   // namespace or translation unit scope, add the UsingDirectiveDecl into
11417   // its lookup structure so qualified name lookup can find it.
11418   DeclContext *Ctx = S->getEntity();
11419   if (Ctx && !Ctx->isFunctionOrMethod())
11420     Ctx->addDecl(UDir);
11421   else
11422     // Otherwise, it is at block scope. The using-directives will affect lookup
11423     // only to the end of the scope.
11424     S->PushUsingDirective(UDir);
11425 }
11426 
11427 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11428                                   SourceLocation UsingLoc,
11429                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11430                                   UnqualifiedId &Name,
11431                                   SourceLocation EllipsisLoc,
11432                                   const ParsedAttributesView &AttrList) {
11433   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11434 
11435   if (SS.isEmpty()) {
11436     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11437     return nullptr;
11438   }
11439 
11440   switch (Name.getKind()) {
11441   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11442   case UnqualifiedIdKind::IK_Identifier:
11443   case UnqualifiedIdKind::IK_OperatorFunctionId:
11444   case UnqualifiedIdKind::IK_LiteralOperatorId:
11445   case UnqualifiedIdKind::IK_ConversionFunctionId:
11446     break;
11447 
11448   case UnqualifiedIdKind::IK_ConstructorName:
11449   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11450     // C++11 inheriting constructors.
11451     Diag(Name.getBeginLoc(),
11452          getLangOpts().CPlusPlus11
11453              ? diag::warn_cxx98_compat_using_decl_constructor
11454              : diag::err_using_decl_constructor)
11455         << SS.getRange();
11456 
11457     if (getLangOpts().CPlusPlus11) break;
11458 
11459     return nullptr;
11460 
11461   case UnqualifiedIdKind::IK_DestructorName:
11462     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11463     return nullptr;
11464 
11465   case UnqualifiedIdKind::IK_TemplateId:
11466     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11467         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11468     return nullptr;
11469 
11470   case UnqualifiedIdKind::IK_DeductionGuideName:
11471     llvm_unreachable("cannot parse qualified deduction guide name");
11472   }
11473 
11474   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11475   DeclarationName TargetName = TargetNameInfo.getName();
11476   if (!TargetName)
11477     return nullptr;
11478 
11479   // Warn about access declarations.
11480   if (UsingLoc.isInvalid()) {
11481     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11482                                  ? diag::err_access_decl
11483                                  : diag::warn_access_decl_deprecated)
11484         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11485   }
11486 
11487   if (EllipsisLoc.isInvalid()) {
11488     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11489         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11490       return nullptr;
11491   } else {
11492     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11493         !TargetNameInfo.containsUnexpandedParameterPack()) {
11494       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11495         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11496       EllipsisLoc = SourceLocation();
11497     }
11498   }
11499 
11500   NamedDecl *UD =
11501       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11502                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11503                             /*IsInstantiation*/false);
11504   if (UD)
11505     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11506 
11507   return UD;
11508 }
11509 
11510 /// Determine whether a using declaration considers the given
11511 /// declarations as "equivalent", e.g., if they are redeclarations of
11512 /// the same entity or are both typedefs of the same type.
11513 static bool
11514 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11515   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11516     return true;
11517 
11518   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11519     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11520       return Context.hasSameType(TD1->getUnderlyingType(),
11521                                  TD2->getUnderlyingType());
11522 
11523   return false;
11524 }
11525 
11526 
11527 /// Determines whether to create a using shadow decl for a particular
11528 /// decl, given the set of decls existing prior to this using lookup.
11529 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11530                                 const LookupResult &Previous,
11531                                 UsingShadowDecl *&PrevShadow) {
11532   // Diagnose finding a decl which is not from a base class of the
11533   // current class.  We do this now because there are cases where this
11534   // function will silently decide not to build a shadow decl, which
11535   // will pre-empt further diagnostics.
11536   //
11537   // We don't need to do this in C++11 because we do the check once on
11538   // the qualifier.
11539   //
11540   // FIXME: diagnose the following if we care enough:
11541   //   struct A { int foo; };
11542   //   struct B : A { using A::foo; };
11543   //   template <class T> struct C : A {};
11544   //   template <class T> struct D : C<T> { using B::foo; } // <---
11545   // This is invalid (during instantiation) in C++03 because B::foo
11546   // resolves to the using decl in B, which is not a base class of D<T>.
11547   // We can't diagnose it immediately because C<T> is an unknown
11548   // specialization.  The UsingShadowDecl in D<T> then points directly
11549   // to A::foo, which will look well-formed when we instantiate.
11550   // The right solution is to not collapse the shadow-decl chain.
11551   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11552     DeclContext *OrigDC = Orig->getDeclContext();
11553 
11554     // Handle enums and anonymous structs.
11555     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11556     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11557     while (OrigRec->isAnonymousStructOrUnion())
11558       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11559 
11560     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11561       if (OrigDC == CurContext) {
11562         Diag(Using->getLocation(),
11563              diag::err_using_decl_nested_name_specifier_is_current_class)
11564           << Using->getQualifierLoc().getSourceRange();
11565         Diag(Orig->getLocation(), diag::note_using_decl_target);
11566         Using->setInvalidDecl();
11567         return true;
11568       }
11569 
11570       Diag(Using->getQualifierLoc().getBeginLoc(),
11571            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11572         << Using->getQualifier()
11573         << cast<CXXRecordDecl>(CurContext)
11574         << Using->getQualifierLoc().getSourceRange();
11575       Diag(Orig->getLocation(), diag::note_using_decl_target);
11576       Using->setInvalidDecl();
11577       return true;
11578     }
11579   }
11580 
11581   if (Previous.empty()) return false;
11582 
11583   NamedDecl *Target = Orig;
11584   if (isa<UsingShadowDecl>(Target))
11585     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11586 
11587   // If the target happens to be one of the previous declarations, we
11588   // don't have a conflict.
11589   //
11590   // FIXME: but we might be increasing its access, in which case we
11591   // should redeclare it.
11592   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11593   bool FoundEquivalentDecl = false;
11594   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11595          I != E; ++I) {
11596     NamedDecl *D = (*I)->getUnderlyingDecl();
11597     // We can have UsingDecls in our Previous results because we use the same
11598     // LookupResult for checking whether the UsingDecl itself is a valid
11599     // redeclaration.
11600     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11601       continue;
11602 
11603     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11604       // C++ [class.mem]p19:
11605       //   If T is the name of a class, then [every named member other than
11606       //   a non-static data member] shall have a name different from T
11607       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11608           !isa<IndirectFieldDecl>(Target) &&
11609           !isa<UnresolvedUsingValueDecl>(Target) &&
11610           DiagnoseClassNameShadow(
11611               CurContext,
11612               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11613         return true;
11614     }
11615 
11616     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11617       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11618         PrevShadow = Shadow;
11619       FoundEquivalentDecl = true;
11620     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11621       // We don't conflict with an existing using shadow decl of an equivalent
11622       // declaration, but we're not a redeclaration of it.
11623       FoundEquivalentDecl = true;
11624     }
11625 
11626     if (isVisible(D))
11627       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11628   }
11629 
11630   if (FoundEquivalentDecl)
11631     return false;
11632 
11633   if (FunctionDecl *FD = Target->getAsFunction()) {
11634     NamedDecl *OldDecl = nullptr;
11635     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11636                           /*IsForUsingDecl*/ true)) {
11637     case Ovl_Overload:
11638       return false;
11639 
11640     case Ovl_NonFunction:
11641       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11642       break;
11643 
11644     // We found a decl with the exact signature.
11645     case Ovl_Match:
11646       // If we're in a record, we want to hide the target, so we
11647       // return true (without a diagnostic) to tell the caller not to
11648       // build a shadow decl.
11649       if (CurContext->isRecord())
11650         return true;
11651 
11652       // If we're not in a record, this is an error.
11653       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11654       break;
11655     }
11656 
11657     Diag(Target->getLocation(), diag::note_using_decl_target);
11658     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11659     Using->setInvalidDecl();
11660     return true;
11661   }
11662 
11663   // Target is not a function.
11664 
11665   if (isa<TagDecl>(Target)) {
11666     // No conflict between a tag and a non-tag.
11667     if (!Tag) return false;
11668 
11669     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11670     Diag(Target->getLocation(), diag::note_using_decl_target);
11671     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11672     Using->setInvalidDecl();
11673     return true;
11674   }
11675 
11676   // No conflict between a tag and a non-tag.
11677   if (!NonTag) return false;
11678 
11679   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11680   Diag(Target->getLocation(), diag::note_using_decl_target);
11681   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11682   Using->setInvalidDecl();
11683   return true;
11684 }
11685 
11686 /// Determine whether a direct base class is a virtual base class.
11687 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11688   if (!Derived->getNumVBases())
11689     return false;
11690   for (auto &B : Derived->bases())
11691     if (B.getType()->getAsCXXRecordDecl() == Base)
11692       return B.isVirtual();
11693   llvm_unreachable("not a direct base class");
11694 }
11695 
11696 /// Builds a shadow declaration corresponding to a 'using' declaration.
11697 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11698                                             UsingDecl *UD,
11699                                             NamedDecl *Orig,
11700                                             UsingShadowDecl *PrevDecl) {
11701   // If we resolved to another shadow declaration, just coalesce them.
11702   NamedDecl *Target = Orig;
11703   if (isa<UsingShadowDecl>(Target)) {
11704     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11705     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11706   }
11707 
11708   NamedDecl *NonTemplateTarget = Target;
11709   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11710     NonTemplateTarget = TargetTD->getTemplatedDecl();
11711 
11712   UsingShadowDecl *Shadow;
11713   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11714     bool IsVirtualBase =
11715         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11716                             UD->getQualifier()->getAsRecordDecl());
11717     Shadow = ConstructorUsingShadowDecl::Create(
11718         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11719   } else {
11720     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11721                                      Target);
11722   }
11723   UD->addShadowDecl(Shadow);
11724 
11725   Shadow->setAccess(UD->getAccess());
11726   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11727     Shadow->setInvalidDecl();
11728 
11729   Shadow->setPreviousDecl(PrevDecl);
11730 
11731   if (S)
11732     PushOnScopeChains(Shadow, S);
11733   else
11734     CurContext->addDecl(Shadow);
11735 
11736 
11737   return Shadow;
11738 }
11739 
11740 /// Hides a using shadow declaration.  This is required by the current
11741 /// using-decl implementation when a resolvable using declaration in a
11742 /// class is followed by a declaration which would hide or override
11743 /// one or more of the using decl's targets; for example:
11744 ///
11745 ///   struct Base { void foo(int); };
11746 ///   struct Derived : Base {
11747 ///     using Base::foo;
11748 ///     void foo(int);
11749 ///   };
11750 ///
11751 /// The governing language is C++03 [namespace.udecl]p12:
11752 ///
11753 ///   When a using-declaration brings names from a base class into a
11754 ///   derived class scope, member functions in the derived class
11755 ///   override and/or hide member functions with the same name and
11756 ///   parameter types in a base class (rather than conflicting).
11757 ///
11758 /// There are two ways to implement this:
11759 ///   (1) optimistically create shadow decls when they're not hidden
11760 ///       by existing declarations, or
11761 ///   (2) don't create any shadow decls (or at least don't make them
11762 ///       visible) until we've fully parsed/instantiated the class.
11763 /// The problem with (1) is that we might have to retroactively remove
11764 /// a shadow decl, which requires several O(n) operations because the
11765 /// decl structures are (very reasonably) not designed for removal.
11766 /// (2) avoids this but is very fiddly and phase-dependent.
11767 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11768   if (Shadow->getDeclName().getNameKind() ==
11769         DeclarationName::CXXConversionFunctionName)
11770     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11771 
11772   // Remove it from the DeclContext...
11773   Shadow->getDeclContext()->removeDecl(Shadow);
11774 
11775   // ...and the scope, if applicable...
11776   if (S) {
11777     S->RemoveDecl(Shadow);
11778     IdResolver.RemoveDecl(Shadow);
11779   }
11780 
11781   // ...and the using decl.
11782   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11783 
11784   // TODO: complain somehow if Shadow was used.  It shouldn't
11785   // be possible for this to happen, because...?
11786 }
11787 
11788 /// Find the base specifier for a base class with the given type.
11789 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11790                                                 QualType DesiredBase,
11791                                                 bool &AnyDependentBases) {
11792   // Check whether the named type is a direct base class.
11793   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11794     .getUnqualifiedType();
11795   for (auto &Base : Derived->bases()) {
11796     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11797     if (CanonicalDesiredBase == BaseType)
11798       return &Base;
11799     if (BaseType->isDependentType())
11800       AnyDependentBases = true;
11801   }
11802   return nullptr;
11803 }
11804 
11805 namespace {
11806 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11807 public:
11808   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11809                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11810       : HasTypenameKeyword(HasTypenameKeyword),
11811         IsInstantiation(IsInstantiation), OldNNS(NNS),
11812         RequireMemberOf(RequireMemberOf) {}
11813 
11814   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11815     NamedDecl *ND = Candidate.getCorrectionDecl();
11816 
11817     // Keywords are not valid here.
11818     if (!ND || isa<NamespaceDecl>(ND))
11819       return false;
11820 
11821     // Completely unqualified names are invalid for a 'using' declaration.
11822     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11823       return false;
11824 
11825     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11826     // reject.
11827 
11828     if (RequireMemberOf) {
11829       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11830       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11831         // No-one ever wants a using-declaration to name an injected-class-name
11832         // of a base class, unless they're declaring an inheriting constructor.
11833         ASTContext &Ctx = ND->getASTContext();
11834         if (!Ctx.getLangOpts().CPlusPlus11)
11835           return false;
11836         QualType FoundType = Ctx.getRecordType(FoundRecord);
11837 
11838         // Check that the injected-class-name is named as a member of its own
11839         // type; we don't want to suggest 'using Derived::Base;', since that
11840         // means something else.
11841         NestedNameSpecifier *Specifier =
11842             Candidate.WillReplaceSpecifier()
11843                 ? Candidate.getCorrectionSpecifier()
11844                 : OldNNS;
11845         if (!Specifier->getAsType() ||
11846             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11847           return false;
11848 
11849         // Check that this inheriting constructor declaration actually names a
11850         // direct base class of the current class.
11851         bool AnyDependentBases = false;
11852         if (!findDirectBaseWithType(RequireMemberOf,
11853                                     Ctx.getRecordType(FoundRecord),
11854                                     AnyDependentBases) &&
11855             !AnyDependentBases)
11856           return false;
11857       } else {
11858         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11859         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11860           return false;
11861 
11862         // FIXME: Check that the base class member is accessible?
11863       }
11864     } else {
11865       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11866       if (FoundRecord && FoundRecord->isInjectedClassName())
11867         return false;
11868     }
11869 
11870     if (isa<TypeDecl>(ND))
11871       return HasTypenameKeyword || !IsInstantiation;
11872 
11873     return !HasTypenameKeyword;
11874   }
11875 
11876   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11877     return std::make_unique<UsingValidatorCCC>(*this);
11878   }
11879 
11880 private:
11881   bool HasTypenameKeyword;
11882   bool IsInstantiation;
11883   NestedNameSpecifier *OldNNS;
11884   CXXRecordDecl *RequireMemberOf;
11885 };
11886 } // end anonymous namespace
11887 
11888 /// Builds a using declaration.
11889 ///
11890 /// \param IsInstantiation - Whether this call arises from an
11891 ///   instantiation of an unresolved using declaration.  We treat
11892 ///   the lookup differently for these declarations.
11893 NamedDecl *Sema::BuildUsingDeclaration(
11894     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11895     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11896     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11897     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11898   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11899   SourceLocation IdentLoc = NameInfo.getLoc();
11900   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11901 
11902   // FIXME: We ignore attributes for now.
11903 
11904   // For an inheriting constructor declaration, the name of the using
11905   // declaration is the name of a constructor in this class, not in the
11906   // base class.
11907   DeclarationNameInfo UsingName = NameInfo;
11908   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11909     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11910       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11911           Context.getCanonicalType(Context.getRecordType(RD))));
11912 
11913   // Do the redeclaration lookup in the current scope.
11914   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11915                         ForVisibleRedeclaration);
11916   Previous.setHideTags(false);
11917   if (S) {
11918     LookupName(Previous, S);
11919 
11920     // It is really dumb that we have to do this.
11921     LookupResult::Filter F = Previous.makeFilter();
11922     while (F.hasNext()) {
11923       NamedDecl *D = F.next();
11924       if (!isDeclInScope(D, CurContext, S))
11925         F.erase();
11926       // If we found a local extern declaration that's not ordinarily visible,
11927       // and this declaration is being added to a non-block scope, ignore it.
11928       // We're only checking for scope conflicts here, not also for violations
11929       // of the linkage rules.
11930       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11931                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11932         F.erase();
11933     }
11934     F.done();
11935   } else {
11936     assert(IsInstantiation && "no scope in non-instantiation");
11937     if (CurContext->isRecord())
11938       LookupQualifiedName(Previous, CurContext);
11939     else {
11940       // No redeclaration check is needed here; in non-member contexts we
11941       // diagnosed all possible conflicts with other using-declarations when
11942       // building the template:
11943       //
11944       // For a dependent non-type using declaration, the only valid case is
11945       // if we instantiate to a single enumerator. We check for conflicts
11946       // between shadow declarations we introduce, and we check in the template
11947       // definition for conflicts between a non-type using declaration and any
11948       // other declaration, which together covers all cases.
11949       //
11950       // A dependent typename using declaration will never successfully
11951       // instantiate, since it will always name a class member, so we reject
11952       // that in the template definition.
11953     }
11954   }
11955 
11956   // Check for invalid redeclarations.
11957   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11958                                   SS, IdentLoc, Previous))
11959     return nullptr;
11960 
11961   // Check for bad qualifiers.
11962   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11963                               IdentLoc))
11964     return nullptr;
11965 
11966   DeclContext *LookupContext = computeDeclContext(SS);
11967   NamedDecl *D;
11968   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11969   if (!LookupContext || EllipsisLoc.isValid()) {
11970     if (HasTypenameKeyword) {
11971       // FIXME: not all declaration name kinds are legal here
11972       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11973                                               UsingLoc, TypenameLoc,
11974                                               QualifierLoc,
11975                                               IdentLoc, NameInfo.getName(),
11976                                               EllipsisLoc);
11977     } else {
11978       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11979                                            QualifierLoc, NameInfo, EllipsisLoc);
11980     }
11981     D->setAccess(AS);
11982     CurContext->addDecl(D);
11983     return D;
11984   }
11985 
11986   auto Build = [&](bool Invalid) {
11987     UsingDecl *UD =
11988         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11989                           UsingName, HasTypenameKeyword);
11990     UD->setAccess(AS);
11991     CurContext->addDecl(UD);
11992     UD->setInvalidDecl(Invalid);
11993     return UD;
11994   };
11995   auto BuildInvalid = [&]{ return Build(true); };
11996   auto BuildValid = [&]{ return Build(false); };
11997 
11998   if (RequireCompleteDeclContext(SS, LookupContext))
11999     return BuildInvalid();
12000 
12001   // Look up the target name.
12002   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12003 
12004   // Unlike most lookups, we don't always want to hide tag
12005   // declarations: tag names are visible through the using declaration
12006   // even if hidden by ordinary names, *except* in a dependent context
12007   // where it's important for the sanity of two-phase lookup.
12008   if (!IsInstantiation)
12009     R.setHideTags(false);
12010 
12011   // For the purposes of this lookup, we have a base object type
12012   // equal to that of the current context.
12013   if (CurContext->isRecord()) {
12014     R.setBaseObjectType(
12015                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12016   }
12017 
12018   LookupQualifiedName(R, LookupContext);
12019 
12020   // Try to correct typos if possible. If constructor name lookup finds no
12021   // results, that means the named class has no explicit constructors, and we
12022   // suppressed declaring implicit ones (probably because it's dependent or
12023   // invalid).
12024   if (R.empty() &&
12025       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12026     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12027     // it will believe that glibc provides a ::gets in cases where it does not,
12028     // and will try to pull it into namespace std with a using-declaration.
12029     // Just ignore the using-declaration in that case.
12030     auto *II = NameInfo.getName().getAsIdentifierInfo();
12031     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12032         CurContext->isStdNamespace() &&
12033         isa<TranslationUnitDecl>(LookupContext) &&
12034         getSourceManager().isInSystemHeader(UsingLoc))
12035       return nullptr;
12036     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12037                           dyn_cast<CXXRecordDecl>(CurContext));
12038     if (TypoCorrection Corrected =
12039             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12040                         CTK_ErrorRecovery)) {
12041       // We reject candidates where DroppedSpecifier == true, hence the
12042       // literal '0' below.
12043       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12044                                 << NameInfo.getName() << LookupContext << 0
12045                                 << SS.getRange());
12046 
12047       // If we picked a correction with no attached Decl we can't do anything
12048       // useful with it, bail out.
12049       NamedDecl *ND = Corrected.getCorrectionDecl();
12050       if (!ND)
12051         return BuildInvalid();
12052 
12053       // If we corrected to an inheriting constructor, handle it as one.
12054       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12055       if (RD && RD->isInjectedClassName()) {
12056         // The parent of the injected class name is the class itself.
12057         RD = cast<CXXRecordDecl>(RD->getParent());
12058 
12059         // Fix up the information we'll use to build the using declaration.
12060         if (Corrected.WillReplaceSpecifier()) {
12061           NestedNameSpecifierLocBuilder Builder;
12062           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12063                               QualifierLoc.getSourceRange());
12064           QualifierLoc = Builder.getWithLocInContext(Context);
12065         }
12066 
12067         // In this case, the name we introduce is the name of a derived class
12068         // constructor.
12069         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12070         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12071             Context.getCanonicalType(Context.getRecordType(CurClass))));
12072         UsingName.setNamedTypeInfo(nullptr);
12073         for (auto *Ctor : LookupConstructors(RD))
12074           R.addDecl(Ctor);
12075         R.resolveKind();
12076       } else {
12077         // FIXME: Pick up all the declarations if we found an overloaded
12078         // function.
12079         UsingName.setName(ND->getDeclName());
12080         R.addDecl(ND);
12081       }
12082     } else {
12083       Diag(IdentLoc, diag::err_no_member)
12084         << NameInfo.getName() << LookupContext << SS.getRange();
12085       return BuildInvalid();
12086     }
12087   }
12088 
12089   if (R.isAmbiguous())
12090     return BuildInvalid();
12091 
12092   if (HasTypenameKeyword) {
12093     // If we asked for a typename and got a non-type decl, error out.
12094     if (!R.getAsSingle<TypeDecl>()) {
12095       Diag(IdentLoc, diag::err_using_typename_non_type);
12096       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12097         Diag((*I)->getUnderlyingDecl()->getLocation(),
12098              diag::note_using_decl_target);
12099       return BuildInvalid();
12100     }
12101   } else {
12102     // If we asked for a non-typename and we got a type, error out,
12103     // but only if this is an instantiation of an unresolved using
12104     // decl.  Otherwise just silently find the type name.
12105     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12106       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12107       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12108       return BuildInvalid();
12109     }
12110   }
12111 
12112   // C++14 [namespace.udecl]p6:
12113   // A using-declaration shall not name a namespace.
12114   if (R.getAsSingle<NamespaceDecl>()) {
12115     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12116       << SS.getRange();
12117     return BuildInvalid();
12118   }
12119 
12120   // C++14 [namespace.udecl]p7:
12121   // A using-declaration shall not name a scoped enumerator.
12122   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12123     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12124       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12125         << SS.getRange();
12126       return BuildInvalid();
12127     }
12128   }
12129 
12130   UsingDecl *UD = BuildValid();
12131 
12132   // Some additional rules apply to inheriting constructors.
12133   if (UsingName.getName().getNameKind() ==
12134         DeclarationName::CXXConstructorName) {
12135     // Suppress access diagnostics; the access check is instead performed at the
12136     // point of use for an inheriting constructor.
12137     R.suppressDiagnostics();
12138     if (CheckInheritingConstructorUsingDecl(UD))
12139       return UD;
12140   }
12141 
12142   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12143     UsingShadowDecl *PrevDecl = nullptr;
12144     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12145       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12146   }
12147 
12148   return UD;
12149 }
12150 
12151 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12152                                     ArrayRef<NamedDecl *> Expansions) {
12153   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12154          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12155          isa<UsingPackDecl>(InstantiatedFrom));
12156 
12157   auto *UPD =
12158       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12159   UPD->setAccess(InstantiatedFrom->getAccess());
12160   CurContext->addDecl(UPD);
12161   return UPD;
12162 }
12163 
12164 /// Additional checks for a using declaration referring to a constructor name.
12165 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12166   assert(!UD->hasTypename() && "expecting a constructor name");
12167 
12168   const Type *SourceType = UD->getQualifier()->getAsType();
12169   assert(SourceType &&
12170          "Using decl naming constructor doesn't have type in scope spec.");
12171   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12172 
12173   // Check whether the named type is a direct base class.
12174   bool AnyDependentBases = false;
12175   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12176                                       AnyDependentBases);
12177   if (!Base && !AnyDependentBases) {
12178     Diag(UD->getUsingLoc(),
12179          diag::err_using_decl_constructor_not_in_direct_base)
12180       << UD->getNameInfo().getSourceRange()
12181       << QualType(SourceType, 0) << TargetClass;
12182     UD->setInvalidDecl();
12183     return true;
12184   }
12185 
12186   if (Base)
12187     Base->setInheritConstructors();
12188 
12189   return false;
12190 }
12191 
12192 /// Checks that the given using declaration is not an invalid
12193 /// redeclaration.  Note that this is checking only for the using decl
12194 /// itself, not for any ill-formedness among the UsingShadowDecls.
12195 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12196                                        bool HasTypenameKeyword,
12197                                        const CXXScopeSpec &SS,
12198                                        SourceLocation NameLoc,
12199                                        const LookupResult &Prev) {
12200   NestedNameSpecifier *Qual = SS.getScopeRep();
12201 
12202   // C++03 [namespace.udecl]p8:
12203   // C++0x [namespace.udecl]p10:
12204   //   A using-declaration is a declaration and can therefore be used
12205   //   repeatedly where (and only where) multiple declarations are
12206   //   allowed.
12207   //
12208   // That's in non-member contexts.
12209   if (!CurContext->getRedeclContext()->isRecord()) {
12210     // A dependent qualifier outside a class can only ever resolve to an
12211     // enumeration type. Therefore it conflicts with any other non-type
12212     // declaration in the same scope.
12213     // FIXME: How should we check for dependent type-type conflicts at block
12214     // scope?
12215     if (Qual->isDependent() && !HasTypenameKeyword) {
12216       for (auto *D : Prev) {
12217         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12218           bool OldCouldBeEnumerator =
12219               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12220           Diag(NameLoc,
12221                OldCouldBeEnumerator ? diag::err_redefinition
12222                                     : diag::err_redefinition_different_kind)
12223               << Prev.getLookupName();
12224           Diag(D->getLocation(), diag::note_previous_definition);
12225           return true;
12226         }
12227       }
12228     }
12229     return false;
12230   }
12231 
12232   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12233     NamedDecl *D = *I;
12234 
12235     bool DTypename;
12236     NestedNameSpecifier *DQual;
12237     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12238       DTypename = UD->hasTypename();
12239       DQual = UD->getQualifier();
12240     } else if (UnresolvedUsingValueDecl *UD
12241                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12242       DTypename = false;
12243       DQual = UD->getQualifier();
12244     } else if (UnresolvedUsingTypenameDecl *UD
12245                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12246       DTypename = true;
12247       DQual = UD->getQualifier();
12248     } else continue;
12249 
12250     // using decls differ if one says 'typename' and the other doesn't.
12251     // FIXME: non-dependent using decls?
12252     if (HasTypenameKeyword != DTypename) continue;
12253 
12254     // using decls differ if they name different scopes (but note that
12255     // template instantiation can cause this check to trigger when it
12256     // didn't before instantiation).
12257     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12258         Context.getCanonicalNestedNameSpecifier(DQual))
12259       continue;
12260 
12261     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12262     Diag(D->getLocation(), diag::note_using_decl) << 1;
12263     return true;
12264   }
12265 
12266   return false;
12267 }
12268 
12269 
12270 /// Checks that the given nested-name qualifier used in a using decl
12271 /// in the current context is appropriately related to the current
12272 /// scope.  If an error is found, diagnoses it and returns true.
12273 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12274                                    bool HasTypename,
12275                                    const CXXScopeSpec &SS,
12276                                    const DeclarationNameInfo &NameInfo,
12277                                    SourceLocation NameLoc) {
12278   DeclContext *NamedContext = computeDeclContext(SS);
12279 
12280   if (!CurContext->isRecord()) {
12281     // C++03 [namespace.udecl]p3:
12282     // C++0x [namespace.udecl]p8:
12283     //   A using-declaration for a class member shall be a member-declaration.
12284 
12285     // If we weren't able to compute a valid scope, it might validly be a
12286     // dependent class scope or a dependent enumeration unscoped scope. If
12287     // we have a 'typename' keyword, the scope must resolve to a class type.
12288     if ((HasTypename && !NamedContext) ||
12289         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12290       auto *RD = NamedContext
12291                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12292                      : nullptr;
12293       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12294         RD = nullptr;
12295 
12296       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12297         << SS.getRange();
12298 
12299       // If we have a complete, non-dependent source type, try to suggest a
12300       // way to get the same effect.
12301       if (!RD)
12302         return true;
12303 
12304       // Find what this using-declaration was referring to.
12305       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12306       R.setHideTags(false);
12307       R.suppressDiagnostics();
12308       LookupQualifiedName(R, RD);
12309 
12310       if (R.getAsSingle<TypeDecl>()) {
12311         if (getLangOpts().CPlusPlus11) {
12312           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12313           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12314             << 0 // alias declaration
12315             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12316                                           NameInfo.getName().getAsString() +
12317                                               " = ");
12318         } else {
12319           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12320           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12321           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12322             << 1 // typedef declaration
12323             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12324             << FixItHint::CreateInsertion(
12325                    InsertLoc, " " + NameInfo.getName().getAsString());
12326         }
12327       } else if (R.getAsSingle<VarDecl>()) {
12328         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12329         // repeating the type of the static data member here.
12330         FixItHint FixIt;
12331         if (getLangOpts().CPlusPlus11) {
12332           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12333           FixIt = FixItHint::CreateReplacement(
12334               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12335         }
12336 
12337         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12338           << 2 // reference declaration
12339           << FixIt;
12340       } else if (R.getAsSingle<EnumConstantDecl>()) {
12341         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12342         // repeating the type of the enumeration here, and we can't do so if
12343         // the type is anonymous.
12344         FixItHint FixIt;
12345         if (getLangOpts().CPlusPlus11) {
12346           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12347           FixIt = FixItHint::CreateReplacement(
12348               UsingLoc,
12349               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12350         }
12351 
12352         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12353           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12354           << FixIt;
12355       }
12356       return true;
12357     }
12358 
12359     // Otherwise, this might be valid.
12360     return false;
12361   }
12362 
12363   // The current scope is a record.
12364 
12365   // If the named context is dependent, we can't decide much.
12366   if (!NamedContext) {
12367     // FIXME: in C++0x, we can diagnose if we can prove that the
12368     // nested-name-specifier does not refer to a base class, which is
12369     // still possible in some cases.
12370 
12371     // Otherwise we have to conservatively report that things might be
12372     // okay.
12373     return false;
12374   }
12375 
12376   if (!NamedContext->isRecord()) {
12377     // Ideally this would point at the last name in the specifier,
12378     // but we don't have that level of source info.
12379     Diag(SS.getRange().getBegin(),
12380          diag::err_using_decl_nested_name_specifier_is_not_class)
12381       << SS.getScopeRep() << SS.getRange();
12382     return true;
12383   }
12384 
12385   if (!NamedContext->isDependentContext() &&
12386       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12387     return true;
12388 
12389   if (getLangOpts().CPlusPlus11) {
12390     // C++11 [namespace.udecl]p3:
12391     //   In a using-declaration used as a member-declaration, the
12392     //   nested-name-specifier shall name a base class of the class
12393     //   being defined.
12394 
12395     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12396                                  cast<CXXRecordDecl>(NamedContext))) {
12397       if (CurContext == NamedContext) {
12398         Diag(NameLoc,
12399              diag::err_using_decl_nested_name_specifier_is_current_class)
12400           << SS.getRange();
12401         return true;
12402       }
12403 
12404       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12405         Diag(SS.getRange().getBegin(),
12406              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12407           << SS.getScopeRep()
12408           << cast<CXXRecordDecl>(CurContext)
12409           << SS.getRange();
12410       }
12411       return true;
12412     }
12413 
12414     return false;
12415   }
12416 
12417   // C++03 [namespace.udecl]p4:
12418   //   A using-declaration used as a member-declaration shall refer
12419   //   to a member of a base class of the class being defined [etc.].
12420 
12421   // Salient point: SS doesn't have to name a base class as long as
12422   // lookup only finds members from base classes.  Therefore we can
12423   // diagnose here only if we can prove that that can't happen,
12424   // i.e. if the class hierarchies provably don't intersect.
12425 
12426   // TODO: it would be nice if "definitely valid" results were cached
12427   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12428   // need to be repeated.
12429 
12430   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12431   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12432     Bases.insert(Base);
12433     return true;
12434   };
12435 
12436   // Collect all bases. Return false if we find a dependent base.
12437   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12438     return false;
12439 
12440   // Returns true if the base is dependent or is one of the accumulated base
12441   // classes.
12442   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12443     return !Bases.count(Base);
12444   };
12445 
12446   // Return false if the class has a dependent base or if it or one
12447   // of its bases is present in the base set of the current context.
12448   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12449       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12450     return false;
12451 
12452   Diag(SS.getRange().getBegin(),
12453        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12454     << SS.getScopeRep()
12455     << cast<CXXRecordDecl>(CurContext)
12456     << SS.getRange();
12457 
12458   return true;
12459 }
12460 
12461 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12462                                   MultiTemplateParamsArg TemplateParamLists,
12463                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12464                                   const ParsedAttributesView &AttrList,
12465                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12466   // Skip up to the relevant declaration scope.
12467   while (S->isTemplateParamScope())
12468     S = S->getParent();
12469   assert((S->getFlags() & Scope::DeclScope) &&
12470          "got alias-declaration outside of declaration scope");
12471 
12472   if (Type.isInvalid())
12473     return nullptr;
12474 
12475   bool Invalid = false;
12476   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12477   TypeSourceInfo *TInfo = nullptr;
12478   GetTypeFromParser(Type.get(), &TInfo);
12479 
12480   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12481     return nullptr;
12482 
12483   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12484                                       UPPC_DeclarationType)) {
12485     Invalid = true;
12486     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12487                                              TInfo->getTypeLoc().getBeginLoc());
12488   }
12489 
12490   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12491                         TemplateParamLists.size()
12492                             ? forRedeclarationInCurContext()
12493                             : ForVisibleRedeclaration);
12494   LookupName(Previous, S);
12495 
12496   // Warn about shadowing the name of a template parameter.
12497   if (Previous.isSingleResult() &&
12498       Previous.getFoundDecl()->isTemplateParameter()) {
12499     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12500     Previous.clear();
12501   }
12502 
12503   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12504          "name in alias declaration must be an identifier");
12505   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12506                                                Name.StartLocation,
12507                                                Name.Identifier, TInfo);
12508 
12509   NewTD->setAccess(AS);
12510 
12511   if (Invalid)
12512     NewTD->setInvalidDecl();
12513 
12514   ProcessDeclAttributeList(S, NewTD, AttrList);
12515   AddPragmaAttributes(S, NewTD);
12516 
12517   CheckTypedefForVariablyModifiedType(S, NewTD);
12518   Invalid |= NewTD->isInvalidDecl();
12519 
12520   bool Redeclaration = false;
12521 
12522   NamedDecl *NewND;
12523   if (TemplateParamLists.size()) {
12524     TypeAliasTemplateDecl *OldDecl = nullptr;
12525     TemplateParameterList *OldTemplateParams = nullptr;
12526 
12527     if (TemplateParamLists.size() != 1) {
12528       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12529         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12530          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12531     }
12532     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12533 
12534     // Check that we can declare a template here.
12535     if (CheckTemplateDeclScope(S, TemplateParams))
12536       return nullptr;
12537 
12538     // Only consider previous declarations in the same scope.
12539     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12540                          /*ExplicitInstantiationOrSpecialization*/false);
12541     if (!Previous.empty()) {
12542       Redeclaration = true;
12543 
12544       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12545       if (!OldDecl && !Invalid) {
12546         Diag(UsingLoc, diag::err_redefinition_different_kind)
12547           << Name.Identifier;
12548 
12549         NamedDecl *OldD = Previous.getRepresentativeDecl();
12550         if (OldD->getLocation().isValid())
12551           Diag(OldD->getLocation(), diag::note_previous_definition);
12552 
12553         Invalid = true;
12554       }
12555 
12556       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12557         if (TemplateParameterListsAreEqual(TemplateParams,
12558                                            OldDecl->getTemplateParameters(),
12559                                            /*Complain=*/true,
12560                                            TPL_TemplateMatch))
12561           OldTemplateParams =
12562               OldDecl->getMostRecentDecl()->getTemplateParameters();
12563         else
12564           Invalid = true;
12565 
12566         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12567         if (!Invalid &&
12568             !Context.hasSameType(OldTD->getUnderlyingType(),
12569                                  NewTD->getUnderlyingType())) {
12570           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12571           // but we can't reasonably accept it.
12572           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12573             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12574           if (OldTD->getLocation().isValid())
12575             Diag(OldTD->getLocation(), diag::note_previous_definition);
12576           Invalid = true;
12577         }
12578       }
12579     }
12580 
12581     // Merge any previous default template arguments into our parameters,
12582     // and check the parameter list.
12583     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12584                                    TPC_TypeAliasTemplate))
12585       return nullptr;
12586 
12587     TypeAliasTemplateDecl *NewDecl =
12588       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12589                                     Name.Identifier, TemplateParams,
12590                                     NewTD);
12591     NewTD->setDescribedAliasTemplate(NewDecl);
12592 
12593     NewDecl->setAccess(AS);
12594 
12595     if (Invalid)
12596       NewDecl->setInvalidDecl();
12597     else if (OldDecl) {
12598       NewDecl->setPreviousDecl(OldDecl);
12599       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12600     }
12601 
12602     NewND = NewDecl;
12603   } else {
12604     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12605       setTagNameForLinkagePurposes(TD, NewTD);
12606       handleTagNumbering(TD, S);
12607     }
12608     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12609     NewND = NewTD;
12610   }
12611 
12612   PushOnScopeChains(NewND, S);
12613   ActOnDocumentableDecl(NewND);
12614   return NewND;
12615 }
12616 
12617 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12618                                    SourceLocation AliasLoc,
12619                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12620                                    SourceLocation IdentLoc,
12621                                    IdentifierInfo *Ident) {
12622 
12623   // Lookup the namespace name.
12624   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12625   LookupParsedName(R, S, &SS);
12626 
12627   if (R.isAmbiguous())
12628     return nullptr;
12629 
12630   if (R.empty()) {
12631     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12632       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12633       return nullptr;
12634     }
12635   }
12636   assert(!R.isAmbiguous() && !R.empty());
12637   NamedDecl *ND = R.getRepresentativeDecl();
12638 
12639   // Check if we have a previous declaration with the same name.
12640   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12641                      ForVisibleRedeclaration);
12642   LookupName(PrevR, S);
12643 
12644   // Check we're not shadowing a template parameter.
12645   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12646     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12647     PrevR.clear();
12648   }
12649 
12650   // Filter out any other lookup result from an enclosing scope.
12651   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12652                        /*AllowInlineNamespace*/false);
12653 
12654   // Find the previous declaration and check that we can redeclare it.
12655   NamespaceAliasDecl *Prev = nullptr;
12656   if (PrevR.isSingleResult()) {
12657     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12658     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12659       // We already have an alias with the same name that points to the same
12660       // namespace; check that it matches.
12661       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12662         Prev = AD;
12663       } else if (isVisible(PrevDecl)) {
12664         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12665           << Alias;
12666         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12667           << AD->getNamespace();
12668         return nullptr;
12669       }
12670     } else if (isVisible(PrevDecl)) {
12671       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12672                             ? diag::err_redefinition
12673                             : diag::err_redefinition_different_kind;
12674       Diag(AliasLoc, DiagID) << Alias;
12675       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12676       return nullptr;
12677     }
12678   }
12679 
12680   // The use of a nested name specifier may trigger deprecation warnings.
12681   DiagnoseUseOfDecl(ND, IdentLoc);
12682 
12683   NamespaceAliasDecl *AliasDecl =
12684     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12685                                Alias, SS.getWithLocInContext(Context),
12686                                IdentLoc, ND);
12687   if (Prev)
12688     AliasDecl->setPreviousDecl(Prev);
12689 
12690   PushOnScopeChains(AliasDecl, S);
12691   return AliasDecl;
12692 }
12693 
12694 namespace {
12695 struct SpecialMemberExceptionSpecInfo
12696     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12697   SourceLocation Loc;
12698   Sema::ImplicitExceptionSpecification ExceptSpec;
12699 
12700   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12701                                  Sema::CXXSpecialMember CSM,
12702                                  Sema::InheritedConstructorInfo *ICI,
12703                                  SourceLocation Loc)
12704       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12705 
12706   bool visitBase(CXXBaseSpecifier *Base);
12707   bool visitField(FieldDecl *FD);
12708 
12709   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12710                            unsigned Quals);
12711 
12712   void visitSubobjectCall(Subobject Subobj,
12713                           Sema::SpecialMemberOverloadResult SMOR);
12714 };
12715 }
12716 
12717 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12718   auto *RT = Base->getType()->getAs<RecordType>();
12719   if (!RT)
12720     return false;
12721 
12722   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12723   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12724   if (auto *BaseCtor = SMOR.getMethod()) {
12725     visitSubobjectCall(Base, BaseCtor);
12726     return false;
12727   }
12728 
12729   visitClassSubobject(BaseClass, Base, 0);
12730   return false;
12731 }
12732 
12733 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12734   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12735     Expr *E = FD->getInClassInitializer();
12736     if (!E)
12737       // FIXME: It's a little wasteful to build and throw away a
12738       // CXXDefaultInitExpr here.
12739       // FIXME: We should have a single context note pointing at Loc, and
12740       // this location should be MD->getLocation() instead, since that's
12741       // the location where we actually use the default init expression.
12742       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12743     if (E)
12744       ExceptSpec.CalledExpr(E);
12745   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12746                             ->getAs<RecordType>()) {
12747     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12748                         FD->getType().getCVRQualifiers());
12749   }
12750   return false;
12751 }
12752 
12753 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12754                                                          Subobject Subobj,
12755                                                          unsigned Quals) {
12756   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12757   bool IsMutable = Field && Field->isMutable();
12758   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12759 }
12760 
12761 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12762     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12763   // Note, if lookup fails, it doesn't matter what exception specification we
12764   // choose because the special member will be deleted.
12765   if (CXXMethodDecl *MD = SMOR.getMethod())
12766     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12767 }
12768 
12769 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12770   llvm::APSInt Result;
12771   ExprResult Converted = CheckConvertedConstantExpression(
12772       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12773   ExplicitSpec.setExpr(Converted.get());
12774   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12775     ExplicitSpec.setKind(Result.getBoolValue()
12776                              ? ExplicitSpecKind::ResolvedTrue
12777                              : ExplicitSpecKind::ResolvedFalse);
12778     return true;
12779   }
12780   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12781   return false;
12782 }
12783 
12784 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12785   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12786   if (!ExplicitExpr->isTypeDependent())
12787     tryResolveExplicitSpecifier(ES);
12788   return ES;
12789 }
12790 
12791 static Sema::ImplicitExceptionSpecification
12792 ComputeDefaultedSpecialMemberExceptionSpec(
12793     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12794     Sema::InheritedConstructorInfo *ICI) {
12795   ComputingExceptionSpec CES(S, MD, Loc);
12796 
12797   CXXRecordDecl *ClassDecl = MD->getParent();
12798 
12799   // C++ [except.spec]p14:
12800   //   An implicitly declared special member function (Clause 12) shall have an
12801   //   exception-specification. [...]
12802   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12803   if (ClassDecl->isInvalidDecl())
12804     return Info.ExceptSpec;
12805 
12806   // FIXME: If this diagnostic fires, we're probably missing a check for
12807   // attempting to resolve an exception specification before it's known
12808   // at a higher level.
12809   if (S.RequireCompleteType(MD->getLocation(),
12810                             S.Context.getRecordType(ClassDecl),
12811                             diag::err_exception_spec_incomplete_type))
12812     return Info.ExceptSpec;
12813 
12814   // C++1z [except.spec]p7:
12815   //   [Look for exceptions thrown by] a constructor selected [...] to
12816   //   initialize a potentially constructed subobject,
12817   // C++1z [except.spec]p8:
12818   //   The exception specification for an implicitly-declared destructor, or a
12819   //   destructor without a noexcept-specifier, is potentially-throwing if and
12820   //   only if any of the destructors for any of its potentially constructed
12821   //   subojects is potentially throwing.
12822   // FIXME: We respect the first rule but ignore the "potentially constructed"
12823   // in the second rule to resolve a core issue (no number yet) that would have
12824   // us reject:
12825   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12826   //   struct B : A {};
12827   //   struct C : B { void f(); };
12828   // ... due to giving B::~B() a non-throwing exception specification.
12829   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12830                                 : Info.VisitAllBases);
12831 
12832   return Info.ExceptSpec;
12833 }
12834 
12835 namespace {
12836 /// RAII object to register a special member as being currently declared.
12837 struct DeclaringSpecialMember {
12838   Sema &S;
12839   Sema::SpecialMemberDecl D;
12840   Sema::ContextRAII SavedContext;
12841   bool WasAlreadyBeingDeclared;
12842 
12843   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12844       : S(S), D(RD, CSM), SavedContext(S, RD) {
12845     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12846     if (WasAlreadyBeingDeclared)
12847       // This almost never happens, but if it does, ensure that our cache
12848       // doesn't contain a stale result.
12849       S.SpecialMemberCache.clear();
12850     else {
12851       // Register a note to be produced if we encounter an error while
12852       // declaring the special member.
12853       Sema::CodeSynthesisContext Ctx;
12854       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12855       // FIXME: We don't have a location to use here. Using the class's
12856       // location maintains the fiction that we declare all special members
12857       // with the class, but (1) it's not clear that lying about that helps our
12858       // users understand what's going on, and (2) there may be outer contexts
12859       // on the stack (some of which are relevant) and printing them exposes
12860       // our lies.
12861       Ctx.PointOfInstantiation = RD->getLocation();
12862       Ctx.Entity = RD;
12863       Ctx.SpecialMember = CSM;
12864       S.pushCodeSynthesisContext(Ctx);
12865     }
12866   }
12867   ~DeclaringSpecialMember() {
12868     if (!WasAlreadyBeingDeclared) {
12869       S.SpecialMembersBeingDeclared.erase(D);
12870       S.popCodeSynthesisContext();
12871     }
12872   }
12873 
12874   /// Are we already trying to declare this special member?
12875   bool isAlreadyBeingDeclared() const {
12876     return WasAlreadyBeingDeclared;
12877   }
12878 };
12879 }
12880 
12881 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12882   // Look up any existing declarations, but don't trigger declaration of all
12883   // implicit special members with this name.
12884   DeclarationName Name = FD->getDeclName();
12885   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12886                  ForExternalRedeclaration);
12887   for (auto *D : FD->getParent()->lookup(Name))
12888     if (auto *Acceptable = R.getAcceptableDecl(D))
12889       R.addDecl(Acceptable);
12890   R.resolveKind();
12891   R.suppressDiagnostics();
12892 
12893   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12894 }
12895 
12896 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12897                                           QualType ResultTy,
12898                                           ArrayRef<QualType> Args) {
12899   // Build an exception specification pointing back at this constructor.
12900   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12901 
12902   LangAS AS = getDefaultCXXMethodAddrSpace();
12903   if (AS != LangAS::Default) {
12904     EPI.TypeQuals.addAddressSpace(AS);
12905   }
12906 
12907   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12908   SpecialMem->setType(QT);
12909 }
12910 
12911 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12912                                                      CXXRecordDecl *ClassDecl) {
12913   // C++ [class.ctor]p5:
12914   //   A default constructor for a class X is a constructor of class X
12915   //   that can be called without an argument. If there is no
12916   //   user-declared constructor for class X, a default constructor is
12917   //   implicitly declared. An implicitly-declared default constructor
12918   //   is an inline public member of its class.
12919   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12920          "Should not build implicit default constructor!");
12921 
12922   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12923   if (DSM.isAlreadyBeingDeclared())
12924     return nullptr;
12925 
12926   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12927                                                      CXXDefaultConstructor,
12928                                                      false);
12929 
12930   // Create the actual constructor declaration.
12931   CanQualType ClassType
12932     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12933   SourceLocation ClassLoc = ClassDecl->getLocation();
12934   DeclarationName Name
12935     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12936   DeclarationNameInfo NameInfo(Name, ClassLoc);
12937   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12938       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12939       /*TInfo=*/nullptr, ExplicitSpecifier(),
12940       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12941       Constexpr ? CSK_constexpr : CSK_unspecified);
12942   DefaultCon->setAccess(AS_public);
12943   DefaultCon->setDefaulted();
12944 
12945   if (getLangOpts().CUDA) {
12946     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12947                                             DefaultCon,
12948                                             /* ConstRHS */ false,
12949                                             /* Diagnose */ false);
12950   }
12951 
12952   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12953 
12954   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12955   // constructors is easy to compute.
12956   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12957 
12958   // Note that we have declared this constructor.
12959   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12960 
12961   Scope *S = getScopeForContext(ClassDecl);
12962   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12963 
12964   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12965     SetDeclDeleted(DefaultCon, ClassLoc);
12966 
12967   if (S)
12968     PushOnScopeChains(DefaultCon, S, false);
12969   ClassDecl->addDecl(DefaultCon);
12970 
12971   return DefaultCon;
12972 }
12973 
12974 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12975                                             CXXConstructorDecl *Constructor) {
12976   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12977           !Constructor->doesThisDeclarationHaveABody() &&
12978           !Constructor->isDeleted()) &&
12979     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12980   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12981     return;
12982 
12983   CXXRecordDecl *ClassDecl = Constructor->getParent();
12984   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12985 
12986   SynthesizedFunctionScope Scope(*this, Constructor);
12987 
12988   // The exception specification is needed because we are defining the
12989   // function.
12990   ResolveExceptionSpec(CurrentLocation,
12991                        Constructor->getType()->castAs<FunctionProtoType>());
12992   MarkVTableUsed(CurrentLocation, ClassDecl);
12993 
12994   // Add a context note for diagnostics produced after this point.
12995   Scope.addContextNote(CurrentLocation);
12996 
12997   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12998     Constructor->setInvalidDecl();
12999     return;
13000   }
13001 
13002   SourceLocation Loc = Constructor->getEndLoc().isValid()
13003                            ? Constructor->getEndLoc()
13004                            : Constructor->getLocation();
13005   Constructor->setBody(new (Context) CompoundStmt(Loc));
13006   Constructor->markUsed(Context);
13007 
13008   if (ASTMutationListener *L = getASTMutationListener()) {
13009     L->CompletedImplicitDefinition(Constructor);
13010   }
13011 
13012   DiagnoseUninitializedFields(*this, Constructor);
13013 }
13014 
13015 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13016   // Perform any delayed checks on exception specifications.
13017   CheckDelayedMemberExceptionSpecs();
13018 }
13019 
13020 /// Find or create the fake constructor we synthesize to model constructing an
13021 /// object of a derived class via a constructor of a base class.
13022 CXXConstructorDecl *
13023 Sema::findInheritingConstructor(SourceLocation Loc,
13024                                 CXXConstructorDecl *BaseCtor,
13025                                 ConstructorUsingShadowDecl *Shadow) {
13026   CXXRecordDecl *Derived = Shadow->getParent();
13027   SourceLocation UsingLoc = Shadow->getLocation();
13028 
13029   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13030   // For now we use the name of the base class constructor as a member of the
13031   // derived class to indicate a (fake) inherited constructor name.
13032   DeclarationName Name = BaseCtor->getDeclName();
13033 
13034   // Check to see if we already have a fake constructor for this inherited
13035   // constructor call.
13036   for (NamedDecl *Ctor : Derived->lookup(Name))
13037     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13038                                ->getInheritedConstructor()
13039                                .getConstructor(),
13040                            BaseCtor))
13041       return cast<CXXConstructorDecl>(Ctor);
13042 
13043   DeclarationNameInfo NameInfo(Name, UsingLoc);
13044   TypeSourceInfo *TInfo =
13045       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13046   FunctionProtoTypeLoc ProtoLoc =
13047       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13048 
13049   // Check the inherited constructor is valid and find the list of base classes
13050   // from which it was inherited.
13051   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13052 
13053   bool Constexpr =
13054       BaseCtor->isConstexpr() &&
13055       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13056                                         false, BaseCtor, &ICI);
13057 
13058   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13059       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13060       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13061       /*isImplicitlyDeclared=*/true,
13062       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13063       InheritedConstructor(Shadow, BaseCtor),
13064       BaseCtor->getTrailingRequiresClause());
13065   if (Shadow->isInvalidDecl())
13066     DerivedCtor->setInvalidDecl();
13067 
13068   // Build an unevaluated exception specification for this fake constructor.
13069   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13070   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13071   EPI.ExceptionSpec.Type = EST_Unevaluated;
13072   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13073   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13074                                                FPT->getParamTypes(), EPI));
13075 
13076   // Build the parameter declarations.
13077   SmallVector<ParmVarDecl *, 16> ParamDecls;
13078   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13079     TypeSourceInfo *TInfo =
13080         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13081     ParmVarDecl *PD = ParmVarDecl::Create(
13082         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13083         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13084     PD->setScopeInfo(0, I);
13085     PD->setImplicit();
13086     // Ensure attributes are propagated onto parameters (this matters for
13087     // format, pass_object_size, ...).
13088     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13089     ParamDecls.push_back(PD);
13090     ProtoLoc.setParam(I, PD);
13091   }
13092 
13093   // Set up the new constructor.
13094   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13095   DerivedCtor->setAccess(BaseCtor->getAccess());
13096   DerivedCtor->setParams(ParamDecls);
13097   Derived->addDecl(DerivedCtor);
13098 
13099   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13100     SetDeclDeleted(DerivedCtor, UsingLoc);
13101 
13102   return DerivedCtor;
13103 }
13104 
13105 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13106   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13107                                Ctor->getInheritedConstructor().getShadowDecl());
13108   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13109                             /*Diagnose*/true);
13110 }
13111 
13112 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13113                                        CXXConstructorDecl *Constructor) {
13114   CXXRecordDecl *ClassDecl = Constructor->getParent();
13115   assert(Constructor->getInheritedConstructor() &&
13116          !Constructor->doesThisDeclarationHaveABody() &&
13117          !Constructor->isDeleted());
13118   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13119     return;
13120 
13121   // Initializations are performed "as if by a defaulted default constructor",
13122   // so enter the appropriate scope.
13123   SynthesizedFunctionScope Scope(*this, Constructor);
13124 
13125   // The exception specification is needed because we are defining the
13126   // function.
13127   ResolveExceptionSpec(CurrentLocation,
13128                        Constructor->getType()->castAs<FunctionProtoType>());
13129   MarkVTableUsed(CurrentLocation, ClassDecl);
13130 
13131   // Add a context note for diagnostics produced after this point.
13132   Scope.addContextNote(CurrentLocation);
13133 
13134   ConstructorUsingShadowDecl *Shadow =
13135       Constructor->getInheritedConstructor().getShadowDecl();
13136   CXXConstructorDecl *InheritedCtor =
13137       Constructor->getInheritedConstructor().getConstructor();
13138 
13139   // [class.inhctor.init]p1:
13140   //   initialization proceeds as if a defaulted default constructor is used to
13141   //   initialize the D object and each base class subobject from which the
13142   //   constructor was inherited
13143 
13144   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13145   CXXRecordDecl *RD = Shadow->getParent();
13146   SourceLocation InitLoc = Shadow->getLocation();
13147 
13148   // Build explicit initializers for all base classes from which the
13149   // constructor was inherited.
13150   SmallVector<CXXCtorInitializer*, 8> Inits;
13151   for (bool VBase : {false, true}) {
13152     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13153       if (B.isVirtual() != VBase)
13154         continue;
13155 
13156       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13157       if (!BaseRD)
13158         continue;
13159 
13160       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13161       if (!BaseCtor.first)
13162         continue;
13163 
13164       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13165       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13166           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13167 
13168       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13169       Inits.push_back(new (Context) CXXCtorInitializer(
13170           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13171           SourceLocation()));
13172     }
13173   }
13174 
13175   // We now proceed as if for a defaulted default constructor, with the relevant
13176   // initializers replaced.
13177 
13178   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13179     Constructor->setInvalidDecl();
13180     return;
13181   }
13182 
13183   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13184   Constructor->markUsed(Context);
13185 
13186   if (ASTMutationListener *L = getASTMutationListener()) {
13187     L->CompletedImplicitDefinition(Constructor);
13188   }
13189 
13190   DiagnoseUninitializedFields(*this, Constructor);
13191 }
13192 
13193 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13194   // C++ [class.dtor]p2:
13195   //   If a class has no user-declared destructor, a destructor is
13196   //   declared implicitly. An implicitly-declared destructor is an
13197   //   inline public member of its class.
13198   assert(ClassDecl->needsImplicitDestructor());
13199 
13200   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13201   if (DSM.isAlreadyBeingDeclared())
13202     return nullptr;
13203 
13204   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13205                                                      CXXDestructor,
13206                                                      false);
13207 
13208   // Create the actual destructor declaration.
13209   CanQualType ClassType
13210     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13211   SourceLocation ClassLoc = ClassDecl->getLocation();
13212   DeclarationName Name
13213     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13214   DeclarationNameInfo NameInfo(Name, ClassLoc);
13215   CXXDestructorDecl *Destructor =
13216       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13217                                 QualType(), nullptr, /*isInline=*/true,
13218                                 /*isImplicitlyDeclared=*/true,
13219                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13220   Destructor->setAccess(AS_public);
13221   Destructor->setDefaulted();
13222 
13223   if (getLangOpts().CUDA) {
13224     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13225                                             Destructor,
13226                                             /* ConstRHS */ false,
13227                                             /* Diagnose */ false);
13228   }
13229 
13230   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13231 
13232   // We don't need to use SpecialMemberIsTrivial here; triviality for
13233   // destructors is easy to compute.
13234   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13235   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13236                                 ClassDecl->hasTrivialDestructorForCall());
13237 
13238   // Note that we have declared this destructor.
13239   ++getASTContext().NumImplicitDestructorsDeclared;
13240 
13241   Scope *S = getScopeForContext(ClassDecl);
13242   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13243 
13244   // We can't check whether an implicit destructor is deleted before we complete
13245   // the definition of the class, because its validity depends on the alignment
13246   // of the class. We'll check this from ActOnFields once the class is complete.
13247   if (ClassDecl->isCompleteDefinition() &&
13248       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13249     SetDeclDeleted(Destructor, ClassLoc);
13250 
13251   // Introduce this destructor into its scope.
13252   if (S)
13253     PushOnScopeChains(Destructor, S, false);
13254   ClassDecl->addDecl(Destructor);
13255 
13256   return Destructor;
13257 }
13258 
13259 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13260                                     CXXDestructorDecl *Destructor) {
13261   assert((Destructor->isDefaulted() &&
13262           !Destructor->doesThisDeclarationHaveABody() &&
13263           !Destructor->isDeleted()) &&
13264          "DefineImplicitDestructor - call it for implicit default dtor");
13265   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13266     return;
13267 
13268   CXXRecordDecl *ClassDecl = Destructor->getParent();
13269   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13270 
13271   SynthesizedFunctionScope Scope(*this, Destructor);
13272 
13273   // The exception specification is needed because we are defining the
13274   // function.
13275   ResolveExceptionSpec(CurrentLocation,
13276                        Destructor->getType()->castAs<FunctionProtoType>());
13277   MarkVTableUsed(CurrentLocation, ClassDecl);
13278 
13279   // Add a context note for diagnostics produced after this point.
13280   Scope.addContextNote(CurrentLocation);
13281 
13282   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13283                                          Destructor->getParent());
13284 
13285   if (CheckDestructor(Destructor)) {
13286     Destructor->setInvalidDecl();
13287     return;
13288   }
13289 
13290   SourceLocation Loc = Destructor->getEndLoc().isValid()
13291                            ? Destructor->getEndLoc()
13292                            : Destructor->getLocation();
13293   Destructor->setBody(new (Context) CompoundStmt(Loc));
13294   Destructor->markUsed(Context);
13295 
13296   if (ASTMutationListener *L = getASTMutationListener()) {
13297     L->CompletedImplicitDefinition(Destructor);
13298   }
13299 }
13300 
13301 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13302                                           CXXDestructorDecl *Destructor) {
13303   if (Destructor->isInvalidDecl())
13304     return;
13305 
13306   CXXRecordDecl *ClassDecl = Destructor->getParent();
13307   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13308          "implicit complete dtors unneeded outside MS ABI");
13309   assert(ClassDecl->getNumVBases() > 0 &&
13310          "complete dtor only exists for classes with vbases");
13311 
13312   SynthesizedFunctionScope Scope(*this, Destructor);
13313 
13314   // Add a context note for diagnostics produced after this point.
13315   Scope.addContextNote(CurrentLocation);
13316 
13317   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13318 }
13319 
13320 /// Perform any semantic analysis which needs to be delayed until all
13321 /// pending class member declarations have been parsed.
13322 void Sema::ActOnFinishCXXMemberDecls() {
13323   // If the context is an invalid C++ class, just suppress these checks.
13324   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13325     if (Record->isInvalidDecl()) {
13326       DelayedOverridingExceptionSpecChecks.clear();
13327       DelayedEquivalentExceptionSpecChecks.clear();
13328       return;
13329     }
13330     checkForMultipleExportedDefaultConstructors(*this, Record);
13331   }
13332 }
13333 
13334 void Sema::ActOnFinishCXXNonNestedClass() {
13335   referenceDLLExportedClassMethods();
13336 
13337   if (!DelayedDllExportMemberFunctions.empty()) {
13338     SmallVector<CXXMethodDecl*, 4> WorkList;
13339     std::swap(DelayedDllExportMemberFunctions, WorkList);
13340     for (CXXMethodDecl *M : WorkList) {
13341       DefineDefaultedFunction(*this, M, M->getLocation());
13342 
13343       // Pass the method to the consumer to get emitted. This is not necessary
13344       // for explicit instantiation definitions, as they will get emitted
13345       // anyway.
13346       if (M->getParent()->getTemplateSpecializationKind() !=
13347           TSK_ExplicitInstantiationDefinition)
13348         ActOnFinishInlineFunctionDef(M);
13349     }
13350   }
13351 }
13352 
13353 void Sema::referenceDLLExportedClassMethods() {
13354   if (!DelayedDllExportClasses.empty()) {
13355     // Calling ReferenceDllExportedMembers might cause the current function to
13356     // be called again, so use a local copy of DelayedDllExportClasses.
13357     SmallVector<CXXRecordDecl *, 4> WorkList;
13358     std::swap(DelayedDllExportClasses, WorkList);
13359     for (CXXRecordDecl *Class : WorkList)
13360       ReferenceDllExportedMembers(*this, Class);
13361   }
13362 }
13363 
13364 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13365   assert(getLangOpts().CPlusPlus11 &&
13366          "adjusting dtor exception specs was introduced in c++11");
13367 
13368   if (Destructor->isDependentContext())
13369     return;
13370 
13371   // C++11 [class.dtor]p3:
13372   //   A declaration of a destructor that does not have an exception-
13373   //   specification is implicitly considered to have the same exception-
13374   //   specification as an implicit declaration.
13375   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13376   if (DtorType->hasExceptionSpec())
13377     return;
13378 
13379   // Replace the destructor's type, building off the existing one. Fortunately,
13380   // the only thing of interest in the destructor type is its extended info.
13381   // The return and arguments are fixed.
13382   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13383   EPI.ExceptionSpec.Type = EST_Unevaluated;
13384   EPI.ExceptionSpec.SourceDecl = Destructor;
13385   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13386 
13387   // FIXME: If the destructor has a body that could throw, and the newly created
13388   // spec doesn't allow exceptions, we should emit a warning, because this
13389   // change in behavior can break conforming C++03 programs at runtime.
13390   // However, we don't have a body or an exception specification yet, so it
13391   // needs to be done somewhere else.
13392 }
13393 
13394 namespace {
13395 /// An abstract base class for all helper classes used in building the
13396 //  copy/move operators. These classes serve as factory functions and help us
13397 //  avoid using the same Expr* in the AST twice.
13398 class ExprBuilder {
13399   ExprBuilder(const ExprBuilder&) = delete;
13400   ExprBuilder &operator=(const ExprBuilder&) = delete;
13401 
13402 protected:
13403   static Expr *assertNotNull(Expr *E) {
13404     assert(E && "Expression construction must not fail.");
13405     return E;
13406   }
13407 
13408 public:
13409   ExprBuilder() {}
13410   virtual ~ExprBuilder() {}
13411 
13412   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13413 };
13414 
13415 class RefBuilder: public ExprBuilder {
13416   VarDecl *Var;
13417   QualType VarType;
13418 
13419 public:
13420   Expr *build(Sema &S, SourceLocation Loc) const override {
13421     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13422   }
13423 
13424   RefBuilder(VarDecl *Var, QualType VarType)
13425       : Var(Var), VarType(VarType) {}
13426 };
13427 
13428 class ThisBuilder: public ExprBuilder {
13429 public:
13430   Expr *build(Sema &S, SourceLocation Loc) const override {
13431     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13432   }
13433 };
13434 
13435 class CastBuilder: public ExprBuilder {
13436   const ExprBuilder &Builder;
13437   QualType Type;
13438   ExprValueKind Kind;
13439   const CXXCastPath &Path;
13440 
13441 public:
13442   Expr *build(Sema &S, SourceLocation Loc) const override {
13443     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13444                                              CK_UncheckedDerivedToBase, Kind,
13445                                              &Path).get());
13446   }
13447 
13448   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13449               const CXXCastPath &Path)
13450       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13451 };
13452 
13453 class DerefBuilder: public ExprBuilder {
13454   const ExprBuilder &Builder;
13455 
13456 public:
13457   Expr *build(Sema &S, SourceLocation Loc) const override {
13458     return assertNotNull(
13459         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13460   }
13461 
13462   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13463 };
13464 
13465 class MemberBuilder: public ExprBuilder {
13466   const ExprBuilder &Builder;
13467   QualType Type;
13468   CXXScopeSpec SS;
13469   bool IsArrow;
13470   LookupResult &MemberLookup;
13471 
13472 public:
13473   Expr *build(Sema &S, SourceLocation Loc) const override {
13474     return assertNotNull(S.BuildMemberReferenceExpr(
13475         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13476         nullptr, MemberLookup, nullptr, nullptr).get());
13477   }
13478 
13479   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13480                 LookupResult &MemberLookup)
13481       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13482         MemberLookup(MemberLookup) {}
13483 };
13484 
13485 class MoveCastBuilder: public ExprBuilder {
13486   const ExprBuilder &Builder;
13487 
13488 public:
13489   Expr *build(Sema &S, SourceLocation Loc) const override {
13490     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13491   }
13492 
13493   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13494 };
13495 
13496 class LvalueConvBuilder: public ExprBuilder {
13497   const ExprBuilder &Builder;
13498 
13499 public:
13500   Expr *build(Sema &S, SourceLocation Loc) const override {
13501     return assertNotNull(
13502         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13503   }
13504 
13505   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13506 };
13507 
13508 class SubscriptBuilder: public ExprBuilder {
13509   const ExprBuilder &Base;
13510   const ExprBuilder &Index;
13511 
13512 public:
13513   Expr *build(Sema &S, SourceLocation Loc) const override {
13514     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13515         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13516   }
13517 
13518   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13519       : Base(Base), Index(Index) {}
13520 };
13521 
13522 } // end anonymous namespace
13523 
13524 /// When generating a defaulted copy or move assignment operator, if a field
13525 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13526 /// do so. This optimization only applies for arrays of scalars, and for arrays
13527 /// of class type where the selected copy/move-assignment operator is trivial.
13528 static StmtResult
13529 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13530                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13531   // Compute the size of the memory buffer to be copied.
13532   QualType SizeType = S.Context.getSizeType();
13533   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13534                    S.Context.getTypeSizeInChars(T).getQuantity());
13535 
13536   // Take the address of the field references for "from" and "to". We
13537   // directly construct UnaryOperators here because semantic analysis
13538   // does not permit us to take the address of an xvalue.
13539   Expr *From = FromB.build(S, Loc);
13540   From = UnaryOperator::Create(
13541       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13542       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13543   Expr *To = ToB.build(S, Loc);
13544   To = UnaryOperator::Create(
13545       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13546       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13547 
13548   const Type *E = T->getBaseElementTypeUnsafe();
13549   bool NeedsCollectableMemCpy =
13550       E->isRecordType() &&
13551       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13552 
13553   // Create a reference to the __builtin_objc_memmove_collectable function
13554   StringRef MemCpyName = NeedsCollectableMemCpy ?
13555     "__builtin_objc_memmove_collectable" :
13556     "__builtin_memcpy";
13557   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13558                  Sema::LookupOrdinaryName);
13559   S.LookupName(R, S.TUScope, true);
13560 
13561   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13562   if (!MemCpy)
13563     // Something went horribly wrong earlier, and we will have complained
13564     // about it.
13565     return StmtError();
13566 
13567   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13568                                             VK_RValue, Loc, nullptr);
13569   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13570 
13571   Expr *CallArgs[] = {
13572     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13573   };
13574   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13575                                     Loc, CallArgs, Loc);
13576 
13577   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13578   return Call.getAs<Stmt>();
13579 }
13580 
13581 /// Builds a statement that copies/moves the given entity from \p From to
13582 /// \c To.
13583 ///
13584 /// This routine is used to copy/move the members of a class with an
13585 /// implicitly-declared copy/move assignment operator. When the entities being
13586 /// copied are arrays, this routine builds for loops to copy them.
13587 ///
13588 /// \param S The Sema object used for type-checking.
13589 ///
13590 /// \param Loc The location where the implicit copy/move is being generated.
13591 ///
13592 /// \param T The type of the expressions being copied/moved. Both expressions
13593 /// must have this type.
13594 ///
13595 /// \param To The expression we are copying/moving to.
13596 ///
13597 /// \param From The expression we are copying/moving from.
13598 ///
13599 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13600 /// Otherwise, it's a non-static member subobject.
13601 ///
13602 /// \param Copying Whether we're copying or moving.
13603 ///
13604 /// \param Depth Internal parameter recording the depth of the recursion.
13605 ///
13606 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13607 /// if a memcpy should be used instead.
13608 static StmtResult
13609 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13610                                  const ExprBuilder &To, const ExprBuilder &From,
13611                                  bool CopyingBaseSubobject, bool Copying,
13612                                  unsigned Depth = 0) {
13613   // C++11 [class.copy]p28:
13614   //   Each subobject is assigned in the manner appropriate to its type:
13615   //
13616   //     - if the subobject is of class type, as if by a call to operator= with
13617   //       the subobject as the object expression and the corresponding
13618   //       subobject of x as a single function argument (as if by explicit
13619   //       qualification; that is, ignoring any possible virtual overriding
13620   //       functions in more derived classes);
13621   //
13622   // C++03 [class.copy]p13:
13623   //     - if the subobject is of class type, the copy assignment operator for
13624   //       the class is used (as if by explicit qualification; that is,
13625   //       ignoring any possible virtual overriding functions in more derived
13626   //       classes);
13627   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13628     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13629 
13630     // Look for operator=.
13631     DeclarationName Name
13632       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13633     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13634     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13635 
13636     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13637     // operator.
13638     if (!S.getLangOpts().CPlusPlus11) {
13639       LookupResult::Filter F = OpLookup.makeFilter();
13640       while (F.hasNext()) {
13641         NamedDecl *D = F.next();
13642         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13643           if (Method->isCopyAssignmentOperator() ||
13644               (!Copying && Method->isMoveAssignmentOperator()))
13645             continue;
13646 
13647         F.erase();
13648       }
13649       F.done();
13650     }
13651 
13652     // Suppress the protected check (C++ [class.protected]) for each of the
13653     // assignment operators we found. This strange dance is required when
13654     // we're assigning via a base classes's copy-assignment operator. To
13655     // ensure that we're getting the right base class subobject (without
13656     // ambiguities), we need to cast "this" to that subobject type; to
13657     // ensure that we don't go through the virtual call mechanism, we need
13658     // to qualify the operator= name with the base class (see below). However,
13659     // this means that if the base class has a protected copy assignment
13660     // operator, the protected member access check will fail. So, we
13661     // rewrite "protected" access to "public" access in this case, since we
13662     // know by construction that we're calling from a derived class.
13663     if (CopyingBaseSubobject) {
13664       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13665            L != LEnd; ++L) {
13666         if (L.getAccess() == AS_protected)
13667           L.setAccess(AS_public);
13668       }
13669     }
13670 
13671     // Create the nested-name-specifier that will be used to qualify the
13672     // reference to operator=; this is required to suppress the virtual
13673     // call mechanism.
13674     CXXScopeSpec SS;
13675     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13676     SS.MakeTrivial(S.Context,
13677                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13678                                                CanonicalT),
13679                    Loc);
13680 
13681     // Create the reference to operator=.
13682     ExprResult OpEqualRef
13683       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13684                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13685                                    /*FirstQualifierInScope=*/nullptr,
13686                                    OpLookup,
13687                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13688                                    /*SuppressQualifierCheck=*/true);
13689     if (OpEqualRef.isInvalid())
13690       return StmtError();
13691 
13692     // Build the call to the assignment operator.
13693 
13694     Expr *FromInst = From.build(S, Loc);
13695     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13696                                                   OpEqualRef.getAs<Expr>(),
13697                                                   Loc, FromInst, Loc);
13698     if (Call.isInvalid())
13699       return StmtError();
13700 
13701     // If we built a call to a trivial 'operator=' while copying an array,
13702     // bail out. We'll replace the whole shebang with a memcpy.
13703     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13704     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13705       return StmtResult((Stmt*)nullptr);
13706 
13707     // Convert to an expression-statement, and clean up any produced
13708     // temporaries.
13709     return S.ActOnExprStmt(Call);
13710   }
13711 
13712   //     - if the subobject is of scalar type, the built-in assignment
13713   //       operator is used.
13714   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13715   if (!ArrayTy) {
13716     ExprResult Assignment = S.CreateBuiltinBinOp(
13717         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13718     if (Assignment.isInvalid())
13719       return StmtError();
13720     return S.ActOnExprStmt(Assignment);
13721   }
13722 
13723   //     - if the subobject is an array, each element is assigned, in the
13724   //       manner appropriate to the element type;
13725 
13726   // Construct a loop over the array bounds, e.g.,
13727   //
13728   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13729   //
13730   // that will copy each of the array elements.
13731   QualType SizeType = S.Context.getSizeType();
13732 
13733   // Create the iteration variable.
13734   IdentifierInfo *IterationVarName = nullptr;
13735   {
13736     SmallString<8> Str;
13737     llvm::raw_svector_ostream OS(Str);
13738     OS << "__i" << Depth;
13739     IterationVarName = &S.Context.Idents.get(OS.str());
13740   }
13741   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13742                                           IterationVarName, SizeType,
13743                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13744                                           SC_None);
13745 
13746   // Initialize the iteration variable to zero.
13747   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13748   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13749 
13750   // Creates a reference to the iteration variable.
13751   RefBuilder IterationVarRef(IterationVar, SizeType);
13752   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13753 
13754   // Create the DeclStmt that holds the iteration variable.
13755   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13756 
13757   // Subscript the "from" and "to" expressions with the iteration variable.
13758   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13759   MoveCastBuilder FromIndexMove(FromIndexCopy);
13760   const ExprBuilder *FromIndex;
13761   if (Copying)
13762     FromIndex = &FromIndexCopy;
13763   else
13764     FromIndex = &FromIndexMove;
13765 
13766   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13767 
13768   // Build the copy/move for an individual element of the array.
13769   StmtResult Copy =
13770     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13771                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13772                                      Copying, Depth + 1);
13773   // Bail out if copying fails or if we determined that we should use memcpy.
13774   if (Copy.isInvalid() || !Copy.get())
13775     return Copy;
13776 
13777   // Create the comparison against the array bound.
13778   llvm::APInt Upper
13779     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13780   Expr *Comparison = BinaryOperator::Create(
13781       S.Context, IterationVarRefRVal.build(S, Loc),
13782       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13783       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13784 
13785   // Create the pre-increment of the iteration variable. We can determine
13786   // whether the increment will overflow based on the value of the array
13787   // bound.
13788   Expr *Increment = UnaryOperator::Create(
13789       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13790       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13791 
13792   // Construct the loop that copies all elements of this array.
13793   return S.ActOnForStmt(
13794       Loc, Loc, InitStmt,
13795       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13796       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13797 }
13798 
13799 static StmtResult
13800 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13801                       const ExprBuilder &To, const ExprBuilder &From,
13802                       bool CopyingBaseSubobject, bool Copying) {
13803   // Maybe we should use a memcpy?
13804   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13805       T.isTriviallyCopyableType(S.Context))
13806     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13807 
13808   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13809                                                      CopyingBaseSubobject,
13810                                                      Copying, 0));
13811 
13812   // If we ended up picking a trivial assignment operator for an array of a
13813   // non-trivially-copyable class type, just emit a memcpy.
13814   if (!Result.isInvalid() && !Result.get())
13815     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13816 
13817   return Result;
13818 }
13819 
13820 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13821   // Note: The following rules are largely analoguous to the copy
13822   // constructor rules. Note that virtual bases are not taken into account
13823   // for determining the argument type of the operator. Note also that
13824   // operators taking an object instead of a reference are allowed.
13825   assert(ClassDecl->needsImplicitCopyAssignment());
13826 
13827   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13828   if (DSM.isAlreadyBeingDeclared())
13829     return nullptr;
13830 
13831   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13832   LangAS AS = getDefaultCXXMethodAddrSpace();
13833   if (AS != LangAS::Default)
13834     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13835   QualType RetType = Context.getLValueReferenceType(ArgType);
13836   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13837   if (Const)
13838     ArgType = ArgType.withConst();
13839 
13840   ArgType = Context.getLValueReferenceType(ArgType);
13841 
13842   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13843                                                      CXXCopyAssignment,
13844                                                      Const);
13845 
13846   //   An implicitly-declared copy assignment operator is an inline public
13847   //   member of its class.
13848   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13849   SourceLocation ClassLoc = ClassDecl->getLocation();
13850   DeclarationNameInfo NameInfo(Name, ClassLoc);
13851   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13852       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13853       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13854       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13855       SourceLocation());
13856   CopyAssignment->setAccess(AS_public);
13857   CopyAssignment->setDefaulted();
13858   CopyAssignment->setImplicit();
13859 
13860   if (getLangOpts().CUDA) {
13861     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13862                                             CopyAssignment,
13863                                             /* ConstRHS */ Const,
13864                                             /* Diagnose */ false);
13865   }
13866 
13867   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13868 
13869   // Add the parameter to the operator.
13870   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13871                                                ClassLoc, ClassLoc,
13872                                                /*Id=*/nullptr, ArgType,
13873                                                /*TInfo=*/nullptr, SC_None,
13874                                                nullptr);
13875   CopyAssignment->setParams(FromParam);
13876 
13877   CopyAssignment->setTrivial(
13878     ClassDecl->needsOverloadResolutionForCopyAssignment()
13879       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13880       : ClassDecl->hasTrivialCopyAssignment());
13881 
13882   // Note that we have added this copy-assignment operator.
13883   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13884 
13885   Scope *S = getScopeForContext(ClassDecl);
13886   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13887 
13888   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13889     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13890     SetDeclDeleted(CopyAssignment, ClassLoc);
13891   }
13892 
13893   if (S)
13894     PushOnScopeChains(CopyAssignment, S, false);
13895   ClassDecl->addDecl(CopyAssignment);
13896 
13897   return CopyAssignment;
13898 }
13899 
13900 /// Diagnose an implicit copy operation for a class which is odr-used, but
13901 /// which is deprecated because the class has a user-declared copy constructor,
13902 /// copy assignment operator, or destructor.
13903 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13904   assert(CopyOp->isImplicit());
13905 
13906   CXXRecordDecl *RD = CopyOp->getParent();
13907   CXXMethodDecl *UserDeclaredOperation = nullptr;
13908 
13909   // In Microsoft mode, assignment operations don't affect constructors and
13910   // vice versa.
13911   if (RD->hasUserDeclaredDestructor()) {
13912     UserDeclaredOperation = RD->getDestructor();
13913   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13914              RD->hasUserDeclaredCopyConstructor() &&
13915              !S.getLangOpts().MSVCCompat) {
13916     // Find any user-declared copy constructor.
13917     for (auto *I : RD->ctors()) {
13918       if (I->isCopyConstructor()) {
13919         UserDeclaredOperation = I;
13920         break;
13921       }
13922     }
13923     assert(UserDeclaredOperation);
13924   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13925              RD->hasUserDeclaredCopyAssignment() &&
13926              !S.getLangOpts().MSVCCompat) {
13927     // Find any user-declared move assignment operator.
13928     for (auto *I : RD->methods()) {
13929       if (I->isCopyAssignmentOperator()) {
13930         UserDeclaredOperation = I;
13931         break;
13932       }
13933     }
13934     assert(UserDeclaredOperation);
13935   }
13936 
13937   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13938     S.Diag(UserDeclaredOperation->getLocation(),
13939            isa<CXXDestructorDecl>(UserDeclaredOperation)
13940                ? diag::warn_deprecated_copy_dtor_operation
13941                : diag::warn_deprecated_copy_operation)
13942         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13943   }
13944 }
13945 
13946 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13947                                         CXXMethodDecl *CopyAssignOperator) {
13948   assert((CopyAssignOperator->isDefaulted() &&
13949           CopyAssignOperator->isOverloadedOperator() &&
13950           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13951           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13952           !CopyAssignOperator->isDeleted()) &&
13953          "DefineImplicitCopyAssignment called for wrong function");
13954   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13955     return;
13956 
13957   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13958   if (ClassDecl->isInvalidDecl()) {
13959     CopyAssignOperator->setInvalidDecl();
13960     return;
13961   }
13962 
13963   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13964 
13965   // The exception specification is needed because we are defining the
13966   // function.
13967   ResolveExceptionSpec(CurrentLocation,
13968                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13969 
13970   // Add a context note for diagnostics produced after this point.
13971   Scope.addContextNote(CurrentLocation);
13972 
13973   // C++11 [class.copy]p18:
13974   //   The [definition of an implicitly declared copy assignment operator] is
13975   //   deprecated if the class has a user-declared copy constructor or a
13976   //   user-declared destructor.
13977   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13978     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13979 
13980   // C++0x [class.copy]p30:
13981   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13982   //   for a non-union class X performs memberwise copy assignment of its
13983   //   subobjects. The direct base classes of X are assigned first, in the
13984   //   order of their declaration in the base-specifier-list, and then the
13985   //   immediate non-static data members of X are assigned, in the order in
13986   //   which they were declared in the class definition.
13987 
13988   // The statements that form the synthesized function body.
13989   SmallVector<Stmt*, 8> Statements;
13990 
13991   // The parameter for the "other" object, which we are copying from.
13992   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13993   Qualifiers OtherQuals = Other->getType().getQualifiers();
13994   QualType OtherRefType = Other->getType();
13995   if (const LValueReferenceType *OtherRef
13996                                 = OtherRefType->getAs<LValueReferenceType>()) {
13997     OtherRefType = OtherRef->getPointeeType();
13998     OtherQuals = OtherRefType.getQualifiers();
13999   }
14000 
14001   // Our location for everything implicitly-generated.
14002   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14003                            ? CopyAssignOperator->getEndLoc()
14004                            : CopyAssignOperator->getLocation();
14005 
14006   // Builds a DeclRefExpr for the "other" object.
14007   RefBuilder OtherRef(Other, OtherRefType);
14008 
14009   // Builds the "this" pointer.
14010   ThisBuilder This;
14011 
14012   // Assign base classes.
14013   bool Invalid = false;
14014   for (auto &Base : ClassDecl->bases()) {
14015     // Form the assignment:
14016     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14017     QualType BaseType = Base.getType().getUnqualifiedType();
14018     if (!BaseType->isRecordType()) {
14019       Invalid = true;
14020       continue;
14021     }
14022 
14023     CXXCastPath BasePath;
14024     BasePath.push_back(&Base);
14025 
14026     // Construct the "from" expression, which is an implicit cast to the
14027     // appropriately-qualified base type.
14028     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14029                      VK_LValue, BasePath);
14030 
14031     // Dereference "this".
14032     DerefBuilder DerefThis(This);
14033     CastBuilder To(DerefThis,
14034                    Context.getQualifiedType(
14035                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14036                    VK_LValue, BasePath);
14037 
14038     // Build the copy.
14039     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14040                                             To, From,
14041                                             /*CopyingBaseSubobject=*/true,
14042                                             /*Copying=*/true);
14043     if (Copy.isInvalid()) {
14044       CopyAssignOperator->setInvalidDecl();
14045       return;
14046     }
14047 
14048     // Success! Record the copy.
14049     Statements.push_back(Copy.getAs<Expr>());
14050   }
14051 
14052   // Assign non-static members.
14053   for (auto *Field : ClassDecl->fields()) {
14054     // FIXME: We should form some kind of AST representation for the implied
14055     // memcpy in a union copy operation.
14056     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14057       continue;
14058 
14059     if (Field->isInvalidDecl()) {
14060       Invalid = true;
14061       continue;
14062     }
14063 
14064     // Check for members of reference type; we can't copy those.
14065     if (Field->getType()->isReferenceType()) {
14066       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14067         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14068       Diag(Field->getLocation(), diag::note_declared_at);
14069       Invalid = true;
14070       continue;
14071     }
14072 
14073     // Check for members of const-qualified, non-class type.
14074     QualType BaseType = Context.getBaseElementType(Field->getType());
14075     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14076       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14077         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14078       Diag(Field->getLocation(), diag::note_declared_at);
14079       Invalid = true;
14080       continue;
14081     }
14082 
14083     // Suppress assigning zero-width bitfields.
14084     if (Field->isZeroLengthBitField(Context))
14085       continue;
14086 
14087     QualType FieldType = Field->getType().getNonReferenceType();
14088     if (FieldType->isIncompleteArrayType()) {
14089       assert(ClassDecl->hasFlexibleArrayMember() &&
14090              "Incomplete array type is not valid");
14091       continue;
14092     }
14093 
14094     // Build references to the field in the object we're copying from and to.
14095     CXXScopeSpec SS; // Intentionally empty
14096     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14097                               LookupMemberName);
14098     MemberLookup.addDecl(Field);
14099     MemberLookup.resolveKind();
14100 
14101     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14102 
14103     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14104 
14105     // Build the copy of this field.
14106     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14107                                             To, From,
14108                                             /*CopyingBaseSubobject=*/false,
14109                                             /*Copying=*/true);
14110     if (Copy.isInvalid()) {
14111       CopyAssignOperator->setInvalidDecl();
14112       return;
14113     }
14114 
14115     // Success! Record the copy.
14116     Statements.push_back(Copy.getAs<Stmt>());
14117   }
14118 
14119   if (!Invalid) {
14120     // Add a "return *this;"
14121     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14122 
14123     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14124     if (Return.isInvalid())
14125       Invalid = true;
14126     else
14127       Statements.push_back(Return.getAs<Stmt>());
14128   }
14129 
14130   if (Invalid) {
14131     CopyAssignOperator->setInvalidDecl();
14132     return;
14133   }
14134 
14135   StmtResult Body;
14136   {
14137     CompoundScopeRAII CompoundScope(*this);
14138     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14139                              /*isStmtExpr=*/false);
14140     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14141   }
14142   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14143   CopyAssignOperator->markUsed(Context);
14144 
14145   if (ASTMutationListener *L = getASTMutationListener()) {
14146     L->CompletedImplicitDefinition(CopyAssignOperator);
14147   }
14148 }
14149 
14150 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14151   assert(ClassDecl->needsImplicitMoveAssignment());
14152 
14153   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14154   if (DSM.isAlreadyBeingDeclared())
14155     return nullptr;
14156 
14157   // Note: The following rules are largely analoguous to the move
14158   // constructor rules.
14159 
14160   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14161   LangAS AS = getDefaultCXXMethodAddrSpace();
14162   if (AS != LangAS::Default)
14163     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14164   QualType RetType = Context.getLValueReferenceType(ArgType);
14165   ArgType = Context.getRValueReferenceType(ArgType);
14166 
14167   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14168                                                      CXXMoveAssignment,
14169                                                      false);
14170 
14171   //   An implicitly-declared move assignment operator is an inline public
14172   //   member of its class.
14173   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14174   SourceLocation ClassLoc = ClassDecl->getLocation();
14175   DeclarationNameInfo NameInfo(Name, ClassLoc);
14176   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14177       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14178       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14179       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14180       SourceLocation());
14181   MoveAssignment->setAccess(AS_public);
14182   MoveAssignment->setDefaulted();
14183   MoveAssignment->setImplicit();
14184 
14185   if (getLangOpts().CUDA) {
14186     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14187                                             MoveAssignment,
14188                                             /* ConstRHS */ false,
14189                                             /* Diagnose */ false);
14190   }
14191 
14192   // Build an exception specification pointing back at this member.
14193   FunctionProtoType::ExtProtoInfo EPI =
14194       getImplicitMethodEPI(*this, MoveAssignment);
14195   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14196 
14197   // Add the parameter to the operator.
14198   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14199                                                ClassLoc, ClassLoc,
14200                                                /*Id=*/nullptr, ArgType,
14201                                                /*TInfo=*/nullptr, SC_None,
14202                                                nullptr);
14203   MoveAssignment->setParams(FromParam);
14204 
14205   MoveAssignment->setTrivial(
14206     ClassDecl->needsOverloadResolutionForMoveAssignment()
14207       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14208       : ClassDecl->hasTrivialMoveAssignment());
14209 
14210   // Note that we have added this copy-assignment operator.
14211   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14212 
14213   Scope *S = getScopeForContext(ClassDecl);
14214   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14215 
14216   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14217     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14218     SetDeclDeleted(MoveAssignment, ClassLoc);
14219   }
14220 
14221   if (S)
14222     PushOnScopeChains(MoveAssignment, S, false);
14223   ClassDecl->addDecl(MoveAssignment);
14224 
14225   return MoveAssignment;
14226 }
14227 
14228 /// Check if we're implicitly defining a move assignment operator for a class
14229 /// with virtual bases. Such a move assignment might move-assign the virtual
14230 /// base multiple times.
14231 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14232                                                SourceLocation CurrentLocation) {
14233   assert(!Class->isDependentContext() && "should not define dependent move");
14234 
14235   // Only a virtual base could get implicitly move-assigned multiple times.
14236   // Only a non-trivial move assignment can observe this. We only want to
14237   // diagnose if we implicitly define an assignment operator that assigns
14238   // two base classes, both of which move-assign the same virtual base.
14239   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14240       Class->getNumBases() < 2)
14241     return;
14242 
14243   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14244   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14245   VBaseMap VBases;
14246 
14247   for (auto &BI : Class->bases()) {
14248     Worklist.push_back(&BI);
14249     while (!Worklist.empty()) {
14250       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14251       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14252 
14253       // If the base has no non-trivial move assignment operators,
14254       // we don't care about moves from it.
14255       if (!Base->hasNonTrivialMoveAssignment())
14256         continue;
14257 
14258       // If there's nothing virtual here, skip it.
14259       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14260         continue;
14261 
14262       // If we're not actually going to call a move assignment for this base,
14263       // or the selected move assignment is trivial, skip it.
14264       Sema::SpecialMemberOverloadResult SMOR =
14265         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14266                               /*ConstArg*/false, /*VolatileArg*/false,
14267                               /*RValueThis*/true, /*ConstThis*/false,
14268                               /*VolatileThis*/false);
14269       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14270           !SMOR.getMethod()->isMoveAssignmentOperator())
14271         continue;
14272 
14273       if (BaseSpec->isVirtual()) {
14274         // We're going to move-assign this virtual base, and its move
14275         // assignment operator is not trivial. If this can happen for
14276         // multiple distinct direct bases of Class, diagnose it. (If it
14277         // only happens in one base, we'll diagnose it when synthesizing
14278         // that base class's move assignment operator.)
14279         CXXBaseSpecifier *&Existing =
14280             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14281                 .first->second;
14282         if (Existing && Existing != &BI) {
14283           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14284             << Class << Base;
14285           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14286               << (Base->getCanonicalDecl() ==
14287                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14288               << Base << Existing->getType() << Existing->getSourceRange();
14289           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14290               << (Base->getCanonicalDecl() ==
14291                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14292               << Base << BI.getType() << BaseSpec->getSourceRange();
14293 
14294           // Only diagnose each vbase once.
14295           Existing = nullptr;
14296         }
14297       } else {
14298         // Only walk over bases that have defaulted move assignment operators.
14299         // We assume that any user-provided move assignment operator handles
14300         // the multiple-moves-of-vbase case itself somehow.
14301         if (!SMOR.getMethod()->isDefaulted())
14302           continue;
14303 
14304         // We're going to move the base classes of Base. Add them to the list.
14305         for (auto &BI : Base->bases())
14306           Worklist.push_back(&BI);
14307       }
14308     }
14309   }
14310 }
14311 
14312 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14313                                         CXXMethodDecl *MoveAssignOperator) {
14314   assert((MoveAssignOperator->isDefaulted() &&
14315           MoveAssignOperator->isOverloadedOperator() &&
14316           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14317           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14318           !MoveAssignOperator->isDeleted()) &&
14319          "DefineImplicitMoveAssignment called for wrong function");
14320   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14321     return;
14322 
14323   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14324   if (ClassDecl->isInvalidDecl()) {
14325     MoveAssignOperator->setInvalidDecl();
14326     return;
14327   }
14328 
14329   // C++0x [class.copy]p28:
14330   //   The implicitly-defined or move assignment operator for a non-union class
14331   //   X performs memberwise move assignment of its subobjects. The direct base
14332   //   classes of X are assigned first, in the order of their declaration in the
14333   //   base-specifier-list, and then the immediate non-static data members of X
14334   //   are assigned, in the order in which they were declared in the class
14335   //   definition.
14336 
14337   // Issue a warning if our implicit move assignment operator will move
14338   // from a virtual base more than once.
14339   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14340 
14341   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14342 
14343   // The exception specification is needed because we are defining the
14344   // function.
14345   ResolveExceptionSpec(CurrentLocation,
14346                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14347 
14348   // Add a context note for diagnostics produced after this point.
14349   Scope.addContextNote(CurrentLocation);
14350 
14351   // The statements that form the synthesized function body.
14352   SmallVector<Stmt*, 8> Statements;
14353 
14354   // The parameter for the "other" object, which we are move from.
14355   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14356   QualType OtherRefType =
14357       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14358 
14359   // Our location for everything implicitly-generated.
14360   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14361                            ? MoveAssignOperator->getEndLoc()
14362                            : MoveAssignOperator->getLocation();
14363 
14364   // Builds a reference to the "other" object.
14365   RefBuilder OtherRef(Other, OtherRefType);
14366   // Cast to rvalue.
14367   MoveCastBuilder MoveOther(OtherRef);
14368 
14369   // Builds the "this" pointer.
14370   ThisBuilder This;
14371 
14372   // Assign base classes.
14373   bool Invalid = false;
14374   for (auto &Base : ClassDecl->bases()) {
14375     // C++11 [class.copy]p28:
14376     //   It is unspecified whether subobjects representing virtual base classes
14377     //   are assigned more than once by the implicitly-defined copy assignment
14378     //   operator.
14379     // FIXME: Do not assign to a vbase that will be assigned by some other base
14380     // class. For a move-assignment, this can result in the vbase being moved
14381     // multiple times.
14382 
14383     // Form the assignment:
14384     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14385     QualType BaseType = Base.getType().getUnqualifiedType();
14386     if (!BaseType->isRecordType()) {
14387       Invalid = true;
14388       continue;
14389     }
14390 
14391     CXXCastPath BasePath;
14392     BasePath.push_back(&Base);
14393 
14394     // Construct the "from" expression, which is an implicit cast to the
14395     // appropriately-qualified base type.
14396     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14397 
14398     // Dereference "this".
14399     DerefBuilder DerefThis(This);
14400 
14401     // Implicitly cast "this" to the appropriately-qualified base type.
14402     CastBuilder To(DerefThis,
14403                    Context.getQualifiedType(
14404                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14405                    VK_LValue, BasePath);
14406 
14407     // Build the move.
14408     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14409                                             To, From,
14410                                             /*CopyingBaseSubobject=*/true,
14411                                             /*Copying=*/false);
14412     if (Move.isInvalid()) {
14413       MoveAssignOperator->setInvalidDecl();
14414       return;
14415     }
14416 
14417     // Success! Record the move.
14418     Statements.push_back(Move.getAs<Expr>());
14419   }
14420 
14421   // Assign non-static members.
14422   for (auto *Field : ClassDecl->fields()) {
14423     // FIXME: We should form some kind of AST representation for the implied
14424     // memcpy in a union copy operation.
14425     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14426       continue;
14427 
14428     if (Field->isInvalidDecl()) {
14429       Invalid = true;
14430       continue;
14431     }
14432 
14433     // Check for members of reference type; we can't move those.
14434     if (Field->getType()->isReferenceType()) {
14435       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14436         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14437       Diag(Field->getLocation(), diag::note_declared_at);
14438       Invalid = true;
14439       continue;
14440     }
14441 
14442     // Check for members of const-qualified, non-class type.
14443     QualType BaseType = Context.getBaseElementType(Field->getType());
14444     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14445       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14446         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14447       Diag(Field->getLocation(), diag::note_declared_at);
14448       Invalid = true;
14449       continue;
14450     }
14451 
14452     // Suppress assigning zero-width bitfields.
14453     if (Field->isZeroLengthBitField(Context))
14454       continue;
14455 
14456     QualType FieldType = Field->getType().getNonReferenceType();
14457     if (FieldType->isIncompleteArrayType()) {
14458       assert(ClassDecl->hasFlexibleArrayMember() &&
14459              "Incomplete array type is not valid");
14460       continue;
14461     }
14462 
14463     // Build references to the field in the object we're copying from and to.
14464     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14465                               LookupMemberName);
14466     MemberLookup.addDecl(Field);
14467     MemberLookup.resolveKind();
14468     MemberBuilder From(MoveOther, OtherRefType,
14469                        /*IsArrow=*/false, MemberLookup);
14470     MemberBuilder To(This, getCurrentThisType(),
14471                      /*IsArrow=*/true, MemberLookup);
14472 
14473     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14474         "Member reference with rvalue base must be rvalue except for reference "
14475         "members, which aren't allowed for move assignment.");
14476 
14477     // Build the move of this field.
14478     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14479                                             To, From,
14480                                             /*CopyingBaseSubobject=*/false,
14481                                             /*Copying=*/false);
14482     if (Move.isInvalid()) {
14483       MoveAssignOperator->setInvalidDecl();
14484       return;
14485     }
14486 
14487     // Success! Record the copy.
14488     Statements.push_back(Move.getAs<Stmt>());
14489   }
14490 
14491   if (!Invalid) {
14492     // Add a "return *this;"
14493     ExprResult ThisObj =
14494         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14495 
14496     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14497     if (Return.isInvalid())
14498       Invalid = true;
14499     else
14500       Statements.push_back(Return.getAs<Stmt>());
14501   }
14502 
14503   if (Invalid) {
14504     MoveAssignOperator->setInvalidDecl();
14505     return;
14506   }
14507 
14508   StmtResult Body;
14509   {
14510     CompoundScopeRAII CompoundScope(*this);
14511     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14512                              /*isStmtExpr=*/false);
14513     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14514   }
14515   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14516   MoveAssignOperator->markUsed(Context);
14517 
14518   if (ASTMutationListener *L = getASTMutationListener()) {
14519     L->CompletedImplicitDefinition(MoveAssignOperator);
14520   }
14521 }
14522 
14523 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14524                                                     CXXRecordDecl *ClassDecl) {
14525   // C++ [class.copy]p4:
14526   //   If the class definition does not explicitly declare a copy
14527   //   constructor, one is declared implicitly.
14528   assert(ClassDecl->needsImplicitCopyConstructor());
14529 
14530   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14531   if (DSM.isAlreadyBeingDeclared())
14532     return nullptr;
14533 
14534   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14535   QualType ArgType = ClassType;
14536   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14537   if (Const)
14538     ArgType = ArgType.withConst();
14539 
14540   LangAS AS = getDefaultCXXMethodAddrSpace();
14541   if (AS != LangAS::Default)
14542     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14543 
14544   ArgType = Context.getLValueReferenceType(ArgType);
14545 
14546   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14547                                                      CXXCopyConstructor,
14548                                                      Const);
14549 
14550   DeclarationName Name
14551     = Context.DeclarationNames.getCXXConstructorName(
14552                                            Context.getCanonicalType(ClassType));
14553   SourceLocation ClassLoc = ClassDecl->getLocation();
14554   DeclarationNameInfo NameInfo(Name, ClassLoc);
14555 
14556   //   An implicitly-declared copy constructor is an inline public
14557   //   member of its class.
14558   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14559       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14560       ExplicitSpecifier(),
14561       /*isInline=*/true,
14562       /*isImplicitlyDeclared=*/true,
14563       Constexpr ? CSK_constexpr : CSK_unspecified);
14564   CopyConstructor->setAccess(AS_public);
14565   CopyConstructor->setDefaulted();
14566 
14567   if (getLangOpts().CUDA) {
14568     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14569                                             CopyConstructor,
14570                                             /* ConstRHS */ Const,
14571                                             /* Diagnose */ false);
14572   }
14573 
14574   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14575 
14576   // Add the parameter to the constructor.
14577   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14578                                                ClassLoc, ClassLoc,
14579                                                /*IdentifierInfo=*/nullptr,
14580                                                ArgType, /*TInfo=*/nullptr,
14581                                                SC_None, nullptr);
14582   CopyConstructor->setParams(FromParam);
14583 
14584   CopyConstructor->setTrivial(
14585       ClassDecl->needsOverloadResolutionForCopyConstructor()
14586           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14587           : ClassDecl->hasTrivialCopyConstructor());
14588 
14589   CopyConstructor->setTrivialForCall(
14590       ClassDecl->hasAttr<TrivialABIAttr>() ||
14591       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14592            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14593              TAH_ConsiderTrivialABI)
14594            : ClassDecl->hasTrivialCopyConstructorForCall()));
14595 
14596   // Note that we have declared this constructor.
14597   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14598 
14599   Scope *S = getScopeForContext(ClassDecl);
14600   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14601 
14602   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14603     ClassDecl->setImplicitCopyConstructorIsDeleted();
14604     SetDeclDeleted(CopyConstructor, ClassLoc);
14605   }
14606 
14607   if (S)
14608     PushOnScopeChains(CopyConstructor, S, false);
14609   ClassDecl->addDecl(CopyConstructor);
14610 
14611   return CopyConstructor;
14612 }
14613 
14614 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14615                                          CXXConstructorDecl *CopyConstructor) {
14616   assert((CopyConstructor->isDefaulted() &&
14617           CopyConstructor->isCopyConstructor() &&
14618           !CopyConstructor->doesThisDeclarationHaveABody() &&
14619           !CopyConstructor->isDeleted()) &&
14620          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14621   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14622     return;
14623 
14624   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14625   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14626 
14627   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14628 
14629   // The exception specification is needed because we are defining the
14630   // function.
14631   ResolveExceptionSpec(CurrentLocation,
14632                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14633   MarkVTableUsed(CurrentLocation, ClassDecl);
14634 
14635   // Add a context note for diagnostics produced after this point.
14636   Scope.addContextNote(CurrentLocation);
14637 
14638   // C++11 [class.copy]p7:
14639   //   The [definition of an implicitly declared copy constructor] is
14640   //   deprecated if the class has a user-declared copy assignment operator
14641   //   or a user-declared destructor.
14642   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14643     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14644 
14645   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14646     CopyConstructor->setInvalidDecl();
14647   }  else {
14648     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14649                              ? CopyConstructor->getEndLoc()
14650                              : CopyConstructor->getLocation();
14651     Sema::CompoundScopeRAII CompoundScope(*this);
14652     CopyConstructor->setBody(
14653         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14654     CopyConstructor->markUsed(Context);
14655   }
14656 
14657   if (ASTMutationListener *L = getASTMutationListener()) {
14658     L->CompletedImplicitDefinition(CopyConstructor);
14659   }
14660 }
14661 
14662 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14663                                                     CXXRecordDecl *ClassDecl) {
14664   assert(ClassDecl->needsImplicitMoveConstructor());
14665 
14666   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14667   if (DSM.isAlreadyBeingDeclared())
14668     return nullptr;
14669 
14670   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14671 
14672   QualType ArgType = ClassType;
14673   LangAS AS = getDefaultCXXMethodAddrSpace();
14674   if (AS != LangAS::Default)
14675     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14676   ArgType = Context.getRValueReferenceType(ArgType);
14677 
14678   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14679                                                      CXXMoveConstructor,
14680                                                      false);
14681 
14682   DeclarationName Name
14683     = Context.DeclarationNames.getCXXConstructorName(
14684                                            Context.getCanonicalType(ClassType));
14685   SourceLocation ClassLoc = ClassDecl->getLocation();
14686   DeclarationNameInfo NameInfo(Name, ClassLoc);
14687 
14688   // C++11 [class.copy]p11:
14689   //   An implicitly-declared copy/move constructor is an inline public
14690   //   member of its class.
14691   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14692       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14693       ExplicitSpecifier(),
14694       /*isInline=*/true,
14695       /*isImplicitlyDeclared=*/true,
14696       Constexpr ? CSK_constexpr : CSK_unspecified);
14697   MoveConstructor->setAccess(AS_public);
14698   MoveConstructor->setDefaulted();
14699 
14700   if (getLangOpts().CUDA) {
14701     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14702                                             MoveConstructor,
14703                                             /* ConstRHS */ false,
14704                                             /* Diagnose */ false);
14705   }
14706 
14707   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14708 
14709   // Add the parameter to the constructor.
14710   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14711                                                ClassLoc, ClassLoc,
14712                                                /*IdentifierInfo=*/nullptr,
14713                                                ArgType, /*TInfo=*/nullptr,
14714                                                SC_None, nullptr);
14715   MoveConstructor->setParams(FromParam);
14716 
14717   MoveConstructor->setTrivial(
14718       ClassDecl->needsOverloadResolutionForMoveConstructor()
14719           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14720           : ClassDecl->hasTrivialMoveConstructor());
14721 
14722   MoveConstructor->setTrivialForCall(
14723       ClassDecl->hasAttr<TrivialABIAttr>() ||
14724       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14725            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14726                                     TAH_ConsiderTrivialABI)
14727            : ClassDecl->hasTrivialMoveConstructorForCall()));
14728 
14729   // Note that we have declared this constructor.
14730   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14731 
14732   Scope *S = getScopeForContext(ClassDecl);
14733   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14734 
14735   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14736     ClassDecl->setImplicitMoveConstructorIsDeleted();
14737     SetDeclDeleted(MoveConstructor, ClassLoc);
14738   }
14739 
14740   if (S)
14741     PushOnScopeChains(MoveConstructor, S, false);
14742   ClassDecl->addDecl(MoveConstructor);
14743 
14744   return MoveConstructor;
14745 }
14746 
14747 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14748                                          CXXConstructorDecl *MoveConstructor) {
14749   assert((MoveConstructor->isDefaulted() &&
14750           MoveConstructor->isMoveConstructor() &&
14751           !MoveConstructor->doesThisDeclarationHaveABody() &&
14752           !MoveConstructor->isDeleted()) &&
14753          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14754   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14755     return;
14756 
14757   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14758   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14759 
14760   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14761 
14762   // The exception specification is needed because we are defining the
14763   // function.
14764   ResolveExceptionSpec(CurrentLocation,
14765                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14766   MarkVTableUsed(CurrentLocation, ClassDecl);
14767 
14768   // Add a context note for diagnostics produced after this point.
14769   Scope.addContextNote(CurrentLocation);
14770 
14771   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14772     MoveConstructor->setInvalidDecl();
14773   } else {
14774     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14775                              ? MoveConstructor->getEndLoc()
14776                              : MoveConstructor->getLocation();
14777     Sema::CompoundScopeRAII CompoundScope(*this);
14778     MoveConstructor->setBody(ActOnCompoundStmt(
14779         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14780     MoveConstructor->markUsed(Context);
14781   }
14782 
14783   if (ASTMutationListener *L = getASTMutationListener()) {
14784     L->CompletedImplicitDefinition(MoveConstructor);
14785   }
14786 }
14787 
14788 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14789   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14790 }
14791 
14792 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14793                             SourceLocation CurrentLocation,
14794                             CXXConversionDecl *Conv) {
14795   SynthesizedFunctionScope Scope(*this, Conv);
14796   assert(!Conv->getReturnType()->isUndeducedType());
14797 
14798   CXXRecordDecl *Lambda = Conv->getParent();
14799   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14800   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14801 
14802   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14803     CallOp = InstantiateFunctionDeclaration(
14804         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14805     if (!CallOp)
14806       return;
14807 
14808     Invoker = InstantiateFunctionDeclaration(
14809         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14810     if (!Invoker)
14811       return;
14812   }
14813 
14814   if (CallOp->isInvalidDecl())
14815     return;
14816 
14817   // Mark the call operator referenced (and add to pending instantiations
14818   // if necessary).
14819   // For both the conversion and static-invoker template specializations
14820   // we construct their body's in this function, so no need to add them
14821   // to the PendingInstantiations.
14822   MarkFunctionReferenced(CurrentLocation, CallOp);
14823 
14824   // Fill in the __invoke function with a dummy implementation. IR generation
14825   // will fill in the actual details. Update its type in case it contained
14826   // an 'auto'.
14827   Invoker->markUsed(Context);
14828   Invoker->setReferenced();
14829   Invoker->setType(Conv->getReturnType()->getPointeeType());
14830   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14831 
14832   // Construct the body of the conversion function { return __invoke; }.
14833   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14834                                        VK_LValue, Conv->getLocation());
14835   assert(FunctionRef && "Can't refer to __invoke function?");
14836   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14837   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14838                                      Conv->getLocation()));
14839   Conv->markUsed(Context);
14840   Conv->setReferenced();
14841 
14842   if (ASTMutationListener *L = getASTMutationListener()) {
14843     L->CompletedImplicitDefinition(Conv);
14844     L->CompletedImplicitDefinition(Invoker);
14845   }
14846 }
14847 
14848 
14849 
14850 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14851        SourceLocation CurrentLocation,
14852        CXXConversionDecl *Conv)
14853 {
14854   assert(!Conv->getParent()->isGenericLambda());
14855 
14856   SynthesizedFunctionScope Scope(*this, Conv);
14857 
14858   // Copy-initialize the lambda object as needed to capture it.
14859   Expr *This = ActOnCXXThis(CurrentLocation).get();
14860   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14861 
14862   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14863                                                         Conv->getLocation(),
14864                                                         Conv, DerefThis);
14865 
14866   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14867   // behavior.  Note that only the general conversion function does this
14868   // (since it's unusable otherwise); in the case where we inline the
14869   // block literal, it has block literal lifetime semantics.
14870   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14871     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14872                                           CK_CopyAndAutoreleaseBlockObject,
14873                                           BuildBlock.get(), nullptr, VK_RValue);
14874 
14875   if (BuildBlock.isInvalid()) {
14876     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14877     Conv->setInvalidDecl();
14878     return;
14879   }
14880 
14881   // Create the return statement that returns the block from the conversion
14882   // function.
14883   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14884   if (Return.isInvalid()) {
14885     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14886     Conv->setInvalidDecl();
14887     return;
14888   }
14889 
14890   // Set the body of the conversion function.
14891   Stmt *ReturnS = Return.get();
14892   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14893                                      Conv->getLocation()));
14894   Conv->markUsed(Context);
14895 
14896   // We're done; notify the mutation listener, if any.
14897   if (ASTMutationListener *L = getASTMutationListener()) {
14898     L->CompletedImplicitDefinition(Conv);
14899   }
14900 }
14901 
14902 /// Determine whether the given list arguments contains exactly one
14903 /// "real" (non-default) argument.
14904 static bool hasOneRealArgument(MultiExprArg Args) {
14905   switch (Args.size()) {
14906   case 0:
14907     return false;
14908 
14909   default:
14910     if (!Args[1]->isDefaultArgument())
14911       return false;
14912 
14913     LLVM_FALLTHROUGH;
14914   case 1:
14915     return !Args[0]->isDefaultArgument();
14916   }
14917 
14918   return false;
14919 }
14920 
14921 ExprResult
14922 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14923                             NamedDecl *FoundDecl,
14924                             CXXConstructorDecl *Constructor,
14925                             MultiExprArg ExprArgs,
14926                             bool HadMultipleCandidates,
14927                             bool IsListInitialization,
14928                             bool IsStdInitListInitialization,
14929                             bool RequiresZeroInit,
14930                             unsigned ConstructKind,
14931                             SourceRange ParenRange) {
14932   bool Elidable = false;
14933 
14934   // C++0x [class.copy]p34:
14935   //   When certain criteria are met, an implementation is allowed to
14936   //   omit the copy/move construction of a class object, even if the
14937   //   copy/move constructor and/or destructor for the object have
14938   //   side effects. [...]
14939   //     - when a temporary class object that has not been bound to a
14940   //       reference (12.2) would be copied/moved to a class object
14941   //       with the same cv-unqualified type, the copy/move operation
14942   //       can be omitted by constructing the temporary object
14943   //       directly into the target of the omitted copy/move
14944   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14945       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14946     Expr *SubExpr = ExprArgs[0];
14947     Elidable = SubExpr->isTemporaryObject(
14948         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14949   }
14950 
14951   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14952                                FoundDecl, Constructor,
14953                                Elidable, ExprArgs, HadMultipleCandidates,
14954                                IsListInitialization,
14955                                IsStdInitListInitialization, RequiresZeroInit,
14956                                ConstructKind, ParenRange);
14957 }
14958 
14959 ExprResult
14960 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14961                             NamedDecl *FoundDecl,
14962                             CXXConstructorDecl *Constructor,
14963                             bool Elidable,
14964                             MultiExprArg ExprArgs,
14965                             bool HadMultipleCandidates,
14966                             bool IsListInitialization,
14967                             bool IsStdInitListInitialization,
14968                             bool RequiresZeroInit,
14969                             unsigned ConstructKind,
14970                             SourceRange ParenRange) {
14971   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14972     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14973     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14974       return ExprError();
14975   }
14976 
14977   return BuildCXXConstructExpr(
14978       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14979       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14980       RequiresZeroInit, ConstructKind, ParenRange);
14981 }
14982 
14983 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14984 /// including handling of its default argument expressions.
14985 ExprResult
14986 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14987                             CXXConstructorDecl *Constructor,
14988                             bool Elidable,
14989                             MultiExprArg ExprArgs,
14990                             bool HadMultipleCandidates,
14991                             bool IsListInitialization,
14992                             bool IsStdInitListInitialization,
14993                             bool RequiresZeroInit,
14994                             unsigned ConstructKind,
14995                             SourceRange ParenRange) {
14996   assert(declaresSameEntity(
14997              Constructor->getParent(),
14998              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14999          "given constructor for wrong type");
15000   MarkFunctionReferenced(ConstructLoc, Constructor);
15001   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15002     return ExprError();
15003   if (getLangOpts().SYCLIsDevice &&
15004       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15005     return ExprError();
15006 
15007   return CheckForImmediateInvocation(
15008       CXXConstructExpr::Create(
15009           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15010           HadMultipleCandidates, IsListInitialization,
15011           IsStdInitListInitialization, RequiresZeroInit,
15012           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15013           ParenRange),
15014       Constructor);
15015 }
15016 
15017 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15018   assert(Field->hasInClassInitializer());
15019 
15020   // If we already have the in-class initializer nothing needs to be done.
15021   if (Field->getInClassInitializer())
15022     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15023 
15024   // If we might have already tried and failed to instantiate, don't try again.
15025   if (Field->isInvalidDecl())
15026     return ExprError();
15027 
15028   // Maybe we haven't instantiated the in-class initializer. Go check the
15029   // pattern FieldDecl to see if it has one.
15030   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15031 
15032   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15033     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15034     DeclContext::lookup_result Lookup =
15035         ClassPattern->lookup(Field->getDeclName());
15036 
15037     // Lookup can return at most two results: the pattern for the field, or the
15038     // injected class name of the parent record. No other member can have the
15039     // same name as the field.
15040     // In modules mode, lookup can return multiple results (coming from
15041     // different modules).
15042     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15043            "more than two lookup results for field name");
15044     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15045     if (!Pattern) {
15046       assert(isa<CXXRecordDecl>(Lookup[0]) &&
15047              "cannot have other non-field member with same name");
15048       for (auto L : Lookup)
15049         if (isa<FieldDecl>(L)) {
15050           Pattern = cast<FieldDecl>(L);
15051           break;
15052         }
15053       assert(Pattern && "We must have set the Pattern!");
15054     }
15055 
15056     if (!Pattern->hasInClassInitializer() ||
15057         InstantiateInClassInitializer(Loc, Field, Pattern,
15058                                       getTemplateInstantiationArgs(Field))) {
15059       // Don't diagnose this again.
15060       Field->setInvalidDecl();
15061       return ExprError();
15062     }
15063     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15064   }
15065 
15066   // DR1351:
15067   //   If the brace-or-equal-initializer of a non-static data member
15068   //   invokes a defaulted default constructor of its class or of an
15069   //   enclosing class in a potentially evaluated subexpression, the
15070   //   program is ill-formed.
15071   //
15072   // This resolution is unworkable: the exception specification of the
15073   // default constructor can be needed in an unevaluated context, in
15074   // particular, in the operand of a noexcept-expression, and we can be
15075   // unable to compute an exception specification for an enclosed class.
15076   //
15077   // Any attempt to resolve the exception specification of a defaulted default
15078   // constructor before the initializer is lexically complete will ultimately
15079   // come here at which point we can diagnose it.
15080   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15081   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
15082       << OutermostClass << Field;
15083   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
15084   // Recover by marking the field invalid, unless we're in a SFINAE context.
15085   if (!isSFINAEContext())
15086     Field->setInvalidDecl();
15087   return ExprError();
15088 }
15089 
15090 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15091   if (VD->isInvalidDecl()) return;
15092   // If initializing the variable failed, don't also diagnose problems with
15093   // the desctructor, they're likely related.
15094   if (VD->getInit() && VD->getInit()->containsErrors())
15095     return;
15096 
15097   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15098   if (ClassDecl->isInvalidDecl()) return;
15099   if (ClassDecl->hasIrrelevantDestructor()) return;
15100   if (ClassDecl->isDependentContext()) return;
15101 
15102   if (VD->isNoDestroy(getASTContext()))
15103     return;
15104 
15105   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15106 
15107   // If this is an array, we'll require the destructor during initialization, so
15108   // we can skip over this. We still want to emit exit-time destructor warnings
15109   // though.
15110   if (!VD->getType()->isArrayType()) {
15111     MarkFunctionReferenced(VD->getLocation(), Destructor);
15112     CheckDestructorAccess(VD->getLocation(), Destructor,
15113                           PDiag(diag::err_access_dtor_var)
15114                               << VD->getDeclName() << VD->getType());
15115     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15116   }
15117 
15118   if (Destructor->isTrivial()) return;
15119 
15120   // If the destructor is constexpr, check whether the variable has constant
15121   // destruction now.
15122   if (Destructor->isConstexpr()) {
15123     bool HasConstantInit = false;
15124     if (VD->getInit() && !VD->getInit()->isValueDependent())
15125       HasConstantInit = VD->evaluateValue();
15126     SmallVector<PartialDiagnosticAt, 8> Notes;
15127     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15128         HasConstantInit) {
15129       Diag(VD->getLocation(),
15130            diag::err_constexpr_var_requires_const_destruction) << VD;
15131       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15132         Diag(Notes[I].first, Notes[I].second);
15133     }
15134   }
15135 
15136   if (!VD->hasGlobalStorage()) return;
15137 
15138   // Emit warning for non-trivial dtor in global scope (a real global,
15139   // class-static, function-static).
15140   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15141 
15142   // TODO: this should be re-enabled for static locals by !CXAAtExit
15143   if (!VD->isStaticLocal())
15144     Diag(VD->getLocation(), diag::warn_global_destructor);
15145 }
15146 
15147 /// Given a constructor and the set of arguments provided for the
15148 /// constructor, convert the arguments and add any required default arguments
15149 /// to form a proper call to this constructor.
15150 ///
15151 /// \returns true if an error occurred, false otherwise.
15152 bool
15153 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15154                               MultiExprArg ArgsPtr,
15155                               SourceLocation Loc,
15156                               SmallVectorImpl<Expr*> &ConvertedArgs,
15157                               bool AllowExplicit,
15158                               bool IsListInitialization) {
15159   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15160   unsigned NumArgs = ArgsPtr.size();
15161   Expr **Args = ArgsPtr.data();
15162 
15163   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15164   unsigned NumParams = Proto->getNumParams();
15165 
15166   // If too few arguments are available, we'll fill in the rest with defaults.
15167   if (NumArgs < NumParams)
15168     ConvertedArgs.reserve(NumParams);
15169   else
15170     ConvertedArgs.reserve(NumArgs);
15171 
15172   VariadicCallType CallType =
15173     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15174   SmallVector<Expr *, 8> AllArgs;
15175   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15176                                         Proto, 0,
15177                                         llvm::makeArrayRef(Args, NumArgs),
15178                                         AllArgs,
15179                                         CallType, AllowExplicit,
15180                                         IsListInitialization);
15181   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15182 
15183   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15184 
15185   CheckConstructorCall(Constructor,
15186                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15187                        Proto, Loc);
15188 
15189   return Invalid;
15190 }
15191 
15192 static inline bool
15193 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15194                                        const FunctionDecl *FnDecl) {
15195   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15196   if (isa<NamespaceDecl>(DC)) {
15197     return SemaRef.Diag(FnDecl->getLocation(),
15198                         diag::err_operator_new_delete_declared_in_namespace)
15199       << FnDecl->getDeclName();
15200   }
15201 
15202   if (isa<TranslationUnitDecl>(DC) &&
15203       FnDecl->getStorageClass() == SC_Static) {
15204     return SemaRef.Diag(FnDecl->getLocation(),
15205                         diag::err_operator_new_delete_declared_static)
15206       << FnDecl->getDeclName();
15207   }
15208 
15209   return false;
15210 }
15211 
15212 static QualType
15213 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15214   QualType QTy = PtrTy->getPointeeType();
15215   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15216   return SemaRef.Context.getPointerType(QTy);
15217 }
15218 
15219 static inline bool
15220 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15221                             CanQualType ExpectedResultType,
15222                             CanQualType ExpectedFirstParamType,
15223                             unsigned DependentParamTypeDiag,
15224                             unsigned InvalidParamTypeDiag) {
15225   QualType ResultType =
15226       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15227 
15228   // The operator is valid on any address space for OpenCL.
15229   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15230     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15231       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15232     }
15233   }
15234 
15235   // Check that the result type is what we expect.
15236   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15237     // Reject even if the type is dependent; an operator delete function is
15238     // required to have a non-dependent result type.
15239     return SemaRef.Diag(
15240                FnDecl->getLocation(),
15241                ResultType->isDependentType()
15242                    ? diag::err_operator_new_delete_dependent_result_type
15243                    : diag::err_operator_new_delete_invalid_result_type)
15244            << FnDecl->getDeclName() << ExpectedResultType;
15245   }
15246 
15247   // A function template must have at least 2 parameters.
15248   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15249     return SemaRef.Diag(FnDecl->getLocation(),
15250                       diag::err_operator_new_delete_template_too_few_parameters)
15251         << FnDecl->getDeclName();
15252 
15253   // The function decl must have at least 1 parameter.
15254   if (FnDecl->getNumParams() == 0)
15255     return SemaRef.Diag(FnDecl->getLocation(),
15256                         diag::err_operator_new_delete_too_few_parameters)
15257       << FnDecl->getDeclName();
15258 
15259   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15260   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15261     // The operator is valid on any address space for OpenCL.
15262     if (auto *PtrTy =
15263             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15264       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15265     }
15266   }
15267 
15268   // Check that the first parameter type is what we expect.
15269   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15270       ExpectedFirstParamType) {
15271     // The first parameter type is not allowed to be dependent. As a tentative
15272     // DR resolution, we allow a dependent parameter type if it is the right
15273     // type anyway, to allow destroying operator delete in class templates.
15274     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15275                                                    ? DependentParamTypeDiag
15276                                                    : InvalidParamTypeDiag)
15277            << FnDecl->getDeclName() << ExpectedFirstParamType;
15278   }
15279 
15280   return false;
15281 }
15282 
15283 static bool
15284 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15285   // C++ [basic.stc.dynamic.allocation]p1:
15286   //   A program is ill-formed if an allocation function is declared in a
15287   //   namespace scope other than global scope or declared static in global
15288   //   scope.
15289   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15290     return true;
15291 
15292   CanQualType SizeTy =
15293     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15294 
15295   // C++ [basic.stc.dynamic.allocation]p1:
15296   //  The return type shall be void*. The first parameter shall have type
15297   //  std::size_t.
15298   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15299                                   SizeTy,
15300                                   diag::err_operator_new_dependent_param_type,
15301                                   diag::err_operator_new_param_type))
15302     return true;
15303 
15304   // C++ [basic.stc.dynamic.allocation]p1:
15305   //  The first parameter shall not have an associated default argument.
15306   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15307     return SemaRef.Diag(FnDecl->getLocation(),
15308                         diag::err_operator_new_default_arg)
15309       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15310 
15311   return false;
15312 }
15313 
15314 static bool
15315 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15316   // C++ [basic.stc.dynamic.deallocation]p1:
15317   //   A program is ill-formed if deallocation functions are declared in a
15318   //   namespace scope other than global scope or declared static in global
15319   //   scope.
15320   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15321     return true;
15322 
15323   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15324 
15325   // C++ P0722:
15326   //   Within a class C, the first parameter of a destroying operator delete
15327   //   shall be of type C *. The first parameter of any other deallocation
15328   //   function shall be of type void *.
15329   CanQualType ExpectedFirstParamType =
15330       MD && MD->isDestroyingOperatorDelete()
15331           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15332                 SemaRef.Context.getRecordType(MD->getParent())))
15333           : SemaRef.Context.VoidPtrTy;
15334 
15335   // C++ [basic.stc.dynamic.deallocation]p2:
15336   //   Each deallocation function shall return void
15337   if (CheckOperatorNewDeleteTypes(
15338           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15339           diag::err_operator_delete_dependent_param_type,
15340           diag::err_operator_delete_param_type))
15341     return true;
15342 
15343   // C++ P0722:
15344   //   A destroying operator delete shall be a usual deallocation function.
15345   if (MD && !MD->getParent()->isDependentContext() &&
15346       MD->isDestroyingOperatorDelete() &&
15347       !SemaRef.isUsualDeallocationFunction(MD)) {
15348     SemaRef.Diag(MD->getLocation(),
15349                  diag::err_destroying_operator_delete_not_usual);
15350     return true;
15351   }
15352 
15353   return false;
15354 }
15355 
15356 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15357 /// of this overloaded operator is well-formed. If so, returns false;
15358 /// otherwise, emits appropriate diagnostics and returns true.
15359 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15360   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15361          "Expected an overloaded operator declaration");
15362 
15363   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15364 
15365   // C++ [over.oper]p5:
15366   //   The allocation and deallocation functions, operator new,
15367   //   operator new[], operator delete and operator delete[], are
15368   //   described completely in 3.7.3. The attributes and restrictions
15369   //   found in the rest of this subclause do not apply to them unless
15370   //   explicitly stated in 3.7.3.
15371   if (Op == OO_Delete || Op == OO_Array_Delete)
15372     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15373 
15374   if (Op == OO_New || Op == OO_Array_New)
15375     return CheckOperatorNewDeclaration(*this, FnDecl);
15376 
15377   // C++ [over.oper]p6:
15378   //   An operator function shall either be a non-static member
15379   //   function or be a non-member function and have at least one
15380   //   parameter whose type is a class, a reference to a class, an
15381   //   enumeration, or a reference to an enumeration.
15382   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15383     if (MethodDecl->isStatic())
15384       return Diag(FnDecl->getLocation(),
15385                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15386   } else {
15387     bool ClassOrEnumParam = false;
15388     for (auto Param : FnDecl->parameters()) {
15389       QualType ParamType = Param->getType().getNonReferenceType();
15390       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15391           ParamType->isEnumeralType()) {
15392         ClassOrEnumParam = true;
15393         break;
15394       }
15395     }
15396 
15397     if (!ClassOrEnumParam)
15398       return Diag(FnDecl->getLocation(),
15399                   diag::err_operator_overload_needs_class_or_enum)
15400         << FnDecl->getDeclName();
15401   }
15402 
15403   // C++ [over.oper]p8:
15404   //   An operator function cannot have default arguments (8.3.6),
15405   //   except where explicitly stated below.
15406   //
15407   // Only the function-call operator allows default arguments
15408   // (C++ [over.call]p1).
15409   if (Op != OO_Call) {
15410     for (auto Param : FnDecl->parameters()) {
15411       if (Param->hasDefaultArg())
15412         return Diag(Param->getLocation(),
15413                     diag::err_operator_overload_default_arg)
15414           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15415     }
15416   }
15417 
15418   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15419     { false, false, false }
15420 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15421     , { Unary, Binary, MemberOnly }
15422 #include "clang/Basic/OperatorKinds.def"
15423   };
15424 
15425   bool CanBeUnaryOperator = OperatorUses[Op][0];
15426   bool CanBeBinaryOperator = OperatorUses[Op][1];
15427   bool MustBeMemberOperator = OperatorUses[Op][2];
15428 
15429   // C++ [over.oper]p8:
15430   //   [...] Operator functions cannot have more or fewer parameters
15431   //   than the number required for the corresponding operator, as
15432   //   described in the rest of this subclause.
15433   unsigned NumParams = FnDecl->getNumParams()
15434                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15435   if (Op != OO_Call &&
15436       ((NumParams == 1 && !CanBeUnaryOperator) ||
15437        (NumParams == 2 && !CanBeBinaryOperator) ||
15438        (NumParams < 1) || (NumParams > 2))) {
15439     // We have the wrong number of parameters.
15440     unsigned ErrorKind;
15441     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15442       ErrorKind = 2;  // 2 -> unary or binary.
15443     } else if (CanBeUnaryOperator) {
15444       ErrorKind = 0;  // 0 -> unary
15445     } else {
15446       assert(CanBeBinaryOperator &&
15447              "All non-call overloaded operators are unary or binary!");
15448       ErrorKind = 1;  // 1 -> binary
15449     }
15450 
15451     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15452       << FnDecl->getDeclName() << NumParams << ErrorKind;
15453   }
15454 
15455   // Overloaded operators other than operator() cannot be variadic.
15456   if (Op != OO_Call &&
15457       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15458     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15459       << FnDecl->getDeclName();
15460   }
15461 
15462   // Some operators must be non-static member functions.
15463   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15464     return Diag(FnDecl->getLocation(),
15465                 diag::err_operator_overload_must_be_member)
15466       << FnDecl->getDeclName();
15467   }
15468 
15469   // C++ [over.inc]p1:
15470   //   The user-defined function called operator++ implements the
15471   //   prefix and postfix ++ operator. If this function is a member
15472   //   function with no parameters, or a non-member function with one
15473   //   parameter of class or enumeration type, it defines the prefix
15474   //   increment operator ++ for objects of that type. If the function
15475   //   is a member function with one parameter (which shall be of type
15476   //   int) or a non-member function with two parameters (the second
15477   //   of which shall be of type int), it defines the postfix
15478   //   increment operator ++ for objects of that type.
15479   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15480     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15481     QualType ParamType = LastParam->getType();
15482 
15483     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15484         !ParamType->isDependentType())
15485       return Diag(LastParam->getLocation(),
15486                   diag::err_operator_overload_post_incdec_must_be_int)
15487         << LastParam->getType() << (Op == OO_MinusMinus);
15488   }
15489 
15490   return false;
15491 }
15492 
15493 static bool
15494 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15495                                           FunctionTemplateDecl *TpDecl) {
15496   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15497 
15498   // Must have one or two template parameters.
15499   if (TemplateParams->size() == 1) {
15500     NonTypeTemplateParmDecl *PmDecl =
15501         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15502 
15503     // The template parameter must be a char parameter pack.
15504     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15505         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15506       return false;
15507 
15508   } else if (TemplateParams->size() == 2) {
15509     TemplateTypeParmDecl *PmType =
15510         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15511     NonTypeTemplateParmDecl *PmArgs =
15512         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15513 
15514     // The second template parameter must be a parameter pack with the
15515     // first template parameter as its type.
15516     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15517         PmArgs->isTemplateParameterPack()) {
15518       const TemplateTypeParmType *TArgs =
15519           PmArgs->getType()->getAs<TemplateTypeParmType>();
15520       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15521           TArgs->getIndex() == PmType->getIndex()) {
15522         if (!SemaRef.inTemplateInstantiation())
15523           SemaRef.Diag(TpDecl->getLocation(),
15524                        diag::ext_string_literal_operator_template);
15525         return false;
15526       }
15527     }
15528   }
15529 
15530   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15531                diag::err_literal_operator_template)
15532       << TpDecl->getTemplateParameters()->getSourceRange();
15533   return true;
15534 }
15535 
15536 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15537 /// of this literal operator function is well-formed. If so, returns
15538 /// false; otherwise, emits appropriate diagnostics and returns true.
15539 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15540   if (isa<CXXMethodDecl>(FnDecl)) {
15541     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15542       << FnDecl->getDeclName();
15543     return true;
15544   }
15545 
15546   if (FnDecl->isExternC()) {
15547     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15548     if (const LinkageSpecDecl *LSD =
15549             FnDecl->getDeclContext()->getExternCContext())
15550       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15551     return true;
15552   }
15553 
15554   // This might be the definition of a literal operator template.
15555   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15556 
15557   // This might be a specialization of a literal operator template.
15558   if (!TpDecl)
15559     TpDecl = FnDecl->getPrimaryTemplate();
15560 
15561   // template <char...> type operator "" name() and
15562   // template <class T, T...> type operator "" name() are the only valid
15563   // template signatures, and the only valid signatures with no parameters.
15564   if (TpDecl) {
15565     if (FnDecl->param_size() != 0) {
15566       Diag(FnDecl->getLocation(),
15567            diag::err_literal_operator_template_with_params);
15568       return true;
15569     }
15570 
15571     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15572       return true;
15573 
15574   } else if (FnDecl->param_size() == 1) {
15575     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15576 
15577     QualType ParamType = Param->getType().getUnqualifiedType();
15578 
15579     // Only unsigned long long int, long double, any character type, and const
15580     // char * are allowed as the only parameters.
15581     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15582         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15583         Context.hasSameType(ParamType, Context.CharTy) ||
15584         Context.hasSameType(ParamType, Context.WideCharTy) ||
15585         Context.hasSameType(ParamType, Context.Char8Ty) ||
15586         Context.hasSameType(ParamType, Context.Char16Ty) ||
15587         Context.hasSameType(ParamType, Context.Char32Ty)) {
15588     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15589       QualType InnerType = Ptr->getPointeeType();
15590 
15591       // Pointer parameter must be a const char *.
15592       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15593                                 Context.CharTy) &&
15594             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15595         Diag(Param->getSourceRange().getBegin(),
15596              diag::err_literal_operator_param)
15597             << ParamType << "'const char *'" << Param->getSourceRange();
15598         return true;
15599       }
15600 
15601     } else if (ParamType->isRealFloatingType()) {
15602       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15603           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15604       return true;
15605 
15606     } else if (ParamType->isIntegerType()) {
15607       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15608           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15609       return true;
15610 
15611     } else {
15612       Diag(Param->getSourceRange().getBegin(),
15613            diag::err_literal_operator_invalid_param)
15614           << ParamType << Param->getSourceRange();
15615       return true;
15616     }
15617 
15618   } else if (FnDecl->param_size() == 2) {
15619     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15620 
15621     // First, verify that the first parameter is correct.
15622 
15623     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15624 
15625     // Two parameter function must have a pointer to const as a
15626     // first parameter; let's strip those qualifiers.
15627     const PointerType *PT = FirstParamType->getAs<PointerType>();
15628 
15629     if (!PT) {
15630       Diag((*Param)->getSourceRange().getBegin(),
15631            diag::err_literal_operator_param)
15632           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15633       return true;
15634     }
15635 
15636     QualType PointeeType = PT->getPointeeType();
15637     // First parameter must be const
15638     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15639       Diag((*Param)->getSourceRange().getBegin(),
15640            diag::err_literal_operator_param)
15641           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15642       return true;
15643     }
15644 
15645     QualType InnerType = PointeeType.getUnqualifiedType();
15646     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15647     // const char32_t* are allowed as the first parameter to a two-parameter
15648     // function
15649     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15650           Context.hasSameType(InnerType, Context.WideCharTy) ||
15651           Context.hasSameType(InnerType, Context.Char8Ty) ||
15652           Context.hasSameType(InnerType, Context.Char16Ty) ||
15653           Context.hasSameType(InnerType, Context.Char32Ty))) {
15654       Diag((*Param)->getSourceRange().getBegin(),
15655            diag::err_literal_operator_param)
15656           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15657       return true;
15658     }
15659 
15660     // Move on to the second and final parameter.
15661     ++Param;
15662 
15663     // The second parameter must be a std::size_t.
15664     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15665     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15666       Diag((*Param)->getSourceRange().getBegin(),
15667            diag::err_literal_operator_param)
15668           << SecondParamType << Context.getSizeType()
15669           << (*Param)->getSourceRange();
15670       return true;
15671     }
15672   } else {
15673     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15674     return true;
15675   }
15676 
15677   // Parameters are good.
15678 
15679   // A parameter-declaration-clause containing a default argument is not
15680   // equivalent to any of the permitted forms.
15681   for (auto Param : FnDecl->parameters()) {
15682     if (Param->hasDefaultArg()) {
15683       Diag(Param->getDefaultArgRange().getBegin(),
15684            diag::err_literal_operator_default_argument)
15685         << Param->getDefaultArgRange();
15686       break;
15687     }
15688   }
15689 
15690   StringRef LiteralName
15691     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15692   if (LiteralName[0] != '_' &&
15693       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15694     // C++11 [usrlit.suffix]p1:
15695     //   Literal suffix identifiers that do not start with an underscore
15696     //   are reserved for future standardization.
15697     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15698       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15699   }
15700 
15701   return false;
15702 }
15703 
15704 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15705 /// linkage specification, including the language and (if present)
15706 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15707 /// language string literal. LBraceLoc, if valid, provides the location of
15708 /// the '{' brace. Otherwise, this linkage specification does not
15709 /// have any braces.
15710 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15711                                            Expr *LangStr,
15712                                            SourceLocation LBraceLoc) {
15713   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15714   if (!Lit->isAscii()) {
15715     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15716       << LangStr->getSourceRange();
15717     return nullptr;
15718   }
15719 
15720   StringRef Lang = Lit->getString();
15721   LinkageSpecDecl::LanguageIDs Language;
15722   if (Lang == "C")
15723     Language = LinkageSpecDecl::lang_c;
15724   else if (Lang == "C++")
15725     Language = LinkageSpecDecl::lang_cxx;
15726   else {
15727     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15728       << LangStr->getSourceRange();
15729     return nullptr;
15730   }
15731 
15732   // FIXME: Add all the various semantics of linkage specifications
15733 
15734   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15735                                                LangStr->getExprLoc(), Language,
15736                                                LBraceLoc.isValid());
15737   CurContext->addDecl(D);
15738   PushDeclContext(S, D);
15739   return D;
15740 }
15741 
15742 /// ActOnFinishLinkageSpecification - Complete the definition of
15743 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15744 /// valid, it's the position of the closing '}' brace in a linkage
15745 /// specification that uses braces.
15746 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15747                                             Decl *LinkageSpec,
15748                                             SourceLocation RBraceLoc) {
15749   if (RBraceLoc.isValid()) {
15750     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15751     LSDecl->setRBraceLoc(RBraceLoc);
15752   }
15753   PopDeclContext();
15754   return LinkageSpec;
15755 }
15756 
15757 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15758                                   const ParsedAttributesView &AttrList,
15759                                   SourceLocation SemiLoc) {
15760   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15761   // Attribute declarations appertain to empty declaration so we handle
15762   // them here.
15763   ProcessDeclAttributeList(S, ED, AttrList);
15764 
15765   CurContext->addDecl(ED);
15766   return ED;
15767 }
15768 
15769 /// Perform semantic analysis for the variable declaration that
15770 /// occurs within a C++ catch clause, returning the newly-created
15771 /// variable.
15772 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15773                                          TypeSourceInfo *TInfo,
15774                                          SourceLocation StartLoc,
15775                                          SourceLocation Loc,
15776                                          IdentifierInfo *Name) {
15777   bool Invalid = false;
15778   QualType ExDeclType = TInfo->getType();
15779 
15780   // Arrays and functions decay.
15781   if (ExDeclType->isArrayType())
15782     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15783   else if (ExDeclType->isFunctionType())
15784     ExDeclType = Context.getPointerType(ExDeclType);
15785 
15786   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15787   // The exception-declaration shall not denote a pointer or reference to an
15788   // incomplete type, other than [cv] void*.
15789   // N2844 forbids rvalue references.
15790   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15791     Diag(Loc, diag::err_catch_rvalue_ref);
15792     Invalid = true;
15793   }
15794 
15795   if (ExDeclType->isVariablyModifiedType()) {
15796     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15797     Invalid = true;
15798   }
15799 
15800   QualType BaseType = ExDeclType;
15801   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15802   unsigned DK = diag::err_catch_incomplete;
15803   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15804     BaseType = Ptr->getPointeeType();
15805     Mode = 1;
15806     DK = diag::err_catch_incomplete_ptr;
15807   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15808     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15809     BaseType = Ref->getPointeeType();
15810     Mode = 2;
15811     DK = diag::err_catch_incomplete_ref;
15812   }
15813   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15814       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15815     Invalid = true;
15816 
15817   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15818     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15819     Invalid = true;
15820   }
15821 
15822   if (!Invalid && !ExDeclType->isDependentType() &&
15823       RequireNonAbstractType(Loc, ExDeclType,
15824                              diag::err_abstract_type_in_decl,
15825                              AbstractVariableType))
15826     Invalid = true;
15827 
15828   // Only the non-fragile NeXT runtime currently supports C++ catches
15829   // of ObjC types, and no runtime supports catching ObjC types by value.
15830   if (!Invalid && getLangOpts().ObjC) {
15831     QualType T = ExDeclType;
15832     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15833       T = RT->getPointeeType();
15834 
15835     if (T->isObjCObjectType()) {
15836       Diag(Loc, diag::err_objc_object_catch);
15837       Invalid = true;
15838     } else if (T->isObjCObjectPointerType()) {
15839       // FIXME: should this be a test for macosx-fragile specifically?
15840       if (getLangOpts().ObjCRuntime.isFragile())
15841         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15842     }
15843   }
15844 
15845   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15846                                     ExDeclType, TInfo, SC_None);
15847   ExDecl->setExceptionVariable(true);
15848 
15849   // In ARC, infer 'retaining' for variables of retainable type.
15850   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15851     Invalid = true;
15852 
15853   if (!Invalid && !ExDeclType->isDependentType()) {
15854     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15855       // Insulate this from anything else we might currently be parsing.
15856       EnterExpressionEvaluationContext scope(
15857           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15858 
15859       // C++ [except.handle]p16:
15860       //   The object declared in an exception-declaration or, if the
15861       //   exception-declaration does not specify a name, a temporary (12.2) is
15862       //   copy-initialized (8.5) from the exception object. [...]
15863       //   The object is destroyed when the handler exits, after the destruction
15864       //   of any automatic objects initialized within the handler.
15865       //
15866       // We just pretend to initialize the object with itself, then make sure
15867       // it can be destroyed later.
15868       QualType initType = Context.getExceptionObjectType(ExDeclType);
15869 
15870       InitializedEntity entity =
15871         InitializedEntity::InitializeVariable(ExDecl);
15872       InitializationKind initKind =
15873         InitializationKind::CreateCopy(Loc, SourceLocation());
15874 
15875       Expr *opaqueValue =
15876         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15877       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15878       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15879       if (result.isInvalid())
15880         Invalid = true;
15881       else {
15882         // If the constructor used was non-trivial, set this as the
15883         // "initializer".
15884         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15885         if (!construct->getConstructor()->isTrivial()) {
15886           Expr *init = MaybeCreateExprWithCleanups(construct);
15887           ExDecl->setInit(init);
15888         }
15889 
15890         // And make sure it's destructable.
15891         FinalizeVarWithDestructor(ExDecl, recordType);
15892       }
15893     }
15894   }
15895 
15896   if (Invalid)
15897     ExDecl->setInvalidDecl();
15898 
15899   return ExDecl;
15900 }
15901 
15902 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15903 /// handler.
15904 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15905   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15906   bool Invalid = D.isInvalidType();
15907 
15908   // Check for unexpanded parameter packs.
15909   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15910                                       UPPC_ExceptionType)) {
15911     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15912                                              D.getIdentifierLoc());
15913     Invalid = true;
15914   }
15915 
15916   IdentifierInfo *II = D.getIdentifier();
15917   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15918                                              LookupOrdinaryName,
15919                                              ForVisibleRedeclaration)) {
15920     // The scope should be freshly made just for us. There is just no way
15921     // it contains any previous declaration, except for function parameters in
15922     // a function-try-block's catch statement.
15923     assert(!S->isDeclScope(PrevDecl));
15924     if (isDeclInScope(PrevDecl, CurContext, S)) {
15925       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15926         << D.getIdentifier();
15927       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15928       Invalid = true;
15929     } else if (PrevDecl->isTemplateParameter())
15930       // Maybe we will complain about the shadowed template parameter.
15931       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15932   }
15933 
15934   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15935     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15936       << D.getCXXScopeSpec().getRange();
15937     Invalid = true;
15938   }
15939 
15940   VarDecl *ExDecl = BuildExceptionDeclaration(
15941       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15942   if (Invalid)
15943     ExDecl->setInvalidDecl();
15944 
15945   // Add the exception declaration into this scope.
15946   if (II)
15947     PushOnScopeChains(ExDecl, S);
15948   else
15949     CurContext->addDecl(ExDecl);
15950 
15951   ProcessDeclAttributes(S, ExDecl, D);
15952   return ExDecl;
15953 }
15954 
15955 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15956                                          Expr *AssertExpr,
15957                                          Expr *AssertMessageExpr,
15958                                          SourceLocation RParenLoc) {
15959   StringLiteral *AssertMessage =
15960       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15961 
15962   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15963     return nullptr;
15964 
15965   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15966                                       AssertMessage, RParenLoc, false);
15967 }
15968 
15969 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15970                                          Expr *AssertExpr,
15971                                          StringLiteral *AssertMessage,
15972                                          SourceLocation RParenLoc,
15973                                          bool Failed) {
15974   assert(AssertExpr != nullptr && "Expected non-null condition");
15975   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15976       !Failed) {
15977     // In a static_assert-declaration, the constant-expression shall be a
15978     // constant expression that can be contextually converted to bool.
15979     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15980     if (Converted.isInvalid())
15981       Failed = true;
15982 
15983     ExprResult FullAssertExpr =
15984         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15985                             /*DiscardedValue*/ false,
15986                             /*IsConstexpr*/ true);
15987     if (FullAssertExpr.isInvalid())
15988       Failed = true;
15989     else
15990       AssertExpr = FullAssertExpr.get();
15991 
15992     llvm::APSInt Cond;
15993     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15994           diag::err_static_assert_expression_is_not_constant,
15995           /*AllowFold=*/false).isInvalid())
15996       Failed = true;
15997 
15998     if (!Failed && !Cond) {
15999       SmallString<256> MsgBuffer;
16000       llvm::raw_svector_ostream Msg(MsgBuffer);
16001       if (AssertMessage)
16002         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16003 
16004       Expr *InnerCond = nullptr;
16005       std::string InnerCondDescription;
16006       std::tie(InnerCond, InnerCondDescription) =
16007         findFailedBooleanCondition(Converted.get());
16008       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16009         // Drill down into concept specialization expressions to see why they
16010         // weren't satisfied.
16011         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16012           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16013         ConstraintSatisfaction Satisfaction;
16014         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16015           DiagnoseUnsatisfiedConstraint(Satisfaction);
16016       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16017                            && !isa<IntegerLiteral>(InnerCond)) {
16018         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16019           << InnerCondDescription << !AssertMessage
16020           << Msg.str() << InnerCond->getSourceRange();
16021       } else {
16022         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16023           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16024       }
16025       Failed = true;
16026     }
16027   } else {
16028     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16029                                                     /*DiscardedValue*/false,
16030                                                     /*IsConstexpr*/true);
16031     if (FullAssertExpr.isInvalid())
16032       Failed = true;
16033     else
16034       AssertExpr = FullAssertExpr.get();
16035   }
16036 
16037   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16038                                         AssertExpr, AssertMessage, RParenLoc,
16039                                         Failed);
16040 
16041   CurContext->addDecl(Decl);
16042   return Decl;
16043 }
16044 
16045 /// Perform semantic analysis of the given friend type declaration.
16046 ///
16047 /// \returns A friend declaration that.
16048 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16049                                       SourceLocation FriendLoc,
16050                                       TypeSourceInfo *TSInfo) {
16051   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16052 
16053   QualType T = TSInfo->getType();
16054   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16055 
16056   // C++03 [class.friend]p2:
16057   //   An elaborated-type-specifier shall be used in a friend declaration
16058   //   for a class.*
16059   //
16060   //   * The class-key of the elaborated-type-specifier is required.
16061   if (!CodeSynthesisContexts.empty()) {
16062     // Do not complain about the form of friend template types during any kind
16063     // of code synthesis. For template instantiation, we will have complained
16064     // when the template was defined.
16065   } else {
16066     if (!T->isElaboratedTypeSpecifier()) {
16067       // If we evaluated the type to a record type, suggest putting
16068       // a tag in front.
16069       if (const RecordType *RT = T->getAs<RecordType>()) {
16070         RecordDecl *RD = RT->getDecl();
16071 
16072         SmallString<16> InsertionText(" ");
16073         InsertionText += RD->getKindName();
16074 
16075         Diag(TypeRange.getBegin(),
16076              getLangOpts().CPlusPlus11 ?
16077                diag::warn_cxx98_compat_unelaborated_friend_type :
16078                diag::ext_unelaborated_friend_type)
16079           << (unsigned) RD->getTagKind()
16080           << T
16081           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16082                                         InsertionText);
16083       } else {
16084         Diag(FriendLoc,
16085              getLangOpts().CPlusPlus11 ?
16086                diag::warn_cxx98_compat_nonclass_type_friend :
16087                diag::ext_nonclass_type_friend)
16088           << T
16089           << TypeRange;
16090       }
16091     } else if (T->getAs<EnumType>()) {
16092       Diag(FriendLoc,
16093            getLangOpts().CPlusPlus11 ?
16094              diag::warn_cxx98_compat_enum_friend :
16095              diag::ext_enum_friend)
16096         << T
16097         << TypeRange;
16098     }
16099 
16100     // C++11 [class.friend]p3:
16101     //   A friend declaration that does not declare a function shall have one
16102     //   of the following forms:
16103     //     friend elaborated-type-specifier ;
16104     //     friend simple-type-specifier ;
16105     //     friend typename-specifier ;
16106     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16107       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16108   }
16109 
16110   //   If the type specifier in a friend declaration designates a (possibly
16111   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16112   //   the friend declaration is ignored.
16113   return FriendDecl::Create(Context, CurContext,
16114                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16115                             FriendLoc);
16116 }
16117 
16118 /// Handle a friend tag declaration where the scope specifier was
16119 /// templated.
16120 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16121                                     unsigned TagSpec, SourceLocation TagLoc,
16122                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16123                                     SourceLocation NameLoc,
16124                                     const ParsedAttributesView &Attr,
16125                                     MultiTemplateParamsArg TempParamLists) {
16126   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16127 
16128   bool IsMemberSpecialization = false;
16129   bool Invalid = false;
16130 
16131   if (TemplateParameterList *TemplateParams =
16132           MatchTemplateParametersToScopeSpecifier(
16133               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16134               IsMemberSpecialization, Invalid)) {
16135     if (TemplateParams->size() > 0) {
16136       // This is a declaration of a class template.
16137       if (Invalid)
16138         return nullptr;
16139 
16140       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16141                                 NameLoc, Attr, TemplateParams, AS_public,
16142                                 /*ModulePrivateLoc=*/SourceLocation(),
16143                                 FriendLoc, TempParamLists.size() - 1,
16144                                 TempParamLists.data()).get();
16145     } else {
16146       // The "template<>" header is extraneous.
16147       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16148         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16149       IsMemberSpecialization = true;
16150     }
16151   }
16152 
16153   if (Invalid) return nullptr;
16154 
16155   bool isAllExplicitSpecializations = true;
16156   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16157     if (TempParamLists[I]->size()) {
16158       isAllExplicitSpecializations = false;
16159       break;
16160     }
16161   }
16162 
16163   // FIXME: don't ignore attributes.
16164 
16165   // If it's explicit specializations all the way down, just forget
16166   // about the template header and build an appropriate non-templated
16167   // friend.  TODO: for source fidelity, remember the headers.
16168   if (isAllExplicitSpecializations) {
16169     if (SS.isEmpty()) {
16170       bool Owned = false;
16171       bool IsDependent = false;
16172       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16173                       Attr, AS_public,
16174                       /*ModulePrivateLoc=*/SourceLocation(),
16175                       MultiTemplateParamsArg(), Owned, IsDependent,
16176                       /*ScopedEnumKWLoc=*/SourceLocation(),
16177                       /*ScopedEnumUsesClassTag=*/false,
16178                       /*UnderlyingType=*/TypeResult(),
16179                       /*IsTypeSpecifier=*/false,
16180                       /*IsTemplateParamOrArg=*/false);
16181     }
16182 
16183     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16184     ElaboratedTypeKeyword Keyword
16185       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16186     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16187                                    *Name, NameLoc);
16188     if (T.isNull())
16189       return nullptr;
16190 
16191     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16192     if (isa<DependentNameType>(T)) {
16193       DependentNameTypeLoc TL =
16194           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16195       TL.setElaboratedKeywordLoc(TagLoc);
16196       TL.setQualifierLoc(QualifierLoc);
16197       TL.setNameLoc(NameLoc);
16198     } else {
16199       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16200       TL.setElaboratedKeywordLoc(TagLoc);
16201       TL.setQualifierLoc(QualifierLoc);
16202       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16203     }
16204 
16205     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16206                                             TSI, FriendLoc, TempParamLists);
16207     Friend->setAccess(AS_public);
16208     CurContext->addDecl(Friend);
16209     return Friend;
16210   }
16211 
16212   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16213 
16214 
16215 
16216   // Handle the case of a templated-scope friend class.  e.g.
16217   //   template <class T> class A<T>::B;
16218   // FIXME: we don't support these right now.
16219   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16220     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16221   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16222   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16223   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16224   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16225   TL.setElaboratedKeywordLoc(TagLoc);
16226   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16227   TL.setNameLoc(NameLoc);
16228 
16229   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16230                                           TSI, FriendLoc, TempParamLists);
16231   Friend->setAccess(AS_public);
16232   Friend->setUnsupportedFriend(true);
16233   CurContext->addDecl(Friend);
16234   return Friend;
16235 }
16236 
16237 /// Handle a friend type declaration.  This works in tandem with
16238 /// ActOnTag.
16239 ///
16240 /// Notes on friend class templates:
16241 ///
16242 /// We generally treat friend class declarations as if they were
16243 /// declaring a class.  So, for example, the elaborated type specifier
16244 /// in a friend declaration is required to obey the restrictions of a
16245 /// class-head (i.e. no typedefs in the scope chain), template
16246 /// parameters are required to match up with simple template-ids, &c.
16247 /// However, unlike when declaring a template specialization, it's
16248 /// okay to refer to a template specialization without an empty
16249 /// template parameter declaration, e.g.
16250 ///   friend class A<T>::B<unsigned>;
16251 /// We permit this as a special case; if there are any template
16252 /// parameters present at all, require proper matching, i.e.
16253 ///   template <> template \<class T> friend class A<int>::B;
16254 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16255                                 MultiTemplateParamsArg TempParams) {
16256   SourceLocation Loc = DS.getBeginLoc();
16257 
16258   assert(DS.isFriendSpecified());
16259   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16260 
16261   // C++ [class.friend]p3:
16262   // A friend declaration that does not declare a function shall have one of
16263   // the following forms:
16264   //     friend elaborated-type-specifier ;
16265   //     friend simple-type-specifier ;
16266   //     friend typename-specifier ;
16267   //
16268   // Any declaration with a type qualifier does not have that form. (It's
16269   // legal to specify a qualified type as a friend, you just can't write the
16270   // keywords.)
16271   if (DS.getTypeQualifiers()) {
16272     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16273       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16274     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16275       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16276     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16277       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16278     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16279       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16280     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16281       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16282   }
16283 
16284   // Try to convert the decl specifier to a type.  This works for
16285   // friend templates because ActOnTag never produces a ClassTemplateDecl
16286   // for a TUK_Friend.
16287   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16288   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16289   QualType T = TSI->getType();
16290   if (TheDeclarator.isInvalidType())
16291     return nullptr;
16292 
16293   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16294     return nullptr;
16295 
16296   // This is definitely an error in C++98.  It's probably meant to
16297   // be forbidden in C++0x, too, but the specification is just
16298   // poorly written.
16299   //
16300   // The problem is with declarations like the following:
16301   //   template <T> friend A<T>::foo;
16302   // where deciding whether a class C is a friend or not now hinges
16303   // on whether there exists an instantiation of A that causes
16304   // 'foo' to equal C.  There are restrictions on class-heads
16305   // (which we declare (by fiat) elaborated friend declarations to
16306   // be) that makes this tractable.
16307   //
16308   // FIXME: handle "template <> friend class A<T>;", which
16309   // is possibly well-formed?  Who even knows?
16310   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16311     Diag(Loc, diag::err_tagless_friend_type_template)
16312       << DS.getSourceRange();
16313     return nullptr;
16314   }
16315 
16316   // C++98 [class.friend]p1: A friend of a class is a function
16317   //   or class that is not a member of the class . . .
16318   // This is fixed in DR77, which just barely didn't make the C++03
16319   // deadline.  It's also a very silly restriction that seriously
16320   // affects inner classes and which nobody else seems to implement;
16321   // thus we never diagnose it, not even in -pedantic.
16322   //
16323   // But note that we could warn about it: it's always useless to
16324   // friend one of your own members (it's not, however, worthless to
16325   // friend a member of an arbitrary specialization of your template).
16326 
16327   Decl *D;
16328   if (!TempParams.empty())
16329     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16330                                    TempParams,
16331                                    TSI,
16332                                    DS.getFriendSpecLoc());
16333   else
16334     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16335 
16336   if (!D)
16337     return nullptr;
16338 
16339   D->setAccess(AS_public);
16340   CurContext->addDecl(D);
16341 
16342   return D;
16343 }
16344 
16345 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16346                                         MultiTemplateParamsArg TemplateParams) {
16347   const DeclSpec &DS = D.getDeclSpec();
16348 
16349   assert(DS.isFriendSpecified());
16350   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16351 
16352   SourceLocation Loc = D.getIdentifierLoc();
16353   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16354 
16355   // C++ [class.friend]p1
16356   //   A friend of a class is a function or class....
16357   // Note that this sees through typedefs, which is intended.
16358   // It *doesn't* see through dependent types, which is correct
16359   // according to [temp.arg.type]p3:
16360   //   If a declaration acquires a function type through a
16361   //   type dependent on a template-parameter and this causes
16362   //   a declaration that does not use the syntactic form of a
16363   //   function declarator to have a function type, the program
16364   //   is ill-formed.
16365   if (!TInfo->getType()->isFunctionType()) {
16366     Diag(Loc, diag::err_unexpected_friend);
16367 
16368     // It might be worthwhile to try to recover by creating an
16369     // appropriate declaration.
16370     return nullptr;
16371   }
16372 
16373   // C++ [namespace.memdef]p3
16374   //  - If a friend declaration in a non-local class first declares a
16375   //    class or function, the friend class or function is a member
16376   //    of the innermost enclosing namespace.
16377   //  - The name of the friend is not found by simple name lookup
16378   //    until a matching declaration is provided in that namespace
16379   //    scope (either before or after the class declaration granting
16380   //    friendship).
16381   //  - If a friend function is called, its name may be found by the
16382   //    name lookup that considers functions from namespaces and
16383   //    classes associated with the types of the function arguments.
16384   //  - When looking for a prior declaration of a class or a function
16385   //    declared as a friend, scopes outside the innermost enclosing
16386   //    namespace scope are not considered.
16387 
16388   CXXScopeSpec &SS = D.getCXXScopeSpec();
16389   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16390   assert(NameInfo.getName());
16391 
16392   // Check for unexpanded parameter packs.
16393   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16394       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16395       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16396     return nullptr;
16397 
16398   // The context we found the declaration in, or in which we should
16399   // create the declaration.
16400   DeclContext *DC;
16401   Scope *DCScope = S;
16402   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16403                         ForExternalRedeclaration);
16404 
16405   // There are five cases here.
16406   //   - There's no scope specifier and we're in a local class. Only look
16407   //     for functions declared in the immediately-enclosing block scope.
16408   // We recover from invalid scope qualifiers as if they just weren't there.
16409   FunctionDecl *FunctionContainingLocalClass = nullptr;
16410   if ((SS.isInvalid() || !SS.isSet()) &&
16411       (FunctionContainingLocalClass =
16412            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16413     // C++11 [class.friend]p11:
16414     //   If a friend declaration appears in a local class and the name
16415     //   specified is an unqualified name, a prior declaration is
16416     //   looked up without considering scopes that are outside the
16417     //   innermost enclosing non-class scope. For a friend function
16418     //   declaration, if there is no prior declaration, the program is
16419     //   ill-formed.
16420 
16421     // Find the innermost enclosing non-class scope. This is the block
16422     // scope containing the local class definition (or for a nested class,
16423     // the outer local class).
16424     DCScope = S->getFnParent();
16425 
16426     // Look up the function name in the scope.
16427     Previous.clear(LookupLocalFriendName);
16428     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16429 
16430     if (!Previous.empty()) {
16431       // All possible previous declarations must have the same context:
16432       // either they were declared at block scope or they are members of
16433       // one of the enclosing local classes.
16434       DC = Previous.getRepresentativeDecl()->getDeclContext();
16435     } else {
16436       // This is ill-formed, but provide the context that we would have
16437       // declared the function in, if we were permitted to, for error recovery.
16438       DC = FunctionContainingLocalClass;
16439     }
16440     adjustContextForLocalExternDecl(DC);
16441 
16442     // C++ [class.friend]p6:
16443     //   A function can be defined in a friend declaration of a class if and
16444     //   only if the class is a non-local class (9.8), the function name is
16445     //   unqualified, and the function has namespace scope.
16446     if (D.isFunctionDefinition()) {
16447       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16448     }
16449 
16450   //   - There's no scope specifier, in which case we just go to the
16451   //     appropriate scope and look for a function or function template
16452   //     there as appropriate.
16453   } else if (SS.isInvalid() || !SS.isSet()) {
16454     // C++11 [namespace.memdef]p3:
16455     //   If the name in a friend declaration is neither qualified nor
16456     //   a template-id and the declaration is a function or an
16457     //   elaborated-type-specifier, the lookup to determine whether
16458     //   the entity has been previously declared shall not consider
16459     //   any scopes outside the innermost enclosing namespace.
16460     bool isTemplateId =
16461         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16462 
16463     // Find the appropriate context according to the above.
16464     DC = CurContext;
16465 
16466     // Skip class contexts.  If someone can cite chapter and verse
16467     // for this behavior, that would be nice --- it's what GCC and
16468     // EDG do, and it seems like a reasonable intent, but the spec
16469     // really only says that checks for unqualified existing
16470     // declarations should stop at the nearest enclosing namespace,
16471     // not that they should only consider the nearest enclosing
16472     // namespace.
16473     while (DC->isRecord())
16474       DC = DC->getParent();
16475 
16476     DeclContext *LookupDC = DC;
16477     while (LookupDC->isTransparentContext())
16478       LookupDC = LookupDC->getParent();
16479 
16480     while (true) {
16481       LookupQualifiedName(Previous, LookupDC);
16482 
16483       if (!Previous.empty()) {
16484         DC = LookupDC;
16485         break;
16486       }
16487 
16488       if (isTemplateId) {
16489         if (isa<TranslationUnitDecl>(LookupDC)) break;
16490       } else {
16491         if (LookupDC->isFileContext()) break;
16492       }
16493       LookupDC = LookupDC->getParent();
16494     }
16495 
16496     DCScope = getScopeForDeclContext(S, DC);
16497 
16498   //   - There's a non-dependent scope specifier, in which case we
16499   //     compute it and do a previous lookup there for a function
16500   //     or function template.
16501   } else if (!SS.getScopeRep()->isDependent()) {
16502     DC = computeDeclContext(SS);
16503     if (!DC) return nullptr;
16504 
16505     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16506 
16507     LookupQualifiedName(Previous, DC);
16508 
16509     // C++ [class.friend]p1: A friend of a class is a function or
16510     //   class that is not a member of the class . . .
16511     if (DC->Equals(CurContext))
16512       Diag(DS.getFriendSpecLoc(),
16513            getLangOpts().CPlusPlus11 ?
16514              diag::warn_cxx98_compat_friend_is_member :
16515              diag::err_friend_is_member);
16516 
16517     if (D.isFunctionDefinition()) {
16518       // C++ [class.friend]p6:
16519       //   A function can be defined in a friend declaration of a class if and
16520       //   only if the class is a non-local class (9.8), the function name is
16521       //   unqualified, and the function has namespace scope.
16522       //
16523       // FIXME: We should only do this if the scope specifier names the
16524       // innermost enclosing namespace; otherwise the fixit changes the
16525       // meaning of the code.
16526       SemaDiagnosticBuilder DB
16527         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16528 
16529       DB << SS.getScopeRep();
16530       if (DC->isFileContext())
16531         DB << FixItHint::CreateRemoval(SS.getRange());
16532       SS.clear();
16533     }
16534 
16535   //   - There's a scope specifier that does not match any template
16536   //     parameter lists, in which case we use some arbitrary context,
16537   //     create a method or method template, and wait for instantiation.
16538   //   - There's a scope specifier that does match some template
16539   //     parameter lists, which we don't handle right now.
16540   } else {
16541     if (D.isFunctionDefinition()) {
16542       // C++ [class.friend]p6:
16543       //   A function can be defined in a friend declaration of a class if and
16544       //   only if the class is a non-local class (9.8), the function name is
16545       //   unqualified, and the function has namespace scope.
16546       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16547         << SS.getScopeRep();
16548     }
16549 
16550     DC = CurContext;
16551     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16552   }
16553 
16554   if (!DC->isRecord()) {
16555     int DiagArg = -1;
16556     switch (D.getName().getKind()) {
16557     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16558     case UnqualifiedIdKind::IK_ConstructorName:
16559       DiagArg = 0;
16560       break;
16561     case UnqualifiedIdKind::IK_DestructorName:
16562       DiagArg = 1;
16563       break;
16564     case UnqualifiedIdKind::IK_ConversionFunctionId:
16565       DiagArg = 2;
16566       break;
16567     case UnqualifiedIdKind::IK_DeductionGuideName:
16568       DiagArg = 3;
16569       break;
16570     case UnqualifiedIdKind::IK_Identifier:
16571     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16572     case UnqualifiedIdKind::IK_LiteralOperatorId:
16573     case UnqualifiedIdKind::IK_OperatorFunctionId:
16574     case UnqualifiedIdKind::IK_TemplateId:
16575       break;
16576     }
16577     // This implies that it has to be an operator or function.
16578     if (DiagArg >= 0) {
16579       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16580       return nullptr;
16581     }
16582   }
16583 
16584   // FIXME: This is an egregious hack to cope with cases where the scope stack
16585   // does not contain the declaration context, i.e., in an out-of-line
16586   // definition of a class.
16587   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16588   if (!DCScope) {
16589     FakeDCScope.setEntity(DC);
16590     DCScope = &FakeDCScope;
16591   }
16592 
16593   bool AddToScope = true;
16594   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16595                                           TemplateParams, AddToScope);
16596   if (!ND) return nullptr;
16597 
16598   assert(ND->getLexicalDeclContext() == CurContext);
16599 
16600   // If we performed typo correction, we might have added a scope specifier
16601   // and changed the decl context.
16602   DC = ND->getDeclContext();
16603 
16604   // Add the function declaration to the appropriate lookup tables,
16605   // adjusting the redeclarations list as necessary.  We don't
16606   // want to do this yet if the friending class is dependent.
16607   //
16608   // Also update the scope-based lookup if the target context's
16609   // lookup context is in lexical scope.
16610   if (!CurContext->isDependentContext()) {
16611     DC = DC->getRedeclContext();
16612     DC->makeDeclVisibleInContext(ND);
16613     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16614       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16615   }
16616 
16617   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16618                                        D.getIdentifierLoc(), ND,
16619                                        DS.getFriendSpecLoc());
16620   FrD->setAccess(AS_public);
16621   CurContext->addDecl(FrD);
16622 
16623   if (ND->isInvalidDecl()) {
16624     FrD->setInvalidDecl();
16625   } else {
16626     if (DC->isRecord()) CheckFriendAccess(ND);
16627 
16628     FunctionDecl *FD;
16629     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16630       FD = FTD->getTemplatedDecl();
16631     else
16632       FD = cast<FunctionDecl>(ND);
16633 
16634     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16635     // default argument expression, that declaration shall be a definition
16636     // and shall be the only declaration of the function or function
16637     // template in the translation unit.
16638     if (functionDeclHasDefaultArgument(FD)) {
16639       // We can't look at FD->getPreviousDecl() because it may not have been set
16640       // if we're in a dependent context. If the function is known to be a
16641       // redeclaration, we will have narrowed Previous down to the right decl.
16642       if (D.isRedeclaration()) {
16643         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16644         Diag(Previous.getRepresentativeDecl()->getLocation(),
16645              diag::note_previous_declaration);
16646       } else if (!D.isFunctionDefinition())
16647         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16648     }
16649 
16650     // Mark templated-scope function declarations as unsupported.
16651     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16652       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16653         << SS.getScopeRep() << SS.getRange()
16654         << cast<CXXRecordDecl>(CurContext);
16655       FrD->setUnsupportedFriend(true);
16656     }
16657   }
16658 
16659   return ND;
16660 }
16661 
16662 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16663   AdjustDeclIfTemplate(Dcl);
16664 
16665   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16666   if (!Fn) {
16667     Diag(DelLoc, diag::err_deleted_non_function);
16668     return;
16669   }
16670 
16671   // Deleted function does not have a body.
16672   Fn->setWillHaveBody(false);
16673 
16674   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16675     // Don't consider the implicit declaration we generate for explicit
16676     // specializations. FIXME: Do not generate these implicit declarations.
16677     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16678          Prev->getPreviousDecl()) &&
16679         !Prev->isDefined()) {
16680       Diag(DelLoc, diag::err_deleted_decl_not_first);
16681       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16682            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16683                               : diag::note_previous_declaration);
16684       // We can't recover from this; the declaration might have already
16685       // been used.
16686       Fn->setInvalidDecl();
16687       return;
16688     }
16689 
16690     // To maintain the invariant that functions are only deleted on their first
16691     // declaration, mark the implicitly-instantiated declaration of the
16692     // explicitly-specialized function as deleted instead of marking the
16693     // instantiated redeclaration.
16694     Fn = Fn->getCanonicalDecl();
16695   }
16696 
16697   // dllimport/dllexport cannot be deleted.
16698   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16699     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16700     Fn->setInvalidDecl();
16701   }
16702 
16703   // C++11 [basic.start.main]p3:
16704   //   A program that defines main as deleted [...] is ill-formed.
16705   if (Fn->isMain())
16706     Diag(DelLoc, diag::err_deleted_main);
16707 
16708   // C++11 [dcl.fct.def.delete]p4:
16709   //  A deleted function is implicitly inline.
16710   Fn->setImplicitlyInline();
16711   Fn->setDeletedAsWritten();
16712 }
16713 
16714 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16715   if (!Dcl || Dcl->isInvalidDecl())
16716     return;
16717 
16718   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16719   if (!FD) {
16720     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16721       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16722         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16723         return;
16724       }
16725     }
16726 
16727     Diag(DefaultLoc, diag::err_default_special_members)
16728         << getLangOpts().CPlusPlus20;
16729     return;
16730   }
16731 
16732   // Reject if this can't possibly be a defaultable function.
16733   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16734   if (!DefKind &&
16735       // A dependent function that doesn't locally look defaultable can
16736       // still instantiate to a defaultable function if it's a constructor
16737       // or assignment operator.
16738       (!FD->isDependentContext() ||
16739        (!isa<CXXConstructorDecl>(FD) &&
16740         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16741     Diag(DefaultLoc, diag::err_default_special_members)
16742         << getLangOpts().CPlusPlus20;
16743     return;
16744   }
16745 
16746   if (DefKind.isComparison() &&
16747       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16748     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16749         << (int)DefKind.asComparison();
16750     return;
16751   }
16752 
16753   // Issue compatibility warning. We already warned if the operator is
16754   // 'operator<=>' when parsing the '<=>' token.
16755   if (DefKind.isComparison() &&
16756       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16757     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16758                          ? diag::warn_cxx17_compat_defaulted_comparison
16759                          : diag::ext_defaulted_comparison);
16760   }
16761 
16762   FD->setDefaulted();
16763   FD->setExplicitlyDefaulted();
16764 
16765   // Defer checking functions that are defaulted in a dependent context.
16766   if (FD->isDependentContext())
16767     return;
16768 
16769   // Unset that we will have a body for this function. We might not,
16770   // if it turns out to be trivial, and we don't need this marking now
16771   // that we've marked it as defaulted.
16772   FD->setWillHaveBody(false);
16773 
16774   // If this definition appears within the record, do the checking when
16775   // the record is complete. This is always the case for a defaulted
16776   // comparison.
16777   if (DefKind.isComparison())
16778     return;
16779   auto *MD = cast<CXXMethodDecl>(FD);
16780 
16781   const FunctionDecl *Primary = FD;
16782   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16783     // Ask the template instantiation pattern that actually had the
16784     // '= default' on it.
16785     Primary = Pattern;
16786 
16787   // If the method was defaulted on its first declaration, we will have
16788   // already performed the checking in CheckCompletedCXXClass. Such a
16789   // declaration doesn't trigger an implicit definition.
16790   if (Primary->getCanonicalDecl()->isDefaulted())
16791     return;
16792 
16793   // FIXME: Once we support defining comparisons out of class, check for a
16794   // defaulted comparison here.
16795   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16796     MD->setInvalidDecl();
16797   else
16798     DefineDefaultedFunction(*this, MD, DefaultLoc);
16799 }
16800 
16801 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16802   for (Stmt *SubStmt : S->children()) {
16803     if (!SubStmt)
16804       continue;
16805     if (isa<ReturnStmt>(SubStmt))
16806       Self.Diag(SubStmt->getBeginLoc(),
16807                 diag::err_return_in_constructor_handler);
16808     if (!isa<Expr>(SubStmt))
16809       SearchForReturnInStmt(Self, SubStmt);
16810   }
16811 }
16812 
16813 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16814   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16815     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16816     SearchForReturnInStmt(*this, Handler);
16817   }
16818 }
16819 
16820 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16821                                              const CXXMethodDecl *Old) {
16822   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16823   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16824 
16825   if (OldFT->hasExtParameterInfos()) {
16826     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16827       // A parameter of the overriding method should be annotated with noescape
16828       // if the corresponding parameter of the overridden method is annotated.
16829       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16830           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16831         Diag(New->getParamDecl(I)->getLocation(),
16832              diag::warn_overriding_method_missing_noescape);
16833         Diag(Old->getParamDecl(I)->getLocation(),
16834              diag::note_overridden_marked_noescape);
16835       }
16836   }
16837 
16838   // Virtual overrides must have the same code_seg.
16839   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16840   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16841   if ((NewCSA || OldCSA) &&
16842       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16843     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16844     Diag(Old->getLocation(), diag::note_previous_declaration);
16845     return true;
16846   }
16847 
16848   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16849 
16850   // If the calling conventions match, everything is fine
16851   if (NewCC == OldCC)
16852     return false;
16853 
16854   // If the calling conventions mismatch because the new function is static,
16855   // suppress the calling convention mismatch error; the error about static
16856   // function override (err_static_overrides_virtual from
16857   // Sema::CheckFunctionDeclaration) is more clear.
16858   if (New->getStorageClass() == SC_Static)
16859     return false;
16860 
16861   Diag(New->getLocation(),
16862        diag::err_conflicting_overriding_cc_attributes)
16863     << New->getDeclName() << New->getType() << Old->getType();
16864   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16865   return true;
16866 }
16867 
16868 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16869                                              const CXXMethodDecl *Old) {
16870   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16871   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16872 
16873   if (Context.hasSameType(NewTy, OldTy) ||
16874       NewTy->isDependentType() || OldTy->isDependentType())
16875     return false;
16876 
16877   // Check if the return types are covariant
16878   QualType NewClassTy, OldClassTy;
16879 
16880   /// Both types must be pointers or references to classes.
16881   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16882     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16883       NewClassTy = NewPT->getPointeeType();
16884       OldClassTy = OldPT->getPointeeType();
16885     }
16886   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16887     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16888       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16889         NewClassTy = NewRT->getPointeeType();
16890         OldClassTy = OldRT->getPointeeType();
16891       }
16892     }
16893   }
16894 
16895   // The return types aren't either both pointers or references to a class type.
16896   if (NewClassTy.isNull()) {
16897     Diag(New->getLocation(),
16898          diag::err_different_return_type_for_overriding_virtual_function)
16899         << New->getDeclName() << NewTy << OldTy
16900         << New->getReturnTypeSourceRange();
16901     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16902         << Old->getReturnTypeSourceRange();
16903 
16904     return true;
16905   }
16906 
16907   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16908     // C++14 [class.virtual]p8:
16909     //   If the class type in the covariant return type of D::f differs from
16910     //   that of B::f, the class type in the return type of D::f shall be
16911     //   complete at the point of declaration of D::f or shall be the class
16912     //   type D.
16913     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16914       if (!RT->isBeingDefined() &&
16915           RequireCompleteType(New->getLocation(), NewClassTy,
16916                               diag::err_covariant_return_incomplete,
16917                               New->getDeclName()))
16918         return true;
16919     }
16920 
16921     // Check if the new class derives from the old class.
16922     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16923       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16924           << New->getDeclName() << NewTy << OldTy
16925           << New->getReturnTypeSourceRange();
16926       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16927           << Old->getReturnTypeSourceRange();
16928       return true;
16929     }
16930 
16931     // Check if we the conversion from derived to base is valid.
16932     if (CheckDerivedToBaseConversion(
16933             NewClassTy, OldClassTy,
16934             diag::err_covariant_return_inaccessible_base,
16935             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16936             New->getLocation(), New->getReturnTypeSourceRange(),
16937             New->getDeclName(), nullptr)) {
16938       // FIXME: this note won't trigger for delayed access control
16939       // diagnostics, and it's impossible to get an undelayed error
16940       // here from access control during the original parse because
16941       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16942       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16943           << Old->getReturnTypeSourceRange();
16944       return true;
16945     }
16946   }
16947 
16948   // The qualifiers of the return types must be the same.
16949   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16950     Diag(New->getLocation(),
16951          diag::err_covariant_return_type_different_qualifications)
16952         << New->getDeclName() << NewTy << OldTy
16953         << New->getReturnTypeSourceRange();
16954     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16955         << Old->getReturnTypeSourceRange();
16956     return true;
16957   }
16958 
16959 
16960   // The new class type must have the same or less qualifiers as the old type.
16961   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16962     Diag(New->getLocation(),
16963          diag::err_covariant_return_type_class_type_more_qualified)
16964         << New->getDeclName() << NewTy << OldTy
16965         << New->getReturnTypeSourceRange();
16966     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16967         << Old->getReturnTypeSourceRange();
16968     return true;
16969   }
16970 
16971   return false;
16972 }
16973 
16974 /// Mark the given method pure.
16975 ///
16976 /// \param Method the method to be marked pure.
16977 ///
16978 /// \param InitRange the source range that covers the "0" initializer.
16979 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16980   SourceLocation EndLoc = InitRange.getEnd();
16981   if (EndLoc.isValid())
16982     Method->setRangeEnd(EndLoc);
16983 
16984   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16985     Method->setPure();
16986     return false;
16987   }
16988 
16989   if (!Method->isInvalidDecl())
16990     Diag(Method->getLocation(), diag::err_non_virtual_pure)
16991       << Method->getDeclName() << InitRange;
16992   return true;
16993 }
16994 
16995 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16996   if (D->getFriendObjectKind())
16997     Diag(D->getLocation(), diag::err_pure_friend);
16998   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16999     CheckPureMethod(M, ZeroLoc);
17000   else
17001     Diag(D->getLocation(), diag::err_illegal_initializer);
17002 }
17003 
17004 /// Determine whether the given declaration is a global variable or
17005 /// static data member.
17006 static bool isNonlocalVariable(const Decl *D) {
17007   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17008     return Var->hasGlobalStorage();
17009 
17010   return false;
17011 }
17012 
17013 /// Invoked when we are about to parse an initializer for the declaration
17014 /// 'Dcl'.
17015 ///
17016 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17017 /// static data member of class X, names should be looked up in the scope of
17018 /// class X. If the declaration had a scope specifier, a scope will have
17019 /// been created and passed in for this purpose. Otherwise, S will be null.
17020 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17021   // If there is no declaration, there was an error parsing it.
17022   if (!D || D->isInvalidDecl())
17023     return;
17024 
17025   // We will always have a nested name specifier here, but this declaration
17026   // might not be out of line if the specifier names the current namespace:
17027   //   extern int n;
17028   //   int ::n = 0;
17029   if (S && D->isOutOfLine())
17030     EnterDeclaratorContext(S, D->getDeclContext());
17031 
17032   // If we are parsing the initializer for a static data member, push a
17033   // new expression evaluation context that is associated with this static
17034   // data member.
17035   if (isNonlocalVariable(D))
17036     PushExpressionEvaluationContext(
17037         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17038 }
17039 
17040 /// Invoked after we are finished parsing an initializer for the declaration D.
17041 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17042   // If there is no declaration, there was an error parsing it.
17043   if (!D || D->isInvalidDecl())
17044     return;
17045 
17046   if (isNonlocalVariable(D))
17047     PopExpressionEvaluationContext();
17048 
17049   if (S && D->isOutOfLine())
17050     ExitDeclaratorContext(S);
17051 }
17052 
17053 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17054 /// C++ if/switch/while/for statement.
17055 /// e.g: "if (int x = f()) {...}"
17056 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17057   // C++ 6.4p2:
17058   // The declarator shall not specify a function or an array.
17059   // The type-specifier-seq shall not contain typedef and shall not declare a
17060   // new class or enumeration.
17061   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17062          "Parser allowed 'typedef' as storage class of condition decl.");
17063 
17064   Decl *Dcl = ActOnDeclarator(S, D);
17065   if (!Dcl)
17066     return true;
17067 
17068   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17069     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17070       << D.getSourceRange();
17071     return true;
17072   }
17073 
17074   return Dcl;
17075 }
17076 
17077 void Sema::LoadExternalVTableUses() {
17078   if (!ExternalSource)
17079     return;
17080 
17081   SmallVector<ExternalVTableUse, 4> VTables;
17082   ExternalSource->ReadUsedVTables(VTables);
17083   SmallVector<VTableUse, 4> NewUses;
17084   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17085     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17086       = VTablesUsed.find(VTables[I].Record);
17087     // Even if a definition wasn't required before, it may be required now.
17088     if (Pos != VTablesUsed.end()) {
17089       if (!Pos->second && VTables[I].DefinitionRequired)
17090         Pos->second = true;
17091       continue;
17092     }
17093 
17094     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17095     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17096   }
17097 
17098   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17099 }
17100 
17101 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17102                           bool DefinitionRequired) {
17103   // Ignore any vtable uses in unevaluated operands or for classes that do
17104   // not have a vtable.
17105   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17106       CurContext->isDependentContext() || isUnevaluatedContext())
17107     return;
17108   // Do not mark as used if compiling for the device outside of the target
17109   // region.
17110   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17111       !isInOpenMPDeclareTargetContext() &&
17112       !isInOpenMPTargetExecutionDirective()) {
17113     if (!DefinitionRequired)
17114       MarkVirtualMembersReferenced(Loc, Class);
17115     return;
17116   }
17117 
17118   // Try to insert this class into the map.
17119   LoadExternalVTableUses();
17120   Class = Class->getCanonicalDecl();
17121   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17122     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17123   if (!Pos.second) {
17124     // If we already had an entry, check to see if we are promoting this vtable
17125     // to require a definition. If so, we need to reappend to the VTableUses
17126     // list, since we may have already processed the first entry.
17127     if (DefinitionRequired && !Pos.first->second) {
17128       Pos.first->second = true;
17129     } else {
17130       // Otherwise, we can early exit.
17131       return;
17132     }
17133   } else {
17134     // The Microsoft ABI requires that we perform the destructor body
17135     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17136     // the deleting destructor is emitted with the vtable, not with the
17137     // destructor definition as in the Itanium ABI.
17138     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17139       CXXDestructorDecl *DD = Class->getDestructor();
17140       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17141         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17142           // If this is an out-of-line declaration, marking it referenced will
17143           // not do anything. Manually call CheckDestructor to look up operator
17144           // delete().
17145           ContextRAII SavedContext(*this, DD);
17146           CheckDestructor(DD);
17147         } else {
17148           MarkFunctionReferenced(Loc, Class->getDestructor());
17149         }
17150       }
17151     }
17152   }
17153 
17154   // Local classes need to have their virtual members marked
17155   // immediately. For all other classes, we mark their virtual members
17156   // at the end of the translation unit.
17157   if (Class->isLocalClass())
17158     MarkVirtualMembersReferenced(Loc, Class);
17159   else
17160     VTableUses.push_back(std::make_pair(Class, Loc));
17161 }
17162 
17163 bool Sema::DefineUsedVTables() {
17164   LoadExternalVTableUses();
17165   if (VTableUses.empty())
17166     return false;
17167 
17168   // Note: The VTableUses vector could grow as a result of marking
17169   // the members of a class as "used", so we check the size each
17170   // time through the loop and prefer indices (which are stable) to
17171   // iterators (which are not).
17172   bool DefinedAnything = false;
17173   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17174     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17175     if (!Class)
17176       continue;
17177     TemplateSpecializationKind ClassTSK =
17178         Class->getTemplateSpecializationKind();
17179 
17180     SourceLocation Loc = VTableUses[I].second;
17181 
17182     bool DefineVTable = true;
17183 
17184     // If this class has a key function, but that key function is
17185     // defined in another translation unit, we don't need to emit the
17186     // vtable even though we're using it.
17187     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17188     if (KeyFunction && !KeyFunction->hasBody()) {
17189       // The key function is in another translation unit.
17190       DefineVTable = false;
17191       TemplateSpecializationKind TSK =
17192           KeyFunction->getTemplateSpecializationKind();
17193       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17194              TSK != TSK_ImplicitInstantiation &&
17195              "Instantiations don't have key functions");
17196       (void)TSK;
17197     } else if (!KeyFunction) {
17198       // If we have a class with no key function that is the subject
17199       // of an explicit instantiation declaration, suppress the
17200       // vtable; it will live with the explicit instantiation
17201       // definition.
17202       bool IsExplicitInstantiationDeclaration =
17203           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17204       for (auto R : Class->redecls()) {
17205         TemplateSpecializationKind TSK
17206           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17207         if (TSK == TSK_ExplicitInstantiationDeclaration)
17208           IsExplicitInstantiationDeclaration = true;
17209         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17210           IsExplicitInstantiationDeclaration = false;
17211           break;
17212         }
17213       }
17214 
17215       if (IsExplicitInstantiationDeclaration)
17216         DefineVTable = false;
17217     }
17218 
17219     // The exception specifications for all virtual members may be needed even
17220     // if we are not providing an authoritative form of the vtable in this TU.
17221     // We may choose to emit it available_externally anyway.
17222     if (!DefineVTable) {
17223       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17224       continue;
17225     }
17226 
17227     // Mark all of the virtual members of this class as referenced, so
17228     // that we can build a vtable. Then, tell the AST consumer that a
17229     // vtable for this class is required.
17230     DefinedAnything = true;
17231     MarkVirtualMembersReferenced(Loc, Class);
17232     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17233     if (VTablesUsed[Canonical])
17234       Consumer.HandleVTable(Class);
17235 
17236     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17237     // no key function or the key function is inlined. Don't warn in C++ ABIs
17238     // that lack key functions, since the user won't be able to make one.
17239     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17240         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17241       const FunctionDecl *KeyFunctionDef = nullptr;
17242       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17243                            KeyFunctionDef->isInlined())) {
17244         Diag(Class->getLocation(),
17245              ClassTSK == TSK_ExplicitInstantiationDefinition
17246                  ? diag::warn_weak_template_vtable
17247                  : diag::warn_weak_vtable)
17248             << Class;
17249       }
17250     }
17251   }
17252   VTableUses.clear();
17253 
17254   return DefinedAnything;
17255 }
17256 
17257 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17258                                                  const CXXRecordDecl *RD) {
17259   for (const auto *I : RD->methods())
17260     if (I->isVirtual() && !I->isPure())
17261       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17262 }
17263 
17264 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17265                                         const CXXRecordDecl *RD,
17266                                         bool ConstexprOnly) {
17267   // Mark all functions which will appear in RD's vtable as used.
17268   CXXFinalOverriderMap FinalOverriders;
17269   RD->getFinalOverriders(FinalOverriders);
17270   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17271                                             E = FinalOverriders.end();
17272        I != E; ++I) {
17273     for (OverridingMethods::const_iterator OI = I->second.begin(),
17274                                            OE = I->second.end();
17275          OI != OE; ++OI) {
17276       assert(OI->second.size() > 0 && "no final overrider");
17277       CXXMethodDecl *Overrider = OI->second.front().Method;
17278 
17279       // C++ [basic.def.odr]p2:
17280       //   [...] A virtual member function is used if it is not pure. [...]
17281       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17282         MarkFunctionReferenced(Loc, Overrider);
17283     }
17284   }
17285 
17286   // Only classes that have virtual bases need a VTT.
17287   if (RD->getNumVBases() == 0)
17288     return;
17289 
17290   for (const auto &I : RD->bases()) {
17291     const auto *Base =
17292         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17293     if (Base->getNumVBases() == 0)
17294       continue;
17295     MarkVirtualMembersReferenced(Loc, Base);
17296   }
17297 }
17298 
17299 /// SetIvarInitializers - This routine builds initialization ASTs for the
17300 /// Objective-C implementation whose ivars need be initialized.
17301 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17302   if (!getLangOpts().CPlusPlus)
17303     return;
17304   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17305     SmallVector<ObjCIvarDecl*, 8> ivars;
17306     CollectIvarsToConstructOrDestruct(OID, ivars);
17307     if (ivars.empty())
17308       return;
17309     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17310     for (unsigned i = 0; i < ivars.size(); i++) {
17311       FieldDecl *Field = ivars[i];
17312       if (Field->isInvalidDecl())
17313         continue;
17314 
17315       CXXCtorInitializer *Member;
17316       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17317       InitializationKind InitKind =
17318         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17319 
17320       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17321       ExprResult MemberInit =
17322         InitSeq.Perform(*this, InitEntity, InitKind, None);
17323       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17324       // Note, MemberInit could actually come back empty if no initialization
17325       // is required (e.g., because it would call a trivial default constructor)
17326       if (!MemberInit.get() || MemberInit.isInvalid())
17327         continue;
17328 
17329       Member =
17330         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17331                                          SourceLocation(),
17332                                          MemberInit.getAs<Expr>(),
17333                                          SourceLocation());
17334       AllToInit.push_back(Member);
17335 
17336       // Be sure that the destructor is accessible and is marked as referenced.
17337       if (const RecordType *RecordTy =
17338               Context.getBaseElementType(Field->getType())
17339                   ->getAs<RecordType>()) {
17340         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17341         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17342           MarkFunctionReferenced(Field->getLocation(), Destructor);
17343           CheckDestructorAccess(Field->getLocation(), Destructor,
17344                             PDiag(diag::err_access_dtor_ivar)
17345                               << Context.getBaseElementType(Field->getType()));
17346         }
17347       }
17348     }
17349     ObjCImplementation->setIvarInitializers(Context,
17350                                             AllToInit.data(), AllToInit.size());
17351   }
17352 }
17353 
17354 static
17355 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17356                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17357                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17358                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17359                            Sema &S) {
17360   if (Ctor->isInvalidDecl())
17361     return;
17362 
17363   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17364 
17365   // Target may not be determinable yet, for instance if this is a dependent
17366   // call in an uninstantiated template.
17367   if (Target) {
17368     const FunctionDecl *FNTarget = nullptr;
17369     (void)Target->hasBody(FNTarget);
17370     Target = const_cast<CXXConstructorDecl*>(
17371       cast_or_null<CXXConstructorDecl>(FNTarget));
17372   }
17373 
17374   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17375                      // Avoid dereferencing a null pointer here.
17376                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17377 
17378   if (!Current.insert(Canonical).second)
17379     return;
17380 
17381   // We know that beyond here, we aren't chaining into a cycle.
17382   if (!Target || !Target->isDelegatingConstructor() ||
17383       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17384     Valid.insert(Current.begin(), Current.end());
17385     Current.clear();
17386   // We've hit a cycle.
17387   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17388              Current.count(TCanonical)) {
17389     // If we haven't diagnosed this cycle yet, do so now.
17390     if (!Invalid.count(TCanonical)) {
17391       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17392              diag::warn_delegating_ctor_cycle)
17393         << Ctor;
17394 
17395       // Don't add a note for a function delegating directly to itself.
17396       if (TCanonical != Canonical)
17397         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17398 
17399       CXXConstructorDecl *C = Target;
17400       while (C->getCanonicalDecl() != Canonical) {
17401         const FunctionDecl *FNTarget = nullptr;
17402         (void)C->getTargetConstructor()->hasBody(FNTarget);
17403         assert(FNTarget && "Ctor cycle through bodiless function");
17404 
17405         C = const_cast<CXXConstructorDecl*>(
17406           cast<CXXConstructorDecl>(FNTarget));
17407         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17408       }
17409     }
17410 
17411     Invalid.insert(Current.begin(), Current.end());
17412     Current.clear();
17413   } else {
17414     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17415   }
17416 }
17417 
17418 
17419 void Sema::CheckDelegatingCtorCycles() {
17420   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17421 
17422   for (DelegatingCtorDeclsType::iterator
17423          I = DelegatingCtorDecls.begin(ExternalSource),
17424          E = DelegatingCtorDecls.end();
17425        I != E; ++I)
17426     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17427 
17428   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17429     (*CI)->setInvalidDecl();
17430 }
17431 
17432 namespace {
17433   /// AST visitor that finds references to the 'this' expression.
17434   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17435     Sema &S;
17436 
17437   public:
17438     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17439 
17440     bool VisitCXXThisExpr(CXXThisExpr *E) {
17441       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17442         << E->isImplicit();
17443       return false;
17444     }
17445   };
17446 }
17447 
17448 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17449   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17450   if (!TSInfo)
17451     return false;
17452 
17453   TypeLoc TL = TSInfo->getTypeLoc();
17454   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17455   if (!ProtoTL)
17456     return false;
17457 
17458   // C++11 [expr.prim.general]p3:
17459   //   [The expression this] shall not appear before the optional
17460   //   cv-qualifier-seq and it shall not appear within the declaration of a
17461   //   static member function (although its type and value category are defined
17462   //   within a static member function as they are within a non-static member
17463   //   function). [ Note: this is because declaration matching does not occur
17464   //  until the complete declarator is known. - end note ]
17465   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17466   FindCXXThisExpr Finder(*this);
17467 
17468   // If the return type came after the cv-qualifier-seq, check it now.
17469   if (Proto->hasTrailingReturn() &&
17470       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17471     return true;
17472 
17473   // Check the exception specification.
17474   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17475     return true;
17476 
17477   // Check the trailing requires clause
17478   if (Expr *E = Method->getTrailingRequiresClause())
17479     if (!Finder.TraverseStmt(E))
17480       return true;
17481 
17482   return checkThisInStaticMemberFunctionAttributes(Method);
17483 }
17484 
17485 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17486   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17487   if (!TSInfo)
17488     return false;
17489 
17490   TypeLoc TL = TSInfo->getTypeLoc();
17491   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17492   if (!ProtoTL)
17493     return false;
17494 
17495   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17496   FindCXXThisExpr Finder(*this);
17497 
17498   switch (Proto->getExceptionSpecType()) {
17499   case EST_Unparsed:
17500   case EST_Uninstantiated:
17501   case EST_Unevaluated:
17502   case EST_BasicNoexcept:
17503   case EST_NoThrow:
17504   case EST_DynamicNone:
17505   case EST_MSAny:
17506   case EST_None:
17507     break;
17508 
17509   case EST_DependentNoexcept:
17510   case EST_NoexceptFalse:
17511   case EST_NoexceptTrue:
17512     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17513       return true;
17514     LLVM_FALLTHROUGH;
17515 
17516   case EST_Dynamic:
17517     for (const auto &E : Proto->exceptions()) {
17518       if (!Finder.TraverseType(E))
17519         return true;
17520     }
17521     break;
17522   }
17523 
17524   return false;
17525 }
17526 
17527 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17528   FindCXXThisExpr Finder(*this);
17529 
17530   // Check attributes.
17531   for (const auto *A : Method->attrs()) {
17532     // FIXME: This should be emitted by tblgen.
17533     Expr *Arg = nullptr;
17534     ArrayRef<Expr *> Args;
17535     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17536       Arg = G->getArg();
17537     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17538       Arg = G->getArg();
17539     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17540       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17541     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17542       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17543     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17544       Arg = ETLF->getSuccessValue();
17545       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17546     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17547       Arg = STLF->getSuccessValue();
17548       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17549     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17550       Arg = LR->getArg();
17551     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17552       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17553     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17554       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17555     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17556       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17557     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17558       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17559     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17560       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17561 
17562     if (Arg && !Finder.TraverseStmt(Arg))
17563       return true;
17564 
17565     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17566       if (!Finder.TraverseStmt(Args[I]))
17567         return true;
17568     }
17569   }
17570 
17571   return false;
17572 }
17573 
17574 void Sema::checkExceptionSpecification(
17575     bool IsTopLevel, ExceptionSpecificationType EST,
17576     ArrayRef<ParsedType> DynamicExceptions,
17577     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17578     SmallVectorImpl<QualType> &Exceptions,
17579     FunctionProtoType::ExceptionSpecInfo &ESI) {
17580   Exceptions.clear();
17581   ESI.Type = EST;
17582   if (EST == EST_Dynamic) {
17583     Exceptions.reserve(DynamicExceptions.size());
17584     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17585       // FIXME: Preserve type source info.
17586       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17587 
17588       if (IsTopLevel) {
17589         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17590         collectUnexpandedParameterPacks(ET, Unexpanded);
17591         if (!Unexpanded.empty()) {
17592           DiagnoseUnexpandedParameterPacks(
17593               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17594               Unexpanded);
17595           continue;
17596         }
17597       }
17598 
17599       // Check that the type is valid for an exception spec, and
17600       // drop it if not.
17601       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17602         Exceptions.push_back(ET);
17603     }
17604     ESI.Exceptions = Exceptions;
17605     return;
17606   }
17607 
17608   if (isComputedNoexcept(EST)) {
17609     assert((NoexceptExpr->isTypeDependent() ||
17610             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17611             Context.BoolTy) &&
17612            "Parser should have made sure that the expression is boolean");
17613     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17614       ESI.Type = EST_BasicNoexcept;
17615       return;
17616     }
17617 
17618     ESI.NoexceptExpr = NoexceptExpr;
17619     return;
17620   }
17621 }
17622 
17623 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17624              ExceptionSpecificationType EST,
17625              SourceRange SpecificationRange,
17626              ArrayRef<ParsedType> DynamicExceptions,
17627              ArrayRef<SourceRange> DynamicExceptionRanges,
17628              Expr *NoexceptExpr) {
17629   if (!MethodD)
17630     return;
17631 
17632   // Dig out the method we're referring to.
17633   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17634     MethodD = FunTmpl->getTemplatedDecl();
17635 
17636   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17637   if (!Method)
17638     return;
17639 
17640   // Check the exception specification.
17641   llvm::SmallVector<QualType, 4> Exceptions;
17642   FunctionProtoType::ExceptionSpecInfo ESI;
17643   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17644                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17645                               ESI);
17646 
17647   // Update the exception specification on the function type.
17648   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17649 
17650   if (Method->isStatic())
17651     checkThisInStaticMemberFunctionExceptionSpec(Method);
17652 
17653   if (Method->isVirtual()) {
17654     // Check overrides, which we previously had to delay.
17655     for (const CXXMethodDecl *O : Method->overridden_methods())
17656       CheckOverridingFunctionExceptionSpec(Method, O);
17657   }
17658 }
17659 
17660 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17661 ///
17662 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17663                                        SourceLocation DeclStart, Declarator &D,
17664                                        Expr *BitWidth,
17665                                        InClassInitStyle InitStyle,
17666                                        AccessSpecifier AS,
17667                                        const ParsedAttr &MSPropertyAttr) {
17668   IdentifierInfo *II = D.getIdentifier();
17669   if (!II) {
17670     Diag(DeclStart, diag::err_anonymous_property);
17671     return nullptr;
17672   }
17673   SourceLocation Loc = D.getIdentifierLoc();
17674 
17675   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17676   QualType T = TInfo->getType();
17677   if (getLangOpts().CPlusPlus) {
17678     CheckExtraCXXDefaultArguments(D);
17679 
17680     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17681                                         UPPC_DataMemberType)) {
17682       D.setInvalidType();
17683       T = Context.IntTy;
17684       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17685     }
17686   }
17687 
17688   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17689 
17690   if (D.getDeclSpec().isInlineSpecified())
17691     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17692         << getLangOpts().CPlusPlus17;
17693   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17694     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17695          diag::err_invalid_thread)
17696       << DeclSpec::getSpecifierName(TSCS);
17697 
17698   // Check to see if this name was declared as a member previously
17699   NamedDecl *PrevDecl = nullptr;
17700   LookupResult Previous(*this, II, Loc, LookupMemberName,
17701                         ForVisibleRedeclaration);
17702   LookupName(Previous, S);
17703   switch (Previous.getResultKind()) {
17704   case LookupResult::Found:
17705   case LookupResult::FoundUnresolvedValue:
17706     PrevDecl = Previous.getAsSingle<NamedDecl>();
17707     break;
17708 
17709   case LookupResult::FoundOverloaded:
17710     PrevDecl = Previous.getRepresentativeDecl();
17711     break;
17712 
17713   case LookupResult::NotFound:
17714   case LookupResult::NotFoundInCurrentInstantiation:
17715   case LookupResult::Ambiguous:
17716     break;
17717   }
17718 
17719   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17720     // Maybe we will complain about the shadowed template parameter.
17721     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17722     // Just pretend that we didn't see the previous declaration.
17723     PrevDecl = nullptr;
17724   }
17725 
17726   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17727     PrevDecl = nullptr;
17728 
17729   SourceLocation TSSL = D.getBeginLoc();
17730   MSPropertyDecl *NewPD =
17731       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17732                              MSPropertyAttr.getPropertyDataGetter(),
17733                              MSPropertyAttr.getPropertyDataSetter());
17734   ProcessDeclAttributes(TUScope, NewPD, D);
17735   NewPD->setAccess(AS);
17736 
17737   if (NewPD->isInvalidDecl())
17738     Record->setInvalidDecl();
17739 
17740   if (D.getDeclSpec().isModulePrivateSpecified())
17741     NewPD->setModulePrivate();
17742 
17743   if (NewPD->isInvalidDecl() && PrevDecl) {
17744     // Don't introduce NewFD into scope; there's already something
17745     // with the same name in the same scope.
17746   } else if (II) {
17747     PushOnScopeChains(NewPD, S);
17748   } else
17749     Record->addDecl(NewPD);
17750 
17751   return NewPD;
17752 }
17753 
17754 void Sema::ActOnStartFunctionDeclarationDeclarator(
17755     Declarator &Declarator, unsigned TemplateParameterDepth) {
17756   auto &Info = InventedParameterInfos.emplace_back();
17757   TemplateParameterList *ExplicitParams = nullptr;
17758   ArrayRef<TemplateParameterList *> ExplicitLists =
17759       Declarator.getTemplateParameterLists();
17760   if (!ExplicitLists.empty()) {
17761     bool IsMemberSpecialization, IsInvalid;
17762     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17763         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17764         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17765         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17766         /*SuppressDiagnostic=*/true);
17767   }
17768   if (ExplicitParams) {
17769     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17770     for (NamedDecl *Param : *ExplicitParams)
17771       Info.TemplateParams.push_back(Param);
17772     Info.NumExplicitTemplateParams = ExplicitParams->size();
17773   } else {
17774     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17775     Info.NumExplicitTemplateParams = 0;
17776   }
17777 }
17778 
17779 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17780   auto &FSI = InventedParameterInfos.back();
17781   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17782     if (FSI.NumExplicitTemplateParams != 0) {
17783       TemplateParameterList *ExplicitParams =
17784           Declarator.getTemplateParameterLists().back();
17785       Declarator.setInventedTemplateParameterList(
17786           TemplateParameterList::Create(
17787               Context, ExplicitParams->getTemplateLoc(),
17788               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17789               ExplicitParams->getRAngleLoc(),
17790               ExplicitParams->getRequiresClause()));
17791     } else {
17792       Declarator.setInventedTemplateParameterList(
17793           TemplateParameterList::Create(
17794               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17795               SourceLocation(), /*RequiresClause=*/nullptr));
17796     }
17797   }
17798   InventedParameterInfos.pop_back();
17799 }
17800