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     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1070                                                SourceLocation Loc) override {
1071       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1072           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1073     }
1074   } Diagnoser(R, Args);
1075 
1076   ExprResult E =
1077       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1078   if (E.isInvalid())
1079     return IsTupleLike::Error;
1080 
1081   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1082   if (E.isInvalid())
1083     return IsTupleLike::Error;
1084 
1085   return IsTupleLike::TupleLike;
1086 }
1087 
1088 /// \return std::tuple_element<I, T>::type.
1089 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1090                                         unsigned I, QualType T) {
1091   // Form template argument list for tuple_element<I, T>.
1092   TemplateArgumentListInfo Args(Loc, Loc);
1093   Args.addArgument(
1094       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1095   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1096 
1097   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1098   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1099   if (lookupStdTypeTraitMember(
1100           S, R, Loc, "tuple_element", Args,
1101           diag::err_decomp_decl_std_tuple_element_not_specialized))
1102     return QualType();
1103 
1104   auto *TD = R.getAsSingle<TypeDecl>();
1105   if (!TD) {
1106     R.suppressDiagnostics();
1107     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1108       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1109     if (!R.empty())
1110       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1111     return QualType();
1112   }
1113 
1114   return S.Context.getTypeDeclType(TD);
1115 }
1116 
1117 namespace {
1118 struct InitializingBinding {
1119   Sema &S;
1120   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1121     Sema::CodeSynthesisContext Ctx;
1122     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1123     Ctx.PointOfInstantiation = BD->getLocation();
1124     Ctx.Entity = BD;
1125     S.pushCodeSynthesisContext(Ctx);
1126   }
1127   ~InitializingBinding() {
1128     S.popCodeSynthesisContext();
1129   }
1130 };
1131 }
1132 
1133 static bool checkTupleLikeDecomposition(Sema &S,
1134                                         ArrayRef<BindingDecl *> Bindings,
1135                                         VarDecl *Src, QualType DecompType,
1136                                         const llvm::APSInt &TupleSize) {
1137   if ((int64_t)Bindings.size() != TupleSize) {
1138     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1139         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1140         << (TupleSize < Bindings.size());
1141     return true;
1142   }
1143 
1144   if (Bindings.empty())
1145     return false;
1146 
1147   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1148 
1149   // [dcl.decomp]p3:
1150   //   The unqualified-id get is looked up in the scope of E by class member
1151   //   access lookup ...
1152   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1153   bool UseMemberGet = false;
1154   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1155     if (auto *RD = DecompType->getAsCXXRecordDecl())
1156       S.LookupQualifiedName(MemberGet, RD);
1157     if (MemberGet.isAmbiguous())
1158       return true;
1159     //   ... and if that finds at least one declaration that is a function
1160     //   template whose first template parameter is a non-type parameter ...
1161     for (NamedDecl *D : MemberGet) {
1162       if (FunctionTemplateDecl *FTD =
1163               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1164         TemplateParameterList *TPL = FTD->getTemplateParameters();
1165         if (TPL->size() != 0 &&
1166             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1167           //   ... the initializer is e.get<i>().
1168           UseMemberGet = true;
1169           break;
1170         }
1171       }
1172     }
1173   }
1174 
1175   unsigned I = 0;
1176   for (auto *B : Bindings) {
1177     InitializingBinding InitContext(S, B);
1178     SourceLocation Loc = B->getLocation();
1179 
1180     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1181     if (E.isInvalid())
1182       return true;
1183 
1184     //   e is an lvalue if the type of the entity is an lvalue reference and
1185     //   an xvalue otherwise
1186     if (!Src->getType()->isLValueReferenceType())
1187       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1188                                    E.get(), nullptr, VK_XValue,
1189                                    FPOptionsOverride());
1190 
1191     TemplateArgumentListInfo Args(Loc, Loc);
1192     Args.addArgument(
1193         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1194 
1195     if (UseMemberGet) {
1196       //   if [lookup of member get] finds at least one declaration, the
1197       //   initializer is e.get<i-1>().
1198       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1199                                      CXXScopeSpec(), SourceLocation(), nullptr,
1200                                      MemberGet, &Args, nullptr);
1201       if (E.isInvalid())
1202         return true;
1203 
1204       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1205     } else {
1206       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1207       //   in the associated namespaces.
1208       Expr *Get = UnresolvedLookupExpr::Create(
1209           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1210           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1211           UnresolvedSetIterator(), UnresolvedSetIterator());
1212 
1213       Expr *Arg = E.get();
1214       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1215     }
1216     if (E.isInvalid())
1217       return true;
1218     Expr *Init = E.get();
1219 
1220     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1221     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1222     if (T.isNull())
1223       return true;
1224 
1225     //   each vi is a variable of type "reference to T" initialized with the
1226     //   initializer, where the reference is an lvalue reference if the
1227     //   initializer is an lvalue and an rvalue reference otherwise
1228     QualType RefType =
1229         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1230     if (RefType.isNull())
1231       return true;
1232     auto *RefVD = VarDecl::Create(
1233         S.Context, Src->getDeclContext(), Loc, Loc,
1234         B->getDeclName().getAsIdentifierInfo(), RefType,
1235         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1236     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1237     RefVD->setTSCSpec(Src->getTSCSpec());
1238     RefVD->setImplicit();
1239     if (Src->isInlineSpecified())
1240       RefVD->setInlineSpecified();
1241     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1242 
1243     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1244     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1245     InitializationSequence Seq(S, Entity, Kind, Init);
1246     E = Seq.Perform(S, Entity, Kind, Init);
1247     if (E.isInvalid())
1248       return true;
1249     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1250     if (E.isInvalid())
1251       return true;
1252     RefVD->setInit(E.get());
1253     if (!E.get()->isValueDependent())
1254       RefVD->checkInitIsICE();
1255 
1256     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1257                                    DeclarationNameInfo(B->getDeclName(), Loc),
1258                                    RefVD);
1259     if (E.isInvalid())
1260       return true;
1261 
1262     B->setBinding(T, E.get());
1263     I++;
1264   }
1265 
1266   return false;
1267 }
1268 
1269 /// Find the base class to decompose in a built-in decomposition of a class type.
1270 /// This base class search is, unfortunately, not quite like any other that we
1271 /// perform anywhere else in C++.
1272 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1273                                                 const CXXRecordDecl *RD,
1274                                                 CXXCastPath &BasePath) {
1275   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1276                           CXXBasePath &Path) {
1277     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1278   };
1279 
1280   const CXXRecordDecl *ClassWithFields = nullptr;
1281   AccessSpecifier AS = AS_public;
1282   if (RD->hasDirectFields())
1283     // [dcl.decomp]p4:
1284     //   Otherwise, all of E's non-static data members shall be public direct
1285     //   members of E ...
1286     ClassWithFields = RD;
1287   else {
1288     //   ... or of ...
1289     CXXBasePaths Paths;
1290     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1291     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1292       // If no classes have fields, just decompose RD itself. (This will work
1293       // if and only if zero bindings were provided.)
1294       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1295     }
1296 
1297     CXXBasePath *BestPath = nullptr;
1298     for (auto &P : Paths) {
1299       if (!BestPath)
1300         BestPath = &P;
1301       else if (!S.Context.hasSameType(P.back().Base->getType(),
1302                                       BestPath->back().Base->getType())) {
1303         //   ... the same ...
1304         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1305           << false << RD << BestPath->back().Base->getType()
1306           << P.back().Base->getType();
1307         return DeclAccessPair();
1308       } else if (P.Access < BestPath->Access) {
1309         BestPath = &P;
1310       }
1311     }
1312 
1313     //   ... unambiguous ...
1314     QualType BaseType = BestPath->back().Base->getType();
1315     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1316       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1317         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1318       return DeclAccessPair();
1319     }
1320 
1321     //   ... [accessible, implied by other rules] base class of E.
1322     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1323                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1324     AS = BestPath->Access;
1325 
1326     ClassWithFields = BaseType->getAsCXXRecordDecl();
1327     S.BuildBasePathArray(Paths, BasePath);
1328   }
1329 
1330   // The above search did not check whether the selected class itself has base
1331   // classes with fields, so check that now.
1332   CXXBasePaths Paths;
1333   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1334     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1335       << (ClassWithFields == RD) << RD << ClassWithFields
1336       << Paths.front().back().Base->getType();
1337     return DeclAccessPair();
1338   }
1339 
1340   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1341 }
1342 
1343 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1344                                      ValueDecl *Src, QualType DecompType,
1345                                      const CXXRecordDecl *OrigRD) {
1346   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1347                             diag::err_incomplete_type))
1348     return true;
1349 
1350   CXXCastPath BasePath;
1351   DeclAccessPair BasePair =
1352       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1353   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1354   if (!RD)
1355     return true;
1356   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1357                                                  DecompType.getQualifiers());
1358 
1359   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1360     unsigned NumFields =
1361         std::count_if(RD->field_begin(), RD->field_end(),
1362                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1363     assert(Bindings.size() != NumFields);
1364     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1365         << DecompType << (unsigned)Bindings.size() << NumFields
1366         << (NumFields < Bindings.size());
1367     return true;
1368   };
1369 
1370   //   all of E's non-static data members shall be [...] well-formed
1371   //   when named as e.name in the context of the structured binding,
1372   //   E shall not have an anonymous union member, ...
1373   unsigned I = 0;
1374   for (auto *FD : RD->fields()) {
1375     if (FD->isUnnamedBitfield())
1376       continue;
1377 
1378     if (FD->isAnonymousStructOrUnion()) {
1379       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1380         << DecompType << FD->getType()->isUnionType();
1381       S.Diag(FD->getLocation(), diag::note_declared_at);
1382       return true;
1383     }
1384 
1385     // We have a real field to bind.
1386     if (I >= Bindings.size())
1387       return DiagnoseBadNumberOfBindings();
1388     auto *B = Bindings[I++];
1389     SourceLocation Loc = B->getLocation();
1390 
1391     // The field must be accessible in the context of the structured binding.
1392     // We already checked that the base class is accessible.
1393     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1394     // const_cast here.
1395     S.CheckStructuredBindingMemberAccess(
1396         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1397         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1398                                      BasePair.getAccess(), FD->getAccess())));
1399 
1400     // Initialize the binding to Src.FD.
1401     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1402     if (E.isInvalid())
1403       return true;
1404     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1405                             VK_LValue, &BasePath);
1406     if (E.isInvalid())
1407       return true;
1408     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1409                                   CXXScopeSpec(), FD,
1410                                   DeclAccessPair::make(FD, FD->getAccess()),
1411                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1412     if (E.isInvalid())
1413       return true;
1414 
1415     // If the type of the member is T, the referenced type is cv T, where cv is
1416     // the cv-qualification of the decomposition expression.
1417     //
1418     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1419     // 'const' to the type of the field.
1420     Qualifiers Q = DecompType.getQualifiers();
1421     if (FD->isMutable())
1422       Q.removeConst();
1423     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1424   }
1425 
1426   if (I != Bindings.size())
1427     return DiagnoseBadNumberOfBindings();
1428 
1429   return false;
1430 }
1431 
1432 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1433   QualType DecompType = DD->getType();
1434 
1435   // If the type of the decomposition is dependent, then so is the type of
1436   // each binding.
1437   if (DecompType->isDependentType()) {
1438     for (auto *B : DD->bindings())
1439       B->setType(Context.DependentTy);
1440     return;
1441   }
1442 
1443   DecompType = DecompType.getNonReferenceType();
1444   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1445 
1446   // C++1z [dcl.decomp]/2:
1447   //   If E is an array type [...]
1448   // As an extension, we also support decomposition of built-in complex and
1449   // vector types.
1450   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1451     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1452       DD->setInvalidDecl();
1453     return;
1454   }
1455   if (auto *VT = DecompType->getAs<VectorType>()) {
1456     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1457       DD->setInvalidDecl();
1458     return;
1459   }
1460   if (auto *CT = DecompType->getAs<ComplexType>()) {
1461     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1462       DD->setInvalidDecl();
1463     return;
1464   }
1465 
1466   // C++1z [dcl.decomp]/3:
1467   //   if the expression std::tuple_size<E>::value is a well-formed integral
1468   //   constant expression, [...]
1469   llvm::APSInt TupleSize(32);
1470   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1471   case IsTupleLike::Error:
1472     DD->setInvalidDecl();
1473     return;
1474 
1475   case IsTupleLike::TupleLike:
1476     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1477       DD->setInvalidDecl();
1478     return;
1479 
1480   case IsTupleLike::NotTupleLike:
1481     break;
1482   }
1483 
1484   // C++1z [dcl.dcl]/8:
1485   //   [E shall be of array or non-union class type]
1486   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1487   if (!RD || RD->isUnion()) {
1488     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1489         << DD << !RD << DecompType;
1490     DD->setInvalidDecl();
1491     return;
1492   }
1493 
1494   // C++1z [dcl.decomp]/4:
1495   //   all of E's non-static data members shall be [...] direct members of
1496   //   E or of the same unambiguous public base class of E, ...
1497   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1498     DD->setInvalidDecl();
1499 }
1500 
1501 /// Merge the exception specifications of two variable declarations.
1502 ///
1503 /// This is called when there's a redeclaration of a VarDecl. The function
1504 /// checks if the redeclaration might have an exception specification and
1505 /// validates compatibility and merges the specs if necessary.
1506 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1507   // Shortcut if exceptions are disabled.
1508   if (!getLangOpts().CXXExceptions)
1509     return;
1510 
1511   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1512          "Should only be called if types are otherwise the same.");
1513 
1514   QualType NewType = New->getType();
1515   QualType OldType = Old->getType();
1516 
1517   // We're only interested in pointers and references to functions, as well
1518   // as pointers to member functions.
1519   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1520     NewType = R->getPointeeType();
1521     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1522   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1523     NewType = P->getPointeeType();
1524     OldType = OldType->castAs<PointerType>()->getPointeeType();
1525   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1526     NewType = M->getPointeeType();
1527     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1528   }
1529 
1530   if (!NewType->isFunctionProtoType())
1531     return;
1532 
1533   // There's lots of special cases for functions. For function pointers, system
1534   // libraries are hopefully not as broken so that we don't need these
1535   // workarounds.
1536   if (CheckEquivalentExceptionSpec(
1537         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1538         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1539     New->setInvalidDecl();
1540   }
1541 }
1542 
1543 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1544 /// function declaration are well-formed according to C++
1545 /// [dcl.fct.default].
1546 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1547   unsigned NumParams = FD->getNumParams();
1548   unsigned ParamIdx = 0;
1549 
1550   // This checking doesn't make sense for explicit specializations; their
1551   // default arguments are determined by the declaration we're specializing,
1552   // not by FD.
1553   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1554     return;
1555   if (auto *FTD = FD->getDescribedFunctionTemplate())
1556     if (FTD->isMemberSpecialization())
1557       return;
1558 
1559   // Find first parameter with a default argument
1560   for (; ParamIdx < NumParams; ++ParamIdx) {
1561     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1562     if (Param->hasDefaultArg())
1563       break;
1564   }
1565 
1566   // C++20 [dcl.fct.default]p4:
1567   //   In a given function declaration, each parameter subsequent to a parameter
1568   //   with a default argument shall have a default argument supplied in this or
1569   //   a previous declaration, unless the parameter was expanded from a
1570   //   parameter pack, or shall be a function parameter pack.
1571   for (; ParamIdx < NumParams; ++ParamIdx) {
1572     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1573     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1574         !(CurrentInstantiationScope &&
1575           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1576       if (Param->isInvalidDecl())
1577         /* We already complained about this parameter. */;
1578       else if (Param->getIdentifier())
1579         Diag(Param->getLocation(),
1580              diag::err_param_default_argument_missing_name)
1581           << Param->getIdentifier();
1582       else
1583         Diag(Param->getLocation(),
1584              diag::err_param_default_argument_missing);
1585     }
1586   }
1587 }
1588 
1589 /// Check that the given type is a literal type. Issue a diagnostic if not,
1590 /// if Kind is Diagnose.
1591 /// \return \c true if a problem has been found (and optionally diagnosed).
1592 template <typename... Ts>
1593 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1594                              SourceLocation Loc, QualType T, unsigned DiagID,
1595                              Ts &&...DiagArgs) {
1596   if (T->isDependentType())
1597     return false;
1598 
1599   switch (Kind) {
1600   case Sema::CheckConstexprKind::Diagnose:
1601     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1602                                       std::forward<Ts>(DiagArgs)...);
1603 
1604   case Sema::CheckConstexprKind::CheckValid:
1605     return !T->isLiteralType(SemaRef.Context);
1606   }
1607 
1608   llvm_unreachable("unknown CheckConstexprKind");
1609 }
1610 
1611 /// Determine whether a destructor cannot be constexpr due to
1612 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1613                                                const CXXDestructorDecl *DD,
1614                                                Sema::CheckConstexprKind Kind) {
1615   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1616     const CXXRecordDecl *RD =
1617         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1618     if (!RD || RD->hasConstexprDestructor())
1619       return true;
1620 
1621     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1622       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1623           << DD->getConstexprKind() << !FD
1624           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1625       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1626           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1627     }
1628     return false;
1629   };
1630 
1631   const CXXRecordDecl *RD = DD->getParent();
1632   for (const CXXBaseSpecifier &B : RD->bases())
1633     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1634       return false;
1635   for (const FieldDecl *FD : RD->fields())
1636     if (!Check(FD->getLocation(), FD->getType(), FD))
1637       return false;
1638   return true;
1639 }
1640 
1641 /// Check whether a function's parameter types are all literal types. If so,
1642 /// return true. If not, produce a suitable diagnostic and return false.
1643 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1644                                          const FunctionDecl *FD,
1645                                          Sema::CheckConstexprKind Kind) {
1646   unsigned ArgIndex = 0;
1647   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1648   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1649                                               e = FT->param_type_end();
1650        i != e; ++i, ++ArgIndex) {
1651     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1652     SourceLocation ParamLoc = PD->getLocation();
1653     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1654                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1655                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1656                          FD->isConsteval()))
1657       return false;
1658   }
1659   return true;
1660 }
1661 
1662 /// Check whether a function's return type is a literal type. If so, return
1663 /// true. If not, produce a suitable diagnostic and return false.
1664 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1665                                      Sema::CheckConstexprKind Kind) {
1666   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1667                        diag::err_constexpr_non_literal_return,
1668                        FD->isConsteval()))
1669     return false;
1670   return true;
1671 }
1672 
1673 /// Get diagnostic %select index for tag kind for
1674 /// record diagnostic message.
1675 /// WARNING: Indexes apply to particular diagnostics only!
1676 ///
1677 /// \returns diagnostic %select index.
1678 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1679   switch (Tag) {
1680   case TTK_Struct: return 0;
1681   case TTK_Interface: return 1;
1682   case TTK_Class:  return 2;
1683   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1684   }
1685 }
1686 
1687 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1688                                        Stmt *Body,
1689                                        Sema::CheckConstexprKind Kind);
1690 
1691 // Check whether a function declaration satisfies the requirements of a
1692 // constexpr function definition or a constexpr constructor definition. If so,
1693 // return true. If not, produce appropriate diagnostics (unless asked not to by
1694 // Kind) and return false.
1695 //
1696 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1697 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1698                                             CheckConstexprKind Kind) {
1699   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1700   if (MD && MD->isInstance()) {
1701     // C++11 [dcl.constexpr]p4:
1702     //  The definition of a constexpr constructor shall satisfy the following
1703     //  constraints:
1704     //  - the class shall not have any virtual base classes;
1705     //
1706     // FIXME: This only applies to constructors and destructors, not arbitrary
1707     // member functions.
1708     const CXXRecordDecl *RD = MD->getParent();
1709     if (RD->getNumVBases()) {
1710       if (Kind == CheckConstexprKind::CheckValid)
1711         return false;
1712 
1713       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1714         << isa<CXXConstructorDecl>(NewFD)
1715         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1716       for (const auto &I : RD->vbases())
1717         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1718             << I.getSourceRange();
1719       return false;
1720     }
1721   }
1722 
1723   if (!isa<CXXConstructorDecl>(NewFD)) {
1724     // C++11 [dcl.constexpr]p3:
1725     //  The definition of a constexpr function shall satisfy the following
1726     //  constraints:
1727     // - it shall not be virtual; (removed in C++20)
1728     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1729     if (Method && Method->isVirtual()) {
1730       if (getLangOpts().CPlusPlus20) {
1731         if (Kind == CheckConstexprKind::Diagnose)
1732           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1733       } else {
1734         if (Kind == CheckConstexprKind::CheckValid)
1735           return false;
1736 
1737         Method = Method->getCanonicalDecl();
1738         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1739 
1740         // If it's not obvious why this function is virtual, find an overridden
1741         // function which uses the 'virtual' keyword.
1742         const CXXMethodDecl *WrittenVirtual = Method;
1743         while (!WrittenVirtual->isVirtualAsWritten())
1744           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1745         if (WrittenVirtual != Method)
1746           Diag(WrittenVirtual->getLocation(),
1747                diag::note_overridden_virtual_function);
1748         return false;
1749       }
1750     }
1751 
1752     // - its return type shall be a literal type;
1753     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1754       return false;
1755   }
1756 
1757   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1758     // A destructor can be constexpr only if the defaulted destructor could be;
1759     // we don't need to check the members and bases if we already know they all
1760     // have constexpr destructors.
1761     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1762       if (Kind == CheckConstexprKind::CheckValid)
1763         return false;
1764       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1765         return false;
1766     }
1767   }
1768 
1769   // - each of its parameter types shall be a literal type;
1770   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1771     return false;
1772 
1773   Stmt *Body = NewFD->getBody();
1774   assert(Body &&
1775          "CheckConstexprFunctionDefinition called on function with no body");
1776   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1777 }
1778 
1779 /// Check the given declaration statement is legal within a constexpr function
1780 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1781 ///
1782 /// \return true if the body is OK (maybe only as an extension), false if we
1783 ///         have diagnosed a problem.
1784 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1785                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1786                                    Sema::CheckConstexprKind Kind) {
1787   // C++11 [dcl.constexpr]p3 and p4:
1788   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1789   //  contain only
1790   for (const auto *DclIt : DS->decls()) {
1791     switch (DclIt->getKind()) {
1792     case Decl::StaticAssert:
1793     case Decl::Using:
1794     case Decl::UsingShadow:
1795     case Decl::UsingDirective:
1796     case Decl::UnresolvedUsingTypename:
1797     case Decl::UnresolvedUsingValue:
1798       //   - static_assert-declarations
1799       //   - using-declarations,
1800       //   - using-directives,
1801       continue;
1802 
1803     case Decl::Typedef:
1804     case Decl::TypeAlias: {
1805       //   - typedef declarations and alias-declarations that do not define
1806       //     classes or enumerations,
1807       const auto *TN = cast<TypedefNameDecl>(DclIt);
1808       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1809         // Don't allow variably-modified types in constexpr functions.
1810         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1811           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1812           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1813             << TL.getSourceRange() << TL.getType()
1814             << isa<CXXConstructorDecl>(Dcl);
1815         }
1816         return false;
1817       }
1818       continue;
1819     }
1820 
1821     case Decl::Enum:
1822     case Decl::CXXRecord:
1823       // C++1y allows types to be defined, not just declared.
1824       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1825         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1826           SemaRef.Diag(DS->getBeginLoc(),
1827                        SemaRef.getLangOpts().CPlusPlus14
1828                            ? diag::warn_cxx11_compat_constexpr_type_definition
1829                            : diag::ext_constexpr_type_definition)
1830               << isa<CXXConstructorDecl>(Dcl);
1831         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1832           return false;
1833         }
1834       }
1835       continue;
1836 
1837     case Decl::EnumConstant:
1838     case Decl::IndirectField:
1839     case Decl::ParmVar:
1840       // These can only appear with other declarations which are banned in
1841       // C++11 and permitted in C++1y, so ignore them.
1842       continue;
1843 
1844     case Decl::Var:
1845     case Decl::Decomposition: {
1846       // C++1y [dcl.constexpr]p3 allows anything except:
1847       //   a definition of a variable of non-literal type or of static or
1848       //   thread storage duration or [before C++2a] for which no
1849       //   initialization is performed.
1850       const auto *VD = cast<VarDecl>(DclIt);
1851       if (VD->isThisDeclarationADefinition()) {
1852         if (VD->isStaticLocal()) {
1853           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1854             SemaRef.Diag(VD->getLocation(),
1855                          diag::err_constexpr_local_var_static)
1856               << isa<CXXConstructorDecl>(Dcl)
1857               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1858           }
1859           return false;
1860         }
1861         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1862                              diag::err_constexpr_local_var_non_literal_type,
1863                              isa<CXXConstructorDecl>(Dcl)))
1864           return false;
1865         if (!VD->getType()->isDependentType() &&
1866             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1867           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1868             SemaRef.Diag(
1869                 VD->getLocation(),
1870                 SemaRef.getLangOpts().CPlusPlus20
1871                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1872                     : diag::ext_constexpr_local_var_no_init)
1873                 << isa<CXXConstructorDecl>(Dcl);
1874           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1875             return false;
1876           }
1877           continue;
1878         }
1879       }
1880       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1881         SemaRef.Diag(VD->getLocation(),
1882                      SemaRef.getLangOpts().CPlusPlus14
1883                       ? diag::warn_cxx11_compat_constexpr_local_var
1884                       : diag::ext_constexpr_local_var)
1885           << isa<CXXConstructorDecl>(Dcl);
1886       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1887         return false;
1888       }
1889       continue;
1890     }
1891 
1892     case Decl::NamespaceAlias:
1893     case Decl::Function:
1894       // These are disallowed in C++11 and permitted in C++1y. Allow them
1895       // everywhere as an extension.
1896       if (!Cxx1yLoc.isValid())
1897         Cxx1yLoc = DS->getBeginLoc();
1898       continue;
1899 
1900     default:
1901       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1902         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1903             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1904       }
1905       return false;
1906     }
1907   }
1908 
1909   return true;
1910 }
1911 
1912 /// Check that the given field is initialized within a constexpr constructor.
1913 ///
1914 /// \param Dcl The constexpr constructor being checked.
1915 /// \param Field The field being checked. This may be a member of an anonymous
1916 ///        struct or union nested within the class being checked.
1917 /// \param Inits All declarations, including anonymous struct/union members and
1918 ///        indirect members, for which any initialization was provided.
1919 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1920 ///        multiple notes for different members to the same error.
1921 /// \param Kind Whether we're diagnosing a constructor as written or determining
1922 ///        whether the formal requirements are satisfied.
1923 /// \return \c false if we're checking for validity and the constructor does
1924 ///         not satisfy the requirements on a constexpr constructor.
1925 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1926                                           const FunctionDecl *Dcl,
1927                                           FieldDecl *Field,
1928                                           llvm::SmallSet<Decl*, 16> &Inits,
1929                                           bool &Diagnosed,
1930                                           Sema::CheckConstexprKind Kind) {
1931   // In C++20 onwards, there's nothing to check for validity.
1932   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1933       SemaRef.getLangOpts().CPlusPlus20)
1934     return true;
1935 
1936   if (Field->isInvalidDecl())
1937     return true;
1938 
1939   if (Field->isUnnamedBitfield())
1940     return true;
1941 
1942   // Anonymous unions with no variant members and empty anonymous structs do not
1943   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1944   // indirect fields don't need initializing.
1945   if (Field->isAnonymousStructOrUnion() &&
1946       (Field->getType()->isUnionType()
1947            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1948            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1949     return true;
1950 
1951   if (!Inits.count(Field)) {
1952     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1953       if (!Diagnosed) {
1954         SemaRef.Diag(Dcl->getLocation(),
1955                      SemaRef.getLangOpts().CPlusPlus20
1956                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1957                          : diag::ext_constexpr_ctor_missing_init);
1958         Diagnosed = true;
1959       }
1960       SemaRef.Diag(Field->getLocation(),
1961                    diag::note_constexpr_ctor_missing_init);
1962     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1963       return false;
1964     }
1965   } else if (Field->isAnonymousStructOrUnion()) {
1966     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1967     for (auto *I : RD->fields())
1968       // If an anonymous union contains an anonymous struct of which any member
1969       // is initialized, all members must be initialized.
1970       if (!RD->isUnion() || Inits.count(I))
1971         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1972                                            Kind))
1973           return false;
1974   }
1975   return true;
1976 }
1977 
1978 /// Check the provided statement is allowed in a constexpr function
1979 /// definition.
1980 static bool
1981 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1982                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1983                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1984                            Sema::CheckConstexprKind Kind) {
1985   // - its function-body shall be [...] a compound-statement that contains only
1986   switch (S->getStmtClass()) {
1987   case Stmt::NullStmtClass:
1988     //   - null statements,
1989     return true;
1990 
1991   case Stmt::DeclStmtClass:
1992     //   - static_assert-declarations
1993     //   - using-declarations,
1994     //   - using-directives,
1995     //   - typedef declarations and alias-declarations that do not define
1996     //     classes or enumerations,
1997     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1998       return false;
1999     return true;
2000 
2001   case Stmt::ReturnStmtClass:
2002     //   - and exactly one return statement;
2003     if (isa<CXXConstructorDecl>(Dcl)) {
2004       // C++1y allows return statements in constexpr constructors.
2005       if (!Cxx1yLoc.isValid())
2006         Cxx1yLoc = S->getBeginLoc();
2007       return true;
2008     }
2009 
2010     ReturnStmts.push_back(S->getBeginLoc());
2011     return true;
2012 
2013   case Stmt::CompoundStmtClass: {
2014     // C++1y allows compound-statements.
2015     if (!Cxx1yLoc.isValid())
2016       Cxx1yLoc = S->getBeginLoc();
2017 
2018     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2019     for (auto *BodyIt : CompStmt->body()) {
2020       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2021                                       Cxx1yLoc, Cxx2aLoc, Kind))
2022         return false;
2023     }
2024     return true;
2025   }
2026 
2027   case Stmt::AttributedStmtClass:
2028     if (!Cxx1yLoc.isValid())
2029       Cxx1yLoc = S->getBeginLoc();
2030     return true;
2031 
2032   case Stmt::IfStmtClass: {
2033     // C++1y allows if-statements.
2034     if (!Cxx1yLoc.isValid())
2035       Cxx1yLoc = S->getBeginLoc();
2036 
2037     IfStmt *If = cast<IfStmt>(S);
2038     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2039                                     Cxx1yLoc, Cxx2aLoc, Kind))
2040       return false;
2041     if (If->getElse() &&
2042         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2043                                     Cxx1yLoc, Cxx2aLoc, Kind))
2044       return false;
2045     return true;
2046   }
2047 
2048   case Stmt::WhileStmtClass:
2049   case Stmt::DoStmtClass:
2050   case Stmt::ForStmtClass:
2051   case Stmt::CXXForRangeStmtClass:
2052   case Stmt::ContinueStmtClass:
2053     // C++1y allows all of these. We don't allow them as extensions in C++11,
2054     // because they don't make sense without variable mutation.
2055     if (!SemaRef.getLangOpts().CPlusPlus14)
2056       break;
2057     if (!Cxx1yLoc.isValid())
2058       Cxx1yLoc = S->getBeginLoc();
2059     for (Stmt *SubStmt : S->children())
2060       if (SubStmt &&
2061           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2062                                       Cxx1yLoc, Cxx2aLoc, Kind))
2063         return false;
2064     return true;
2065 
2066   case Stmt::SwitchStmtClass:
2067   case Stmt::CaseStmtClass:
2068   case Stmt::DefaultStmtClass:
2069   case Stmt::BreakStmtClass:
2070     // C++1y allows switch-statements, and since they don't need variable
2071     // mutation, we can reasonably allow them in C++11 as an extension.
2072     if (!Cxx1yLoc.isValid())
2073       Cxx1yLoc = S->getBeginLoc();
2074     for (Stmt *SubStmt : S->children())
2075       if (SubStmt &&
2076           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2077                                       Cxx1yLoc, Cxx2aLoc, Kind))
2078         return false;
2079     return true;
2080 
2081   case Stmt::GCCAsmStmtClass:
2082   case Stmt::MSAsmStmtClass:
2083     // C++2a allows inline assembly statements.
2084   case Stmt::CXXTryStmtClass:
2085     if (Cxx2aLoc.isInvalid())
2086       Cxx2aLoc = S->getBeginLoc();
2087     for (Stmt *SubStmt : S->children()) {
2088       if (SubStmt &&
2089           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2090                                       Cxx1yLoc, Cxx2aLoc, Kind))
2091         return false;
2092     }
2093     return true;
2094 
2095   case Stmt::CXXCatchStmtClass:
2096     // Do not bother checking the language mode (already covered by the
2097     // try block check).
2098     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2099                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2100                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2101       return false;
2102     return true;
2103 
2104   default:
2105     if (!isa<Expr>(S))
2106       break;
2107 
2108     // C++1y allows expression-statements.
2109     if (!Cxx1yLoc.isValid())
2110       Cxx1yLoc = S->getBeginLoc();
2111     return true;
2112   }
2113 
2114   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2115     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2116         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2117   }
2118   return false;
2119 }
2120 
2121 /// Check the body for the given constexpr function declaration only contains
2122 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2123 ///
2124 /// \return true if the body is OK, false if we have found or diagnosed a
2125 /// problem.
2126 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2127                                        Stmt *Body,
2128                                        Sema::CheckConstexprKind Kind) {
2129   SmallVector<SourceLocation, 4> ReturnStmts;
2130 
2131   if (isa<CXXTryStmt>(Body)) {
2132     // C++11 [dcl.constexpr]p3:
2133     //  The definition of a constexpr function shall satisfy the following
2134     //  constraints: [...]
2135     // - its function-body shall be = delete, = default, or a
2136     //   compound-statement
2137     //
2138     // C++11 [dcl.constexpr]p4:
2139     //  In the definition of a constexpr constructor, [...]
2140     // - its function-body shall not be a function-try-block;
2141     //
2142     // This restriction is lifted in C++2a, as long as inner statements also
2143     // apply the general constexpr rules.
2144     switch (Kind) {
2145     case Sema::CheckConstexprKind::CheckValid:
2146       if (!SemaRef.getLangOpts().CPlusPlus20)
2147         return false;
2148       break;
2149 
2150     case Sema::CheckConstexprKind::Diagnose:
2151       SemaRef.Diag(Body->getBeginLoc(),
2152            !SemaRef.getLangOpts().CPlusPlus20
2153                ? diag::ext_constexpr_function_try_block_cxx20
2154                : diag::warn_cxx17_compat_constexpr_function_try_block)
2155           << isa<CXXConstructorDecl>(Dcl);
2156       break;
2157     }
2158   }
2159 
2160   // - its function-body shall be [...] a compound-statement that contains only
2161   //   [... list of cases ...]
2162   //
2163   // Note that walking the children here is enough to properly check for
2164   // CompoundStmt and CXXTryStmt body.
2165   SourceLocation Cxx1yLoc, Cxx2aLoc;
2166   for (Stmt *SubStmt : Body->children()) {
2167     if (SubStmt &&
2168         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2169                                     Cxx1yLoc, Cxx2aLoc, Kind))
2170       return false;
2171   }
2172 
2173   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2174     // If this is only valid as an extension, report that we don't satisfy the
2175     // constraints of the current language.
2176     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2177         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2178       return false;
2179   } else if (Cxx2aLoc.isValid()) {
2180     SemaRef.Diag(Cxx2aLoc,
2181          SemaRef.getLangOpts().CPlusPlus20
2182            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2183            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2184       << isa<CXXConstructorDecl>(Dcl);
2185   } else if (Cxx1yLoc.isValid()) {
2186     SemaRef.Diag(Cxx1yLoc,
2187          SemaRef.getLangOpts().CPlusPlus14
2188            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2189            : diag::ext_constexpr_body_invalid_stmt)
2190       << isa<CXXConstructorDecl>(Dcl);
2191   }
2192 
2193   if (const CXXConstructorDecl *Constructor
2194         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2195     const CXXRecordDecl *RD = Constructor->getParent();
2196     // DR1359:
2197     // - every non-variant non-static data member and base class sub-object
2198     //   shall be initialized;
2199     // DR1460:
2200     // - if the class is a union having variant members, exactly one of them
2201     //   shall be initialized;
2202     if (RD->isUnion()) {
2203       if (Constructor->getNumCtorInitializers() == 0 &&
2204           RD->hasVariantMembers()) {
2205         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2206           SemaRef.Diag(
2207               Dcl->getLocation(),
2208               SemaRef.getLangOpts().CPlusPlus20
2209                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2210                   : diag::ext_constexpr_union_ctor_no_init);
2211         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2212           return false;
2213         }
2214       }
2215     } else if (!Constructor->isDependentContext() &&
2216                !Constructor->isDelegatingConstructor()) {
2217       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2218 
2219       // Skip detailed checking if we have enough initializers, and we would
2220       // allow at most one initializer per member.
2221       bool AnyAnonStructUnionMembers = false;
2222       unsigned Fields = 0;
2223       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2224            E = RD->field_end(); I != E; ++I, ++Fields) {
2225         if (I->isAnonymousStructOrUnion()) {
2226           AnyAnonStructUnionMembers = true;
2227           break;
2228         }
2229       }
2230       // DR1460:
2231       // - if the class is a union-like class, but is not a union, for each of
2232       //   its anonymous union members having variant members, exactly one of
2233       //   them shall be initialized;
2234       if (AnyAnonStructUnionMembers ||
2235           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2236         // Check initialization of non-static data members. Base classes are
2237         // always initialized so do not need to be checked. Dependent bases
2238         // might not have initializers in the member initializer list.
2239         llvm::SmallSet<Decl*, 16> Inits;
2240         for (const auto *I: Constructor->inits()) {
2241           if (FieldDecl *FD = I->getMember())
2242             Inits.insert(FD);
2243           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2244             Inits.insert(ID->chain_begin(), ID->chain_end());
2245         }
2246 
2247         bool Diagnosed = false;
2248         for (auto *I : RD->fields())
2249           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2250                                              Kind))
2251             return false;
2252       }
2253     }
2254   } else {
2255     if (ReturnStmts.empty()) {
2256       // C++1y doesn't require constexpr functions to contain a 'return'
2257       // statement. We still do, unless the return type might be void, because
2258       // otherwise if there's no return statement, the function cannot
2259       // be used in a core constant expression.
2260       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2261                 (Dcl->getReturnType()->isVoidType() ||
2262                  Dcl->getReturnType()->isDependentType());
2263       switch (Kind) {
2264       case Sema::CheckConstexprKind::Diagnose:
2265         SemaRef.Diag(Dcl->getLocation(),
2266                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2267                         : diag::err_constexpr_body_no_return)
2268             << Dcl->isConsteval();
2269         if (!OK)
2270           return false;
2271         break;
2272 
2273       case Sema::CheckConstexprKind::CheckValid:
2274         // The formal requirements don't include this rule in C++14, even
2275         // though the "must be able to produce a constant expression" rules
2276         // still imply it in some cases.
2277         if (!SemaRef.getLangOpts().CPlusPlus14)
2278           return false;
2279         break;
2280       }
2281     } else if (ReturnStmts.size() > 1) {
2282       switch (Kind) {
2283       case Sema::CheckConstexprKind::Diagnose:
2284         SemaRef.Diag(
2285             ReturnStmts.back(),
2286             SemaRef.getLangOpts().CPlusPlus14
2287                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2288                 : diag::ext_constexpr_body_multiple_return);
2289         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2290           SemaRef.Diag(ReturnStmts[I],
2291                        diag::note_constexpr_body_previous_return);
2292         break;
2293 
2294       case Sema::CheckConstexprKind::CheckValid:
2295         if (!SemaRef.getLangOpts().CPlusPlus14)
2296           return false;
2297         break;
2298       }
2299     }
2300   }
2301 
2302   // C++11 [dcl.constexpr]p5:
2303   //   if no function argument values exist such that the function invocation
2304   //   substitution would produce a constant expression, the program is
2305   //   ill-formed; no diagnostic required.
2306   // C++11 [dcl.constexpr]p3:
2307   //   - every constructor call and implicit conversion used in initializing the
2308   //     return value shall be one of those allowed in a constant expression.
2309   // C++11 [dcl.constexpr]p4:
2310   //   - every constructor involved in initializing non-static data members and
2311   //     base class sub-objects shall be a constexpr constructor.
2312   //
2313   // Note that this rule is distinct from the "requirements for a constexpr
2314   // function", so is not checked in CheckValid mode.
2315   SmallVector<PartialDiagnosticAt, 8> Diags;
2316   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2317       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2318     SemaRef.Diag(Dcl->getLocation(),
2319                  diag::ext_constexpr_function_never_constant_expr)
2320         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2321     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2322       SemaRef.Diag(Diags[I].first, Diags[I].second);
2323     // Don't return false here: we allow this for compatibility in
2324     // system headers.
2325   }
2326 
2327   return true;
2328 }
2329 
2330 /// Get the class that is directly named by the current context. This is the
2331 /// class for which an unqualified-id in this scope could name a constructor
2332 /// or destructor.
2333 ///
2334 /// If the scope specifier denotes a class, this will be that class.
2335 /// If the scope specifier is empty, this will be the class whose
2336 /// member-specification we are currently within. Otherwise, there
2337 /// is no such class.
2338 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2339   assert(getLangOpts().CPlusPlus && "No class names in C!");
2340 
2341   if (SS && SS->isInvalid())
2342     return nullptr;
2343 
2344   if (SS && SS->isNotEmpty()) {
2345     DeclContext *DC = computeDeclContext(*SS, true);
2346     return dyn_cast_or_null<CXXRecordDecl>(DC);
2347   }
2348 
2349   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2350 }
2351 
2352 /// isCurrentClassName - Determine whether the identifier II is the
2353 /// name of the class type currently being defined. In the case of
2354 /// nested classes, this will only return true if II is the name of
2355 /// the innermost class.
2356 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2357                               const CXXScopeSpec *SS) {
2358   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2359   return CurDecl && &II == CurDecl->getIdentifier();
2360 }
2361 
2362 /// Determine whether the identifier II is a typo for the name of
2363 /// the class type currently being defined. If so, update it to the identifier
2364 /// that should have been used.
2365 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2366   assert(getLangOpts().CPlusPlus && "No class names in C!");
2367 
2368   if (!getLangOpts().SpellChecking)
2369     return false;
2370 
2371   CXXRecordDecl *CurDecl;
2372   if (SS && SS->isSet() && !SS->isInvalid()) {
2373     DeclContext *DC = computeDeclContext(*SS, true);
2374     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2375   } else
2376     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2377 
2378   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2379       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2380           < II->getLength()) {
2381     II = CurDecl->getIdentifier();
2382     return true;
2383   }
2384 
2385   return false;
2386 }
2387 
2388 /// Determine whether the given class is a base class of the given
2389 /// class, including looking at dependent bases.
2390 static bool findCircularInheritance(const CXXRecordDecl *Class,
2391                                     const CXXRecordDecl *Current) {
2392   SmallVector<const CXXRecordDecl*, 8> Queue;
2393 
2394   Class = Class->getCanonicalDecl();
2395   while (true) {
2396     for (const auto &I : Current->bases()) {
2397       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2398       if (!Base)
2399         continue;
2400 
2401       Base = Base->getDefinition();
2402       if (!Base)
2403         continue;
2404 
2405       if (Base->getCanonicalDecl() == Class)
2406         return true;
2407 
2408       Queue.push_back(Base);
2409     }
2410 
2411     if (Queue.empty())
2412       return false;
2413 
2414     Current = Queue.pop_back_val();
2415   }
2416 
2417   return false;
2418 }
2419 
2420 /// Check the validity of a C++ base class specifier.
2421 ///
2422 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2423 /// and returns NULL otherwise.
2424 CXXBaseSpecifier *
2425 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2426                          SourceRange SpecifierRange,
2427                          bool Virtual, AccessSpecifier Access,
2428                          TypeSourceInfo *TInfo,
2429                          SourceLocation EllipsisLoc) {
2430   QualType BaseType = TInfo->getType();
2431   if (BaseType->containsErrors()) {
2432     // Already emitted a diagnostic when parsing the error type.
2433     return nullptr;
2434   }
2435   // C++ [class.union]p1:
2436   //   A union shall not have base classes.
2437   if (Class->isUnion()) {
2438     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2439       << SpecifierRange;
2440     return nullptr;
2441   }
2442 
2443   if (EllipsisLoc.isValid() &&
2444       !TInfo->getType()->containsUnexpandedParameterPack()) {
2445     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2446       << TInfo->getTypeLoc().getSourceRange();
2447     EllipsisLoc = SourceLocation();
2448   }
2449 
2450   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2451 
2452   if (BaseType->isDependentType()) {
2453     // Make sure that we don't have circular inheritance among our dependent
2454     // bases. For non-dependent bases, the check for completeness below handles
2455     // this.
2456     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2457       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2458           ((BaseDecl = BaseDecl->getDefinition()) &&
2459            findCircularInheritance(Class, BaseDecl))) {
2460         Diag(BaseLoc, diag::err_circular_inheritance)
2461           << BaseType << Context.getTypeDeclType(Class);
2462 
2463         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2464           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2465             << BaseType;
2466 
2467         return nullptr;
2468       }
2469     }
2470 
2471     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2472                                           Class->getTagKind() == TTK_Class,
2473                                           Access, TInfo, EllipsisLoc);
2474   }
2475 
2476   // Base specifiers must be record types.
2477   if (!BaseType->isRecordType()) {
2478     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2479     return nullptr;
2480   }
2481 
2482   // C++ [class.union]p1:
2483   //   A union shall not be used as a base class.
2484   if (BaseType->isUnionType()) {
2485     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2486     return nullptr;
2487   }
2488 
2489   // For the MS ABI, propagate DLL attributes to base class templates.
2490   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2491     if (Attr *ClassAttr = getDLLAttr(Class)) {
2492       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2493               BaseType->getAsCXXRecordDecl())) {
2494         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2495                                             BaseLoc);
2496       }
2497     }
2498   }
2499 
2500   // C++ [class.derived]p2:
2501   //   The class-name in a base-specifier shall not be an incompletely
2502   //   defined class.
2503   if (RequireCompleteType(BaseLoc, BaseType,
2504                           diag::err_incomplete_base_class, SpecifierRange)) {
2505     Class->setInvalidDecl();
2506     return nullptr;
2507   }
2508 
2509   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2510   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2511   assert(BaseDecl && "Record type has no declaration");
2512   BaseDecl = BaseDecl->getDefinition();
2513   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2514   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2515   assert(CXXBaseDecl && "Base type is not a C++ type");
2516 
2517   // Microsoft docs say:
2518   // "If a base-class has a code_seg attribute, derived classes must have the
2519   // same attribute."
2520   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2521   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2522   if ((DerivedCSA || BaseCSA) &&
2523       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2524     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2525     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2526       << CXXBaseDecl;
2527     return nullptr;
2528   }
2529 
2530   // A class which contains a flexible array member is not suitable for use as a
2531   // base class:
2532   //   - If the layout determines that a base comes before another base,
2533   //     the flexible array member would index into the subsequent base.
2534   //   - If the layout determines that base comes before the derived class,
2535   //     the flexible array member would index into the derived class.
2536   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2537     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2538       << CXXBaseDecl->getDeclName();
2539     return nullptr;
2540   }
2541 
2542   // C++ [class]p3:
2543   //   If a class is marked final and it appears as a base-type-specifier in
2544   //   base-clause, the program is ill-formed.
2545   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2546     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2547       << CXXBaseDecl->getDeclName()
2548       << FA->isSpelledAsSealed();
2549     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2550         << CXXBaseDecl->getDeclName() << FA->getRange();
2551     return nullptr;
2552   }
2553 
2554   if (BaseDecl->isInvalidDecl())
2555     Class->setInvalidDecl();
2556 
2557   // Create the base specifier.
2558   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2559                                         Class->getTagKind() == TTK_Class,
2560                                         Access, TInfo, EllipsisLoc);
2561 }
2562 
2563 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2564 /// one entry in the base class list of a class specifier, for
2565 /// example:
2566 ///    class foo : public bar, virtual private baz {
2567 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2568 BaseResult
2569 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2570                          ParsedAttributes &Attributes,
2571                          bool Virtual, AccessSpecifier Access,
2572                          ParsedType basetype, SourceLocation BaseLoc,
2573                          SourceLocation EllipsisLoc) {
2574   if (!classdecl)
2575     return true;
2576 
2577   AdjustDeclIfTemplate(classdecl);
2578   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2579   if (!Class)
2580     return true;
2581 
2582   // We haven't yet attached the base specifiers.
2583   Class->setIsParsingBaseSpecifiers();
2584 
2585   // We do not support any C++11 attributes on base-specifiers yet.
2586   // Diagnose any attributes we see.
2587   for (const ParsedAttr &AL : Attributes) {
2588     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2589       continue;
2590     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2591                           ? (unsigned)diag::warn_unknown_attribute_ignored
2592                           : (unsigned)diag::err_base_specifier_attribute)
2593         << AL;
2594   }
2595 
2596   TypeSourceInfo *TInfo = nullptr;
2597   GetTypeFromParser(basetype, &TInfo);
2598 
2599   if (EllipsisLoc.isInvalid() &&
2600       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2601                                       UPPC_BaseType))
2602     return true;
2603 
2604   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2605                                                       Virtual, Access, TInfo,
2606                                                       EllipsisLoc))
2607     return BaseSpec;
2608   else
2609     Class->setInvalidDecl();
2610 
2611   return true;
2612 }
2613 
2614 /// Use small set to collect indirect bases.  As this is only used
2615 /// locally, there's no need to abstract the small size parameter.
2616 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2617 
2618 /// Recursively add the bases of Type.  Don't add Type itself.
2619 static void
2620 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2621                   const QualType &Type)
2622 {
2623   // Even though the incoming type is a base, it might not be
2624   // a class -- it could be a template parm, for instance.
2625   if (auto Rec = Type->getAs<RecordType>()) {
2626     auto Decl = Rec->getAsCXXRecordDecl();
2627 
2628     // Iterate over its bases.
2629     for (const auto &BaseSpec : Decl->bases()) {
2630       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2631         .getUnqualifiedType();
2632       if (Set.insert(Base).second)
2633         // If we've not already seen it, recurse.
2634         NoteIndirectBases(Context, Set, Base);
2635     }
2636   }
2637 }
2638 
2639 /// Performs the actual work of attaching the given base class
2640 /// specifiers to a C++ class.
2641 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2642                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2643  if (Bases.empty())
2644     return false;
2645 
2646   // Used to keep track of which base types we have already seen, so
2647   // that we can properly diagnose redundant direct base types. Note
2648   // that the key is always the unqualified canonical type of the base
2649   // class.
2650   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2651 
2652   // Used to track indirect bases so we can see if a direct base is
2653   // ambiguous.
2654   IndirectBaseSet IndirectBaseTypes;
2655 
2656   // Copy non-redundant base specifiers into permanent storage.
2657   unsigned NumGoodBases = 0;
2658   bool Invalid = false;
2659   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2660     QualType NewBaseType
2661       = Context.getCanonicalType(Bases[idx]->getType());
2662     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2663 
2664     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2665     if (KnownBase) {
2666       // C++ [class.mi]p3:
2667       //   A class shall not be specified as a direct base class of a
2668       //   derived class more than once.
2669       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2670           << KnownBase->getType() << Bases[idx]->getSourceRange();
2671 
2672       // Delete the duplicate base class specifier; we're going to
2673       // overwrite its pointer later.
2674       Context.Deallocate(Bases[idx]);
2675 
2676       Invalid = true;
2677     } else {
2678       // Okay, add this new base class.
2679       KnownBase = Bases[idx];
2680       Bases[NumGoodBases++] = Bases[idx];
2681 
2682       // Note this base's direct & indirect bases, if there could be ambiguity.
2683       if (Bases.size() > 1)
2684         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2685 
2686       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2687         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2688         if (Class->isInterface() &&
2689               (!RD->isInterfaceLike() ||
2690                KnownBase->getAccessSpecifier() != AS_public)) {
2691           // The Microsoft extension __interface does not permit bases that
2692           // are not themselves public interfaces.
2693           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2694               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2695               << RD->getSourceRange();
2696           Invalid = true;
2697         }
2698         if (RD->hasAttr<WeakAttr>())
2699           Class->addAttr(WeakAttr::CreateImplicit(Context));
2700       }
2701     }
2702   }
2703 
2704   // Attach the remaining base class specifiers to the derived class.
2705   Class->setBases(Bases.data(), NumGoodBases);
2706 
2707   // Check that the only base classes that are duplicate are virtual.
2708   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2709     // Check whether this direct base is inaccessible due to ambiguity.
2710     QualType BaseType = Bases[idx]->getType();
2711 
2712     // Skip all dependent types in templates being used as base specifiers.
2713     // Checks below assume that the base specifier is a CXXRecord.
2714     if (BaseType->isDependentType())
2715       continue;
2716 
2717     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2718       .getUnqualifiedType();
2719 
2720     if (IndirectBaseTypes.count(CanonicalBase)) {
2721       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2722                          /*DetectVirtual=*/true);
2723       bool found
2724         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2725       assert(found);
2726       (void)found;
2727 
2728       if (Paths.isAmbiguous(CanonicalBase))
2729         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2730             << BaseType << getAmbiguousPathsDisplayString(Paths)
2731             << Bases[idx]->getSourceRange();
2732       else
2733         assert(Bases[idx]->isVirtual());
2734     }
2735 
2736     // Delete the base class specifier, since its data has been copied
2737     // into the CXXRecordDecl.
2738     Context.Deallocate(Bases[idx]);
2739   }
2740 
2741   return Invalid;
2742 }
2743 
2744 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2745 /// class, after checking whether there are any duplicate base
2746 /// classes.
2747 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2748                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2749   if (!ClassDecl || Bases.empty())
2750     return;
2751 
2752   AdjustDeclIfTemplate(ClassDecl);
2753   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2754 }
2755 
2756 /// Determine whether the type \p Derived is a C++ class that is
2757 /// derived from the type \p Base.
2758 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2759   if (!getLangOpts().CPlusPlus)
2760     return false;
2761 
2762   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2763   if (!DerivedRD)
2764     return false;
2765 
2766   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2767   if (!BaseRD)
2768     return false;
2769 
2770   // If either the base or the derived type is invalid, don't try to
2771   // check whether one is derived from the other.
2772   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2773     return false;
2774 
2775   // FIXME: In a modules build, do we need the entire path to be visible for us
2776   // to be able to use the inheritance relationship?
2777   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2778     return false;
2779 
2780   return DerivedRD->isDerivedFrom(BaseRD);
2781 }
2782 
2783 /// Determine whether the type \p Derived is a C++ class that is
2784 /// derived from the type \p Base.
2785 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2786                          CXXBasePaths &Paths) {
2787   if (!getLangOpts().CPlusPlus)
2788     return false;
2789 
2790   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2791   if (!DerivedRD)
2792     return false;
2793 
2794   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2795   if (!BaseRD)
2796     return false;
2797 
2798   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2799     return false;
2800 
2801   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2802 }
2803 
2804 static void BuildBasePathArray(const CXXBasePath &Path,
2805                                CXXCastPath &BasePathArray) {
2806   // We first go backward and check if we have a virtual base.
2807   // FIXME: It would be better if CXXBasePath had the base specifier for
2808   // the nearest virtual base.
2809   unsigned Start = 0;
2810   for (unsigned I = Path.size(); I != 0; --I) {
2811     if (Path[I - 1].Base->isVirtual()) {
2812       Start = I - 1;
2813       break;
2814     }
2815   }
2816 
2817   // Now add all bases.
2818   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2819     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2820 }
2821 
2822 
2823 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2824                               CXXCastPath &BasePathArray) {
2825   assert(BasePathArray.empty() && "Base path array must be empty!");
2826   assert(Paths.isRecordingPaths() && "Must record paths!");
2827   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2828 }
2829 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2830 /// conversion (where Derived and Base are class types) is
2831 /// well-formed, meaning that the conversion is unambiguous (and
2832 /// that all of the base classes are accessible). Returns true
2833 /// and emits a diagnostic if the code is ill-formed, returns false
2834 /// otherwise. Loc is the location where this routine should point to
2835 /// if there is an error, and Range is the source range to highlight
2836 /// if there is an error.
2837 ///
2838 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2839 /// diagnostic for the respective type of error will be suppressed, but the
2840 /// check for ill-formed code will still be performed.
2841 bool
2842 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2843                                    unsigned InaccessibleBaseID,
2844                                    unsigned AmbiguousBaseConvID,
2845                                    SourceLocation Loc, SourceRange Range,
2846                                    DeclarationName Name,
2847                                    CXXCastPath *BasePath,
2848                                    bool IgnoreAccess) {
2849   // First, determine whether the path from Derived to Base is
2850   // ambiguous. This is slightly more expensive than checking whether
2851   // the Derived to Base conversion exists, because here we need to
2852   // explore multiple paths to determine if there is an ambiguity.
2853   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2854                      /*DetectVirtual=*/false);
2855   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2856   if (!DerivationOkay)
2857     return true;
2858 
2859   const CXXBasePath *Path = nullptr;
2860   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2861     Path = &Paths.front();
2862 
2863   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2864   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2865   // user to access such bases.
2866   if (!Path && getLangOpts().MSVCCompat) {
2867     for (const CXXBasePath &PossiblePath : Paths) {
2868       if (PossiblePath.size() == 1) {
2869         Path = &PossiblePath;
2870         if (AmbiguousBaseConvID)
2871           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2872               << Base << Derived << Range;
2873         break;
2874       }
2875     }
2876   }
2877 
2878   if (Path) {
2879     if (!IgnoreAccess) {
2880       // Check that the base class can be accessed.
2881       switch (
2882           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2883       case AR_inaccessible:
2884         return true;
2885       case AR_accessible:
2886       case AR_dependent:
2887       case AR_delayed:
2888         break;
2889       }
2890     }
2891 
2892     // Build a base path if necessary.
2893     if (BasePath)
2894       ::BuildBasePathArray(*Path, *BasePath);
2895     return false;
2896   }
2897 
2898   if (AmbiguousBaseConvID) {
2899     // We know that the derived-to-base conversion is ambiguous, and
2900     // we're going to produce a diagnostic. Perform the derived-to-base
2901     // search just one more time to compute all of the possible paths so
2902     // that we can print them out. This is more expensive than any of
2903     // the previous derived-to-base checks we've done, but at this point
2904     // performance isn't as much of an issue.
2905     Paths.clear();
2906     Paths.setRecordingPaths(true);
2907     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2908     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2909     (void)StillOkay;
2910 
2911     // Build up a textual representation of the ambiguous paths, e.g.,
2912     // D -> B -> A, that will be used to illustrate the ambiguous
2913     // conversions in the diagnostic. We only print one of the paths
2914     // to each base class subobject.
2915     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2916 
2917     Diag(Loc, AmbiguousBaseConvID)
2918     << Derived << Base << PathDisplayStr << Range << Name;
2919   }
2920   return true;
2921 }
2922 
2923 bool
2924 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2925                                    SourceLocation Loc, SourceRange Range,
2926                                    CXXCastPath *BasePath,
2927                                    bool IgnoreAccess) {
2928   return CheckDerivedToBaseConversion(
2929       Derived, Base, diag::err_upcast_to_inaccessible_base,
2930       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2931       BasePath, IgnoreAccess);
2932 }
2933 
2934 
2935 /// Builds a string representing ambiguous paths from a
2936 /// specific derived class to different subobjects of the same base
2937 /// class.
2938 ///
2939 /// This function builds a string that can be used in error messages
2940 /// to show the different paths that one can take through the
2941 /// inheritance hierarchy to go from the derived class to different
2942 /// subobjects of a base class. The result looks something like this:
2943 /// @code
2944 /// struct D -> struct B -> struct A
2945 /// struct D -> struct C -> struct A
2946 /// @endcode
2947 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2948   std::string PathDisplayStr;
2949   std::set<unsigned> DisplayedPaths;
2950   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2951        Path != Paths.end(); ++Path) {
2952     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2953       // We haven't displayed a path to this particular base
2954       // class subobject yet.
2955       PathDisplayStr += "\n    ";
2956       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2957       for (CXXBasePath::const_iterator Element = Path->begin();
2958            Element != Path->end(); ++Element)
2959         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2960     }
2961   }
2962 
2963   return PathDisplayStr;
2964 }
2965 
2966 //===----------------------------------------------------------------------===//
2967 // C++ class member Handling
2968 //===----------------------------------------------------------------------===//
2969 
2970 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2971 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2972                                 SourceLocation ColonLoc,
2973                                 const ParsedAttributesView &Attrs) {
2974   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2975   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2976                                                   ASLoc, ColonLoc);
2977   CurContext->addHiddenDecl(ASDecl);
2978   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2979 }
2980 
2981 /// CheckOverrideControl - Check C++11 override control semantics.
2982 void Sema::CheckOverrideControl(NamedDecl *D) {
2983   if (D->isInvalidDecl())
2984     return;
2985 
2986   // We only care about "override" and "final" declarations.
2987   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2988     return;
2989 
2990   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2991 
2992   // We can't check dependent instance methods.
2993   if (MD && MD->isInstance() &&
2994       (MD->getParent()->hasAnyDependentBases() ||
2995        MD->getType()->isDependentType()))
2996     return;
2997 
2998   if (MD && !MD->isVirtual()) {
2999     // If we have a non-virtual method, check if if hides a virtual method.
3000     // (In that case, it's most likely the method has the wrong type.)
3001     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3002     FindHiddenVirtualMethods(MD, OverloadedMethods);
3003 
3004     if (!OverloadedMethods.empty()) {
3005       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3006         Diag(OA->getLocation(),
3007              diag::override_keyword_hides_virtual_member_function)
3008           << "override" << (OverloadedMethods.size() > 1);
3009       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3010         Diag(FA->getLocation(),
3011              diag::override_keyword_hides_virtual_member_function)
3012           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3013           << (OverloadedMethods.size() > 1);
3014       }
3015       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3016       MD->setInvalidDecl();
3017       return;
3018     }
3019     // Fall through into the general case diagnostic.
3020     // FIXME: We might want to attempt typo correction here.
3021   }
3022 
3023   if (!MD || !MD->isVirtual()) {
3024     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3025       Diag(OA->getLocation(),
3026            diag::override_keyword_only_allowed_on_virtual_member_functions)
3027         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3028       D->dropAttr<OverrideAttr>();
3029     }
3030     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3031       Diag(FA->getLocation(),
3032            diag::override_keyword_only_allowed_on_virtual_member_functions)
3033         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3034         << FixItHint::CreateRemoval(FA->getLocation());
3035       D->dropAttr<FinalAttr>();
3036     }
3037     return;
3038   }
3039 
3040   // C++11 [class.virtual]p5:
3041   //   If a function is marked with the virt-specifier override and
3042   //   does not override a member function of a base class, the program is
3043   //   ill-formed.
3044   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3045   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3046     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3047       << MD->getDeclName();
3048 }
3049 
3050 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3051   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3052     return;
3053   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3054   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3055     return;
3056 
3057   SourceLocation Loc = MD->getLocation();
3058   SourceLocation SpellingLoc = Loc;
3059   if (getSourceManager().isMacroArgExpansion(Loc))
3060     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3061   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3062   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3063       return;
3064 
3065   if (MD->size_overridden_methods() > 0) {
3066     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3067       unsigned DiagID =
3068           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3069               ? DiagInconsistent
3070               : DiagSuggest;
3071       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3072       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3073       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3074     };
3075     if (isa<CXXDestructorDecl>(MD))
3076       EmitDiag(
3077           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3078           diag::warn_suggest_destructor_marked_not_override_overriding);
3079     else
3080       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3081                diag::warn_suggest_function_marked_not_override_overriding);
3082   }
3083 }
3084 
3085 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3086 /// function overrides a virtual member function marked 'final', according to
3087 /// C++11 [class.virtual]p4.
3088 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3089                                                   const CXXMethodDecl *Old) {
3090   FinalAttr *FA = Old->getAttr<FinalAttr>();
3091   if (!FA)
3092     return false;
3093 
3094   Diag(New->getLocation(), diag::err_final_function_overridden)
3095     << New->getDeclName()
3096     << FA->isSpelledAsSealed();
3097   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3098   return true;
3099 }
3100 
3101 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3102   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3103   // FIXME: Destruction of ObjC lifetime types has side-effects.
3104   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3105     return !RD->isCompleteDefinition() ||
3106            !RD->hasTrivialDefaultConstructor() ||
3107            !RD->hasTrivialDestructor();
3108   return false;
3109 }
3110 
3111 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3112   ParsedAttributesView::const_iterator Itr =
3113       llvm::find_if(list, [](const ParsedAttr &AL) {
3114         return AL.isDeclspecPropertyAttribute();
3115       });
3116   if (Itr != list.end())
3117     return &*Itr;
3118   return nullptr;
3119 }
3120 
3121 // Check if there is a field shadowing.
3122 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3123                                       DeclarationName FieldName,
3124                                       const CXXRecordDecl *RD,
3125                                       bool DeclIsField) {
3126   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3127     return;
3128 
3129   // To record a shadowed field in a base
3130   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3131   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3132                            CXXBasePath &Path) {
3133     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3134     // Record an ambiguous path directly
3135     if (Bases.find(Base) != Bases.end())
3136       return true;
3137     for (const auto Field : Base->lookup(FieldName)) {
3138       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3139           Field->getAccess() != AS_private) {
3140         assert(Field->getAccess() != AS_none);
3141         assert(Bases.find(Base) == Bases.end());
3142         Bases[Base] = Field;
3143         return true;
3144       }
3145     }
3146     return false;
3147   };
3148 
3149   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3150                      /*DetectVirtual=*/true);
3151   if (!RD->lookupInBases(FieldShadowed, Paths))
3152     return;
3153 
3154   for (const auto &P : Paths) {
3155     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3156     auto It = Bases.find(Base);
3157     // Skip duplicated bases
3158     if (It == Bases.end())
3159       continue;
3160     auto BaseField = It->second;
3161     assert(BaseField->getAccess() != AS_private);
3162     if (AS_none !=
3163         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3164       Diag(Loc, diag::warn_shadow_field)
3165         << FieldName << RD << Base << DeclIsField;
3166       Diag(BaseField->getLocation(), diag::note_shadow_field);
3167       Bases.erase(It);
3168     }
3169   }
3170 }
3171 
3172 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3173 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3174 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3175 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3176 /// present (but parsing it has been deferred).
3177 NamedDecl *
3178 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3179                                MultiTemplateParamsArg TemplateParameterLists,
3180                                Expr *BW, const VirtSpecifiers &VS,
3181                                InClassInitStyle InitStyle) {
3182   const DeclSpec &DS = D.getDeclSpec();
3183   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3184   DeclarationName Name = NameInfo.getName();
3185   SourceLocation Loc = NameInfo.getLoc();
3186 
3187   // For anonymous bitfields, the location should point to the type.
3188   if (Loc.isInvalid())
3189     Loc = D.getBeginLoc();
3190 
3191   Expr *BitWidth = static_cast<Expr*>(BW);
3192 
3193   assert(isa<CXXRecordDecl>(CurContext));
3194   assert(!DS.isFriendSpecified());
3195 
3196   bool isFunc = D.isDeclarationOfFunction();
3197   const ParsedAttr *MSPropertyAttr =
3198       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3199 
3200   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3201     // The Microsoft extension __interface only permits public member functions
3202     // and prohibits constructors, destructors, operators, non-public member
3203     // functions, static methods and data members.
3204     unsigned InvalidDecl;
3205     bool ShowDeclName = true;
3206     if (!isFunc &&
3207         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3208       InvalidDecl = 0;
3209     else if (!isFunc)
3210       InvalidDecl = 1;
3211     else if (AS != AS_public)
3212       InvalidDecl = 2;
3213     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3214       InvalidDecl = 3;
3215     else switch (Name.getNameKind()) {
3216       case DeclarationName::CXXConstructorName:
3217         InvalidDecl = 4;
3218         ShowDeclName = false;
3219         break;
3220 
3221       case DeclarationName::CXXDestructorName:
3222         InvalidDecl = 5;
3223         ShowDeclName = false;
3224         break;
3225 
3226       case DeclarationName::CXXOperatorName:
3227       case DeclarationName::CXXConversionFunctionName:
3228         InvalidDecl = 6;
3229         break;
3230 
3231       default:
3232         InvalidDecl = 0;
3233         break;
3234     }
3235 
3236     if (InvalidDecl) {
3237       if (ShowDeclName)
3238         Diag(Loc, diag::err_invalid_member_in_interface)
3239           << (InvalidDecl-1) << Name;
3240       else
3241         Diag(Loc, diag::err_invalid_member_in_interface)
3242           << (InvalidDecl-1) << "";
3243       return nullptr;
3244     }
3245   }
3246 
3247   // C++ 9.2p6: A member shall not be declared to have automatic storage
3248   // duration (auto, register) or with the extern storage-class-specifier.
3249   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3250   // data members and cannot be applied to names declared const or static,
3251   // and cannot be applied to reference members.
3252   switch (DS.getStorageClassSpec()) {
3253   case DeclSpec::SCS_unspecified:
3254   case DeclSpec::SCS_typedef:
3255   case DeclSpec::SCS_static:
3256     break;
3257   case DeclSpec::SCS_mutable:
3258     if (isFunc) {
3259       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3260 
3261       // FIXME: It would be nicer if the keyword was ignored only for this
3262       // declarator. Otherwise we could get follow-up errors.
3263       D.getMutableDeclSpec().ClearStorageClassSpecs();
3264     }
3265     break;
3266   default:
3267     Diag(DS.getStorageClassSpecLoc(),
3268          diag::err_storageclass_invalid_for_member);
3269     D.getMutableDeclSpec().ClearStorageClassSpecs();
3270     break;
3271   }
3272 
3273   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3274                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3275                       !isFunc);
3276 
3277   if (DS.hasConstexprSpecifier() && isInstField) {
3278     SemaDiagnosticBuilder B =
3279         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3280     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3281     if (InitStyle == ICIS_NoInit) {
3282       B << 0 << 0;
3283       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3284         B << FixItHint::CreateRemoval(ConstexprLoc);
3285       else {
3286         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3287         D.getMutableDeclSpec().ClearConstexprSpec();
3288         const char *PrevSpec;
3289         unsigned DiagID;
3290         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3291             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3292         (void)Failed;
3293         assert(!Failed && "Making a constexpr member const shouldn't fail");
3294       }
3295     } else {
3296       B << 1;
3297       const char *PrevSpec;
3298       unsigned DiagID;
3299       if (D.getMutableDeclSpec().SetStorageClassSpec(
3300           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3301           Context.getPrintingPolicy())) {
3302         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3303                "This is the only DeclSpec that should fail to be applied");
3304         B << 1;
3305       } else {
3306         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3307         isInstField = false;
3308       }
3309     }
3310   }
3311 
3312   NamedDecl *Member;
3313   if (isInstField) {
3314     CXXScopeSpec &SS = D.getCXXScopeSpec();
3315 
3316     // Data members must have identifiers for names.
3317     if (!Name.isIdentifier()) {
3318       Diag(Loc, diag::err_bad_variable_name)
3319         << Name;
3320       return nullptr;
3321     }
3322 
3323     IdentifierInfo *II = Name.getAsIdentifierInfo();
3324 
3325     // Member field could not be with "template" keyword.
3326     // So TemplateParameterLists should be empty in this case.
3327     if (TemplateParameterLists.size()) {
3328       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3329       if (TemplateParams->size()) {
3330         // There is no such thing as a member field template.
3331         Diag(D.getIdentifierLoc(), diag::err_template_member)
3332             << II
3333             << SourceRange(TemplateParams->getTemplateLoc(),
3334                 TemplateParams->getRAngleLoc());
3335       } else {
3336         // There is an extraneous 'template<>' for this member.
3337         Diag(TemplateParams->getTemplateLoc(),
3338             diag::err_template_member_noparams)
3339             << II
3340             << SourceRange(TemplateParams->getTemplateLoc(),
3341                 TemplateParams->getRAngleLoc());
3342       }
3343       return nullptr;
3344     }
3345 
3346     if (SS.isSet() && !SS.isInvalid()) {
3347       // The user provided a superfluous scope specifier inside a class
3348       // definition:
3349       //
3350       // class X {
3351       //   int X::member;
3352       // };
3353       if (DeclContext *DC = computeDeclContext(SS, false))
3354         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3355                                      D.getName().getKind() ==
3356                                          UnqualifiedIdKind::IK_TemplateId);
3357       else
3358         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3359           << Name << SS.getRange();
3360 
3361       SS.clear();
3362     }
3363 
3364     if (MSPropertyAttr) {
3365       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3366                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3367       if (!Member)
3368         return nullptr;
3369       isInstField = false;
3370     } else {
3371       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3372                                 BitWidth, InitStyle, AS);
3373       if (!Member)
3374         return nullptr;
3375     }
3376 
3377     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3378   } else {
3379     Member = HandleDeclarator(S, D, TemplateParameterLists);
3380     if (!Member)
3381       return nullptr;
3382 
3383     // Non-instance-fields can't have a bitfield.
3384     if (BitWidth) {
3385       if (Member->isInvalidDecl()) {
3386         // don't emit another diagnostic.
3387       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3388         // C++ 9.6p3: A bit-field shall not be a static member.
3389         // "static member 'A' cannot be a bit-field"
3390         Diag(Loc, diag::err_static_not_bitfield)
3391           << Name << BitWidth->getSourceRange();
3392       } else if (isa<TypedefDecl>(Member)) {
3393         // "typedef member 'x' cannot be a bit-field"
3394         Diag(Loc, diag::err_typedef_not_bitfield)
3395           << Name << BitWidth->getSourceRange();
3396       } else {
3397         // A function typedef ("typedef int f(); f a;").
3398         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3399         Diag(Loc, diag::err_not_integral_type_bitfield)
3400           << Name << cast<ValueDecl>(Member)->getType()
3401           << BitWidth->getSourceRange();
3402       }
3403 
3404       BitWidth = nullptr;
3405       Member->setInvalidDecl();
3406     }
3407 
3408     NamedDecl *NonTemplateMember = Member;
3409     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3410       NonTemplateMember = FunTmpl->getTemplatedDecl();
3411     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3412       NonTemplateMember = VarTmpl->getTemplatedDecl();
3413 
3414     Member->setAccess(AS);
3415 
3416     // If we have declared a member function template or static data member
3417     // template, set the access of the templated declaration as well.
3418     if (NonTemplateMember != Member)
3419       NonTemplateMember->setAccess(AS);
3420 
3421     // C++ [temp.deduct.guide]p3:
3422     //   A deduction guide [...] for a member class template [shall be
3423     //   declared] with the same access [as the template].
3424     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3425       auto *TD = DG->getDeducedTemplate();
3426       // Access specifiers are only meaningful if both the template and the
3427       // deduction guide are from the same scope.
3428       if (AS != TD->getAccess() &&
3429           TD->getDeclContext()->getRedeclContext()->Equals(
3430               DG->getDeclContext()->getRedeclContext())) {
3431         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3432         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3433             << TD->getAccess();
3434         const AccessSpecDecl *LastAccessSpec = nullptr;
3435         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3436           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3437             LastAccessSpec = AccessSpec;
3438         }
3439         assert(LastAccessSpec && "differing access with no access specifier");
3440         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3441             << AS;
3442       }
3443     }
3444   }
3445 
3446   if (VS.isOverrideSpecified())
3447     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3448                                          AttributeCommonInfo::AS_Keyword));
3449   if (VS.isFinalSpecified())
3450     Member->addAttr(FinalAttr::Create(
3451         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3452         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3453 
3454   if (VS.getLastLocation().isValid()) {
3455     // Update the end location of a method that has a virt-specifiers.
3456     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3457       MD->setRangeEnd(VS.getLastLocation());
3458   }
3459 
3460   CheckOverrideControl(Member);
3461 
3462   assert((Name || isInstField) && "No identifier for non-field ?");
3463 
3464   if (isInstField) {
3465     FieldDecl *FD = cast<FieldDecl>(Member);
3466     FieldCollector->Add(FD);
3467 
3468     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3469       // Remember all explicit private FieldDecls that have a name, no side
3470       // effects and are not part of a dependent type declaration.
3471       if (!FD->isImplicit() && FD->getDeclName() &&
3472           FD->getAccess() == AS_private &&
3473           !FD->hasAttr<UnusedAttr>() &&
3474           !FD->getParent()->isDependentContext() &&
3475           !InitializationHasSideEffects(*FD))
3476         UnusedPrivateFields.insert(FD);
3477     }
3478   }
3479 
3480   return Member;
3481 }
3482 
3483 namespace {
3484   class UninitializedFieldVisitor
3485       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3486     Sema &S;
3487     // List of Decls to generate a warning on.  Also remove Decls that become
3488     // initialized.
3489     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3490     // List of base classes of the record.  Classes are removed after their
3491     // initializers.
3492     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3493     // Vector of decls to be removed from the Decl set prior to visiting the
3494     // nodes.  These Decls may have been initialized in the prior initializer.
3495     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3496     // If non-null, add a note to the warning pointing back to the constructor.
3497     const CXXConstructorDecl *Constructor;
3498     // Variables to hold state when processing an initializer list.  When
3499     // InitList is true, special case initialization of FieldDecls matching
3500     // InitListFieldDecl.
3501     bool InitList;
3502     FieldDecl *InitListFieldDecl;
3503     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3504 
3505   public:
3506     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3507     UninitializedFieldVisitor(Sema &S,
3508                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3509                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3510       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3511         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3512 
3513     // Returns true if the use of ME is not an uninitialized use.
3514     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3515                                          bool CheckReferenceOnly) {
3516       llvm::SmallVector<FieldDecl*, 4> Fields;
3517       bool ReferenceField = false;
3518       while (ME) {
3519         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3520         if (!FD)
3521           return false;
3522         Fields.push_back(FD);
3523         if (FD->getType()->isReferenceType())
3524           ReferenceField = true;
3525         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3526       }
3527 
3528       // Binding a reference to an uninitialized field is not an
3529       // uninitialized use.
3530       if (CheckReferenceOnly && !ReferenceField)
3531         return true;
3532 
3533       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3534       // Discard the first field since it is the field decl that is being
3535       // initialized.
3536       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3537         UsedFieldIndex.push_back((*I)->getFieldIndex());
3538       }
3539 
3540       for (auto UsedIter = UsedFieldIndex.begin(),
3541                 UsedEnd = UsedFieldIndex.end(),
3542                 OrigIter = InitFieldIndex.begin(),
3543                 OrigEnd = InitFieldIndex.end();
3544            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3545         if (*UsedIter < *OrigIter)
3546           return true;
3547         if (*UsedIter > *OrigIter)
3548           break;
3549       }
3550 
3551       return false;
3552     }
3553 
3554     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3555                           bool AddressOf) {
3556       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3557         return;
3558 
3559       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3560       // or union.
3561       MemberExpr *FieldME = ME;
3562 
3563       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3564 
3565       Expr *Base = ME;
3566       while (MemberExpr *SubME =
3567                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3568 
3569         if (isa<VarDecl>(SubME->getMemberDecl()))
3570           return;
3571 
3572         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3573           if (!FD->isAnonymousStructOrUnion())
3574             FieldME = SubME;
3575 
3576         if (!FieldME->getType().isPODType(S.Context))
3577           AllPODFields = false;
3578 
3579         Base = SubME->getBase();
3580       }
3581 
3582       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3583         Visit(Base);
3584         return;
3585       }
3586 
3587       if (AddressOf && AllPODFields)
3588         return;
3589 
3590       ValueDecl* FoundVD = FieldME->getMemberDecl();
3591 
3592       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3593         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3594           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3595         }
3596 
3597         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3598           QualType T = BaseCast->getType();
3599           if (T->isPointerType() &&
3600               BaseClasses.count(T->getPointeeType())) {
3601             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3602                 << T->getPointeeType() << FoundVD;
3603           }
3604         }
3605       }
3606 
3607       if (!Decls.count(FoundVD))
3608         return;
3609 
3610       const bool IsReference = FoundVD->getType()->isReferenceType();
3611 
3612       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3613         // Special checking for initializer lists.
3614         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3615           return;
3616         }
3617       } else {
3618         // Prevent double warnings on use of unbounded references.
3619         if (CheckReferenceOnly && !IsReference)
3620           return;
3621       }
3622 
3623       unsigned diag = IsReference
3624           ? diag::warn_reference_field_is_uninit
3625           : diag::warn_field_is_uninit;
3626       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3627       if (Constructor)
3628         S.Diag(Constructor->getLocation(),
3629                diag::note_uninit_in_this_constructor)
3630           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3631 
3632     }
3633 
3634     void HandleValue(Expr *E, bool AddressOf) {
3635       E = E->IgnoreParens();
3636 
3637       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3638         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3639                          AddressOf /*AddressOf*/);
3640         return;
3641       }
3642 
3643       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3644         Visit(CO->getCond());
3645         HandleValue(CO->getTrueExpr(), AddressOf);
3646         HandleValue(CO->getFalseExpr(), AddressOf);
3647         return;
3648       }
3649 
3650       if (BinaryConditionalOperator *BCO =
3651               dyn_cast<BinaryConditionalOperator>(E)) {
3652         Visit(BCO->getCond());
3653         HandleValue(BCO->getFalseExpr(), AddressOf);
3654         return;
3655       }
3656 
3657       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3658         HandleValue(OVE->getSourceExpr(), AddressOf);
3659         return;
3660       }
3661 
3662       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3663         switch (BO->getOpcode()) {
3664         default:
3665           break;
3666         case(BO_PtrMemD):
3667         case(BO_PtrMemI):
3668           HandleValue(BO->getLHS(), AddressOf);
3669           Visit(BO->getRHS());
3670           return;
3671         case(BO_Comma):
3672           Visit(BO->getLHS());
3673           HandleValue(BO->getRHS(), AddressOf);
3674           return;
3675         }
3676       }
3677 
3678       Visit(E);
3679     }
3680 
3681     void CheckInitListExpr(InitListExpr *ILE) {
3682       InitFieldIndex.push_back(0);
3683       for (auto Child : ILE->children()) {
3684         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3685           CheckInitListExpr(SubList);
3686         } else {
3687           Visit(Child);
3688         }
3689         ++InitFieldIndex.back();
3690       }
3691       InitFieldIndex.pop_back();
3692     }
3693 
3694     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3695                           FieldDecl *Field, const Type *BaseClass) {
3696       // Remove Decls that may have been initialized in the previous
3697       // initializer.
3698       for (ValueDecl* VD : DeclsToRemove)
3699         Decls.erase(VD);
3700       DeclsToRemove.clear();
3701 
3702       Constructor = FieldConstructor;
3703       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3704 
3705       if (ILE && Field) {
3706         InitList = true;
3707         InitListFieldDecl = Field;
3708         InitFieldIndex.clear();
3709         CheckInitListExpr(ILE);
3710       } else {
3711         InitList = false;
3712         Visit(E);
3713       }
3714 
3715       if (Field)
3716         Decls.erase(Field);
3717       if (BaseClass)
3718         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3719     }
3720 
3721     void VisitMemberExpr(MemberExpr *ME) {
3722       // All uses of unbounded reference fields will warn.
3723       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3724     }
3725 
3726     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3727       if (E->getCastKind() == CK_LValueToRValue) {
3728         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3729         return;
3730       }
3731 
3732       Inherited::VisitImplicitCastExpr(E);
3733     }
3734 
3735     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3736       if (E->getConstructor()->isCopyConstructor()) {
3737         Expr *ArgExpr = E->getArg(0);
3738         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3739           if (ILE->getNumInits() == 1)
3740             ArgExpr = ILE->getInit(0);
3741         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3742           if (ICE->getCastKind() == CK_NoOp)
3743             ArgExpr = ICE->getSubExpr();
3744         HandleValue(ArgExpr, false /*AddressOf*/);
3745         return;
3746       }
3747       Inherited::VisitCXXConstructExpr(E);
3748     }
3749 
3750     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3751       Expr *Callee = E->getCallee();
3752       if (isa<MemberExpr>(Callee)) {
3753         HandleValue(Callee, false /*AddressOf*/);
3754         for (auto Arg : E->arguments())
3755           Visit(Arg);
3756         return;
3757       }
3758 
3759       Inherited::VisitCXXMemberCallExpr(E);
3760     }
3761 
3762     void VisitCallExpr(CallExpr *E) {
3763       // Treat std::move as a use.
3764       if (E->isCallToStdMove()) {
3765         HandleValue(E->getArg(0), /*AddressOf=*/false);
3766         return;
3767       }
3768 
3769       Inherited::VisitCallExpr(E);
3770     }
3771 
3772     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3773       Expr *Callee = E->getCallee();
3774 
3775       if (isa<UnresolvedLookupExpr>(Callee))
3776         return Inherited::VisitCXXOperatorCallExpr(E);
3777 
3778       Visit(Callee);
3779       for (auto Arg : E->arguments())
3780         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3781     }
3782 
3783     void VisitBinaryOperator(BinaryOperator *E) {
3784       // If a field assignment is detected, remove the field from the
3785       // uninitiailized field set.
3786       if (E->getOpcode() == BO_Assign)
3787         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3788           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3789             if (!FD->getType()->isReferenceType())
3790               DeclsToRemove.push_back(FD);
3791 
3792       if (E->isCompoundAssignmentOp()) {
3793         HandleValue(E->getLHS(), false /*AddressOf*/);
3794         Visit(E->getRHS());
3795         return;
3796       }
3797 
3798       Inherited::VisitBinaryOperator(E);
3799     }
3800 
3801     void VisitUnaryOperator(UnaryOperator *E) {
3802       if (E->isIncrementDecrementOp()) {
3803         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3804         return;
3805       }
3806       if (E->getOpcode() == UO_AddrOf) {
3807         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3808           HandleValue(ME->getBase(), true /*AddressOf*/);
3809           return;
3810         }
3811       }
3812 
3813       Inherited::VisitUnaryOperator(E);
3814     }
3815   };
3816 
3817   // Diagnose value-uses of fields to initialize themselves, e.g.
3818   //   foo(foo)
3819   // where foo is not also a parameter to the constructor.
3820   // Also diagnose across field uninitialized use such as
3821   //   x(y), y(x)
3822   // TODO: implement -Wuninitialized and fold this into that framework.
3823   static void DiagnoseUninitializedFields(
3824       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3825 
3826     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3827                                            Constructor->getLocation())) {
3828       return;
3829     }
3830 
3831     if (Constructor->isInvalidDecl())
3832       return;
3833 
3834     const CXXRecordDecl *RD = Constructor->getParent();
3835 
3836     if (RD->isDependentContext())
3837       return;
3838 
3839     // Holds fields that are uninitialized.
3840     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3841 
3842     // At the beginning, all fields are uninitialized.
3843     for (auto *I : RD->decls()) {
3844       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3845         UninitializedFields.insert(FD);
3846       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3847         UninitializedFields.insert(IFD->getAnonField());
3848       }
3849     }
3850 
3851     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3852     for (auto I : RD->bases())
3853       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3854 
3855     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3856       return;
3857 
3858     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3859                                                    UninitializedFields,
3860                                                    UninitializedBaseClasses);
3861 
3862     for (const auto *FieldInit : Constructor->inits()) {
3863       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3864         break;
3865 
3866       Expr *InitExpr = FieldInit->getInit();
3867       if (!InitExpr)
3868         continue;
3869 
3870       if (CXXDefaultInitExpr *Default =
3871               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3872         InitExpr = Default->getExpr();
3873         if (!InitExpr)
3874           continue;
3875         // In class initializers will point to the constructor.
3876         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3877                                               FieldInit->getAnyMember(),
3878                                               FieldInit->getBaseClass());
3879       } else {
3880         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3881                                               FieldInit->getAnyMember(),
3882                                               FieldInit->getBaseClass());
3883       }
3884     }
3885   }
3886 } // namespace
3887 
3888 /// Enter a new C++ default initializer scope. After calling this, the
3889 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3890 /// parsing or instantiating the initializer failed.
3891 void Sema::ActOnStartCXXInClassMemberInitializer() {
3892   // Create a synthetic function scope to represent the call to the constructor
3893   // that notionally surrounds a use of this initializer.
3894   PushFunctionScope();
3895 }
3896 
3897 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3898   if (!D.isFunctionDeclarator())
3899     return;
3900   auto &FTI = D.getFunctionTypeInfo();
3901   if (!FTI.Params)
3902     return;
3903   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3904                                                           FTI.NumParams)) {
3905     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3906     if (ParamDecl->getDeclName())
3907       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3908   }
3909 }
3910 
3911 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3912   if (ConstraintExpr.isInvalid())
3913     return ExprError();
3914   return CorrectDelayedTyposInExpr(ConstraintExpr);
3915 }
3916 
3917 /// This is invoked after parsing an in-class initializer for a
3918 /// non-static C++ class member, and after instantiating an in-class initializer
3919 /// in a class template. Such actions are deferred until the class is complete.
3920 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3921                                                   SourceLocation InitLoc,
3922                                                   Expr *InitExpr) {
3923   // Pop the notional constructor scope we created earlier.
3924   PopFunctionScopeInfo(nullptr, D);
3925 
3926   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3927   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3928          "must set init style when field is created");
3929 
3930   if (!InitExpr) {
3931     D->setInvalidDecl();
3932     if (FD)
3933       FD->removeInClassInitializer();
3934     return;
3935   }
3936 
3937   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3938     FD->setInvalidDecl();
3939     FD->removeInClassInitializer();
3940     return;
3941   }
3942 
3943   ExprResult Init = InitExpr;
3944   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3945     InitializedEntity Entity =
3946         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3947     InitializationKind Kind =
3948         FD->getInClassInitStyle() == ICIS_ListInit
3949             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3950                                                    InitExpr->getBeginLoc(),
3951                                                    InitExpr->getEndLoc())
3952             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3953     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3954     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3955     if (Init.isInvalid()) {
3956       FD->setInvalidDecl();
3957       return;
3958     }
3959   }
3960 
3961   // C++11 [class.base.init]p7:
3962   //   The initialization of each base and member constitutes a
3963   //   full-expression.
3964   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3965   if (Init.isInvalid()) {
3966     FD->setInvalidDecl();
3967     return;
3968   }
3969 
3970   InitExpr = Init.get();
3971 
3972   FD->setInClassInitializer(InitExpr);
3973 }
3974 
3975 /// Find the direct and/or virtual base specifiers that
3976 /// correspond to the given base type, for use in base initialization
3977 /// within a constructor.
3978 static bool FindBaseInitializer(Sema &SemaRef,
3979                                 CXXRecordDecl *ClassDecl,
3980                                 QualType BaseType,
3981                                 const CXXBaseSpecifier *&DirectBaseSpec,
3982                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3983   // First, check for a direct base class.
3984   DirectBaseSpec = nullptr;
3985   for (const auto &Base : ClassDecl->bases()) {
3986     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3987       // We found a direct base of this type. That's what we're
3988       // initializing.
3989       DirectBaseSpec = &Base;
3990       break;
3991     }
3992   }
3993 
3994   // Check for a virtual base class.
3995   // FIXME: We might be able to short-circuit this if we know in advance that
3996   // there are no virtual bases.
3997   VirtualBaseSpec = nullptr;
3998   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3999     // We haven't found a base yet; search the class hierarchy for a
4000     // virtual base class.
4001     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4002                        /*DetectVirtual=*/false);
4003     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4004                               SemaRef.Context.getTypeDeclType(ClassDecl),
4005                               BaseType, Paths)) {
4006       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4007            Path != Paths.end(); ++Path) {
4008         if (Path->back().Base->isVirtual()) {
4009           VirtualBaseSpec = Path->back().Base;
4010           break;
4011         }
4012       }
4013     }
4014   }
4015 
4016   return DirectBaseSpec || VirtualBaseSpec;
4017 }
4018 
4019 /// Handle a C++ member initializer using braced-init-list syntax.
4020 MemInitResult
4021 Sema::ActOnMemInitializer(Decl *ConstructorD,
4022                           Scope *S,
4023                           CXXScopeSpec &SS,
4024                           IdentifierInfo *MemberOrBase,
4025                           ParsedType TemplateTypeTy,
4026                           const DeclSpec &DS,
4027                           SourceLocation IdLoc,
4028                           Expr *InitList,
4029                           SourceLocation EllipsisLoc) {
4030   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4031                              DS, IdLoc, InitList,
4032                              EllipsisLoc);
4033 }
4034 
4035 /// Handle a C++ member initializer using parentheses syntax.
4036 MemInitResult
4037 Sema::ActOnMemInitializer(Decl *ConstructorD,
4038                           Scope *S,
4039                           CXXScopeSpec &SS,
4040                           IdentifierInfo *MemberOrBase,
4041                           ParsedType TemplateTypeTy,
4042                           const DeclSpec &DS,
4043                           SourceLocation IdLoc,
4044                           SourceLocation LParenLoc,
4045                           ArrayRef<Expr *> Args,
4046                           SourceLocation RParenLoc,
4047                           SourceLocation EllipsisLoc) {
4048   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4049   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4050                              DS, IdLoc, List, EllipsisLoc);
4051 }
4052 
4053 namespace {
4054 
4055 // Callback to only accept typo corrections that can be a valid C++ member
4056 // intializer: either a non-static field member or a base class.
4057 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4058 public:
4059   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4060       : ClassDecl(ClassDecl) {}
4061 
4062   bool ValidateCandidate(const TypoCorrection &candidate) override {
4063     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4064       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4065         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4066       return isa<TypeDecl>(ND);
4067     }
4068     return false;
4069   }
4070 
4071   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4072     return std::make_unique<MemInitializerValidatorCCC>(*this);
4073   }
4074 
4075 private:
4076   CXXRecordDecl *ClassDecl;
4077 };
4078 
4079 }
4080 
4081 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4082                                              CXXScopeSpec &SS,
4083                                              ParsedType TemplateTypeTy,
4084                                              IdentifierInfo *MemberOrBase) {
4085   if (SS.getScopeRep() || TemplateTypeTy)
4086     return nullptr;
4087   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4088   if (Result.empty())
4089     return nullptr;
4090   ValueDecl *Member;
4091   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4092       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4093     return Member;
4094   return nullptr;
4095 }
4096 
4097 /// Handle a C++ member initializer.
4098 MemInitResult
4099 Sema::BuildMemInitializer(Decl *ConstructorD,
4100                           Scope *S,
4101                           CXXScopeSpec &SS,
4102                           IdentifierInfo *MemberOrBase,
4103                           ParsedType TemplateTypeTy,
4104                           const DeclSpec &DS,
4105                           SourceLocation IdLoc,
4106                           Expr *Init,
4107                           SourceLocation EllipsisLoc) {
4108   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4109   if (!Res.isUsable())
4110     return true;
4111   Init = Res.get();
4112 
4113   if (!ConstructorD)
4114     return true;
4115 
4116   AdjustDeclIfTemplate(ConstructorD);
4117 
4118   CXXConstructorDecl *Constructor
4119     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4120   if (!Constructor) {
4121     // The user wrote a constructor initializer on a function that is
4122     // not a C++ constructor. Ignore the error for now, because we may
4123     // have more member initializers coming; we'll diagnose it just
4124     // once in ActOnMemInitializers.
4125     return true;
4126   }
4127 
4128   CXXRecordDecl *ClassDecl = Constructor->getParent();
4129 
4130   // C++ [class.base.init]p2:
4131   //   Names in a mem-initializer-id are looked up in the scope of the
4132   //   constructor's class and, if not found in that scope, are looked
4133   //   up in the scope containing the constructor's definition.
4134   //   [Note: if the constructor's class contains a member with the
4135   //   same name as a direct or virtual base class of the class, a
4136   //   mem-initializer-id naming the member or base class and composed
4137   //   of a single identifier refers to the class member. A
4138   //   mem-initializer-id for the hidden base class may be specified
4139   //   using a qualified name. ]
4140 
4141   // Look for a member, first.
4142   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4143           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4144     if (EllipsisLoc.isValid())
4145       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4146           << MemberOrBase
4147           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4148 
4149     return BuildMemberInitializer(Member, Init, IdLoc);
4150   }
4151   // It didn't name a member, so see if it names a class.
4152   QualType BaseType;
4153   TypeSourceInfo *TInfo = nullptr;
4154 
4155   if (TemplateTypeTy) {
4156     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4157     if (BaseType.isNull())
4158       return true;
4159   } else if (DS.getTypeSpecType() == TST_decltype) {
4160     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4161   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4162     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4163     return true;
4164   } else {
4165     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4166     LookupParsedName(R, S, &SS);
4167 
4168     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4169     if (!TyD) {
4170       if (R.isAmbiguous()) return true;
4171 
4172       // We don't want access-control diagnostics here.
4173       R.suppressDiagnostics();
4174 
4175       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4176         bool NotUnknownSpecialization = false;
4177         DeclContext *DC = computeDeclContext(SS, false);
4178         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4179           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4180 
4181         if (!NotUnknownSpecialization) {
4182           // When the scope specifier can refer to a member of an unknown
4183           // specialization, we take it as a type name.
4184           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4185                                        SS.getWithLocInContext(Context),
4186                                        *MemberOrBase, IdLoc);
4187           if (BaseType.isNull())
4188             return true;
4189 
4190           TInfo = Context.CreateTypeSourceInfo(BaseType);
4191           DependentNameTypeLoc TL =
4192               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4193           if (!TL.isNull()) {
4194             TL.setNameLoc(IdLoc);
4195             TL.setElaboratedKeywordLoc(SourceLocation());
4196             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4197           }
4198 
4199           R.clear();
4200           R.setLookupName(MemberOrBase);
4201         }
4202       }
4203 
4204       // If no results were found, try to correct typos.
4205       TypoCorrection Corr;
4206       MemInitializerValidatorCCC CCC(ClassDecl);
4207       if (R.empty() && BaseType.isNull() &&
4208           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4209                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4210         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4211           // We have found a non-static data member with a similar
4212           // name to what was typed; complain and initialize that
4213           // member.
4214           diagnoseTypo(Corr,
4215                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4216                          << MemberOrBase << true);
4217           return BuildMemberInitializer(Member, Init, IdLoc);
4218         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4219           const CXXBaseSpecifier *DirectBaseSpec;
4220           const CXXBaseSpecifier *VirtualBaseSpec;
4221           if (FindBaseInitializer(*this, ClassDecl,
4222                                   Context.getTypeDeclType(Type),
4223                                   DirectBaseSpec, VirtualBaseSpec)) {
4224             // We have found a direct or virtual base class with a
4225             // similar name to what was typed; complain and initialize
4226             // that base class.
4227             diagnoseTypo(Corr,
4228                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4229                            << MemberOrBase << false,
4230                          PDiag() /*Suppress note, we provide our own.*/);
4231 
4232             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4233                                                               : VirtualBaseSpec;
4234             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4235                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4236 
4237             TyD = Type;
4238           }
4239         }
4240       }
4241 
4242       if (!TyD && BaseType.isNull()) {
4243         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4244           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4245         return true;
4246       }
4247     }
4248 
4249     if (BaseType.isNull()) {
4250       BaseType = Context.getTypeDeclType(TyD);
4251       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4252       if (SS.isSet()) {
4253         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4254                                              BaseType);
4255         TInfo = Context.CreateTypeSourceInfo(BaseType);
4256         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4257         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4258         TL.setElaboratedKeywordLoc(SourceLocation());
4259         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4260       }
4261     }
4262   }
4263 
4264   if (!TInfo)
4265     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4266 
4267   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4268 }
4269 
4270 MemInitResult
4271 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4272                              SourceLocation IdLoc) {
4273   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4274   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4275   assert((DirectMember || IndirectMember) &&
4276          "Member must be a FieldDecl or IndirectFieldDecl");
4277 
4278   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4279     return true;
4280 
4281   if (Member->isInvalidDecl())
4282     return true;
4283 
4284   MultiExprArg Args;
4285   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4286     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4287   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4288     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4289   } else {
4290     // Template instantiation doesn't reconstruct ParenListExprs for us.
4291     Args = Init;
4292   }
4293 
4294   SourceRange InitRange = Init->getSourceRange();
4295 
4296   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4297     // Can't check initialization for a member of dependent type or when
4298     // any of the arguments are type-dependent expressions.
4299     DiscardCleanupsInEvaluationContext();
4300   } else {
4301     bool InitList = false;
4302     if (isa<InitListExpr>(Init)) {
4303       InitList = true;
4304       Args = Init;
4305     }
4306 
4307     // Initialize the member.
4308     InitializedEntity MemberEntity =
4309       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4310                    : InitializedEntity::InitializeMember(IndirectMember,
4311                                                          nullptr);
4312     InitializationKind Kind =
4313         InitList ? InitializationKind::CreateDirectList(
4314                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4315                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4316                                                     InitRange.getEnd());
4317 
4318     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4319     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4320                                             nullptr);
4321     if (MemberInit.isInvalid())
4322       return true;
4323 
4324     // C++11 [class.base.init]p7:
4325     //   The initialization of each base and member constitutes a
4326     //   full-expression.
4327     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4328                                      /*DiscardedValue*/ false);
4329     if (MemberInit.isInvalid())
4330       return true;
4331 
4332     Init = MemberInit.get();
4333   }
4334 
4335   if (DirectMember) {
4336     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4337                                             InitRange.getBegin(), Init,
4338                                             InitRange.getEnd());
4339   } else {
4340     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4341                                             InitRange.getBegin(), Init,
4342                                             InitRange.getEnd());
4343   }
4344 }
4345 
4346 MemInitResult
4347 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4348                                  CXXRecordDecl *ClassDecl) {
4349   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4350   if (!LangOpts.CPlusPlus11)
4351     return Diag(NameLoc, diag::err_delegating_ctor)
4352       << TInfo->getTypeLoc().getLocalSourceRange();
4353   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4354 
4355   bool InitList = true;
4356   MultiExprArg Args = Init;
4357   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4358     InitList = false;
4359     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4360   }
4361 
4362   SourceRange InitRange = Init->getSourceRange();
4363   // Initialize the object.
4364   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4365                                      QualType(ClassDecl->getTypeForDecl(), 0));
4366   InitializationKind Kind =
4367       InitList ? InitializationKind::CreateDirectList(
4368                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4369                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4370                                                   InitRange.getEnd());
4371   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4372   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4373                                               Args, nullptr);
4374   if (DelegationInit.isInvalid())
4375     return true;
4376 
4377   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4378          "Delegating constructor with no target?");
4379 
4380   // C++11 [class.base.init]p7:
4381   //   The initialization of each base and member constitutes a
4382   //   full-expression.
4383   DelegationInit = ActOnFinishFullExpr(
4384       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4385   if (DelegationInit.isInvalid())
4386     return true;
4387 
4388   // If we are in a dependent context, template instantiation will
4389   // perform this type-checking again. Just save the arguments that we
4390   // received in a ParenListExpr.
4391   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4392   // of the information that we have about the base
4393   // initializer. However, deconstructing the ASTs is a dicey process,
4394   // and this approach is far more likely to get the corner cases right.
4395   if (CurContext->isDependentContext())
4396     DelegationInit = Init;
4397 
4398   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4399                                           DelegationInit.getAs<Expr>(),
4400                                           InitRange.getEnd());
4401 }
4402 
4403 MemInitResult
4404 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4405                            Expr *Init, CXXRecordDecl *ClassDecl,
4406                            SourceLocation EllipsisLoc) {
4407   SourceLocation BaseLoc
4408     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4409 
4410   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4411     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4412              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4413 
4414   // C++ [class.base.init]p2:
4415   //   [...] Unless the mem-initializer-id names a nonstatic data
4416   //   member of the constructor's class or a direct or virtual base
4417   //   of that class, the mem-initializer is ill-formed. A
4418   //   mem-initializer-list can initialize a base class using any
4419   //   name that denotes that base class type.
4420   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4421 
4422   SourceRange InitRange = Init->getSourceRange();
4423   if (EllipsisLoc.isValid()) {
4424     // This is a pack expansion.
4425     if (!BaseType->containsUnexpandedParameterPack())  {
4426       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4427         << SourceRange(BaseLoc, InitRange.getEnd());
4428 
4429       EllipsisLoc = SourceLocation();
4430     }
4431   } else {
4432     // Check for any unexpanded parameter packs.
4433     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4434       return true;
4435 
4436     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4437       return true;
4438   }
4439 
4440   // Check for direct and virtual base classes.
4441   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4442   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4443   if (!Dependent) {
4444     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4445                                        BaseType))
4446       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4447 
4448     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4449                         VirtualBaseSpec);
4450 
4451     // C++ [base.class.init]p2:
4452     // Unless the mem-initializer-id names a nonstatic data member of the
4453     // constructor's class or a direct or virtual base of that class, the
4454     // mem-initializer is ill-formed.
4455     if (!DirectBaseSpec && !VirtualBaseSpec) {
4456       // If the class has any dependent bases, then it's possible that
4457       // one of those types will resolve to the same type as
4458       // BaseType. Therefore, just treat this as a dependent base
4459       // class initialization.  FIXME: Should we try to check the
4460       // initialization anyway? It seems odd.
4461       if (ClassDecl->hasAnyDependentBases())
4462         Dependent = true;
4463       else
4464         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4465           << BaseType << Context.getTypeDeclType(ClassDecl)
4466           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4467     }
4468   }
4469 
4470   if (Dependent) {
4471     DiscardCleanupsInEvaluationContext();
4472 
4473     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4474                                             /*IsVirtual=*/false,
4475                                             InitRange.getBegin(), Init,
4476                                             InitRange.getEnd(), EllipsisLoc);
4477   }
4478 
4479   // C++ [base.class.init]p2:
4480   //   If a mem-initializer-id is ambiguous because it designates both
4481   //   a direct non-virtual base class and an inherited virtual base
4482   //   class, the mem-initializer is ill-formed.
4483   if (DirectBaseSpec && VirtualBaseSpec)
4484     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4485       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4486 
4487   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4488   if (!BaseSpec)
4489     BaseSpec = VirtualBaseSpec;
4490 
4491   // Initialize the base.
4492   bool InitList = true;
4493   MultiExprArg Args = Init;
4494   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4495     InitList = false;
4496     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4497   }
4498 
4499   InitializedEntity BaseEntity =
4500     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4501   InitializationKind Kind =
4502       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4503                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4504                                                   InitRange.getEnd());
4505   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4506   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4507   if (BaseInit.isInvalid())
4508     return true;
4509 
4510   // C++11 [class.base.init]p7:
4511   //   The initialization of each base and member constitutes a
4512   //   full-expression.
4513   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4514                                  /*DiscardedValue*/ false);
4515   if (BaseInit.isInvalid())
4516     return true;
4517 
4518   // If we are in a dependent context, template instantiation will
4519   // perform this type-checking again. Just save the arguments that we
4520   // received in a ParenListExpr.
4521   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4522   // of the information that we have about the base
4523   // initializer. However, deconstructing the ASTs is a dicey process,
4524   // and this approach is far more likely to get the corner cases right.
4525   if (CurContext->isDependentContext())
4526     BaseInit = Init;
4527 
4528   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4529                                           BaseSpec->isVirtual(),
4530                                           InitRange.getBegin(),
4531                                           BaseInit.getAs<Expr>(),
4532                                           InitRange.getEnd(), EllipsisLoc);
4533 }
4534 
4535 // Create a static_cast\<T&&>(expr).
4536 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4537   if (T.isNull()) T = E->getType();
4538   QualType TargetType = SemaRef.BuildReferenceType(
4539       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4540   SourceLocation ExprLoc = E->getBeginLoc();
4541   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4542       TargetType, ExprLoc);
4543 
4544   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4545                                    SourceRange(ExprLoc, ExprLoc),
4546                                    E->getSourceRange()).get();
4547 }
4548 
4549 /// ImplicitInitializerKind - How an implicit base or member initializer should
4550 /// initialize its base or member.
4551 enum ImplicitInitializerKind {
4552   IIK_Default,
4553   IIK_Copy,
4554   IIK_Move,
4555   IIK_Inherit
4556 };
4557 
4558 static bool
4559 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4560                              ImplicitInitializerKind ImplicitInitKind,
4561                              CXXBaseSpecifier *BaseSpec,
4562                              bool IsInheritedVirtualBase,
4563                              CXXCtorInitializer *&CXXBaseInit) {
4564   InitializedEntity InitEntity
4565     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4566                                         IsInheritedVirtualBase);
4567 
4568   ExprResult BaseInit;
4569 
4570   switch (ImplicitInitKind) {
4571   case IIK_Inherit:
4572   case IIK_Default: {
4573     InitializationKind InitKind
4574       = InitializationKind::CreateDefault(Constructor->getLocation());
4575     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4576     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4577     break;
4578   }
4579 
4580   case IIK_Move:
4581   case IIK_Copy: {
4582     bool Moving = ImplicitInitKind == IIK_Move;
4583     ParmVarDecl *Param = Constructor->getParamDecl(0);
4584     QualType ParamType = Param->getType().getNonReferenceType();
4585 
4586     Expr *CopyCtorArg =
4587       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4588                           SourceLocation(), Param, false,
4589                           Constructor->getLocation(), ParamType,
4590                           VK_LValue, nullptr);
4591 
4592     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4593 
4594     // Cast to the base class to avoid ambiguities.
4595     QualType ArgTy =
4596       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4597                                        ParamType.getQualifiers());
4598 
4599     if (Moving) {
4600       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4601     }
4602 
4603     CXXCastPath BasePath;
4604     BasePath.push_back(BaseSpec);
4605     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4606                                             CK_UncheckedDerivedToBase,
4607                                             Moving ? VK_XValue : VK_LValue,
4608                                             &BasePath).get();
4609 
4610     InitializationKind InitKind
4611       = InitializationKind::CreateDirect(Constructor->getLocation(),
4612                                          SourceLocation(), SourceLocation());
4613     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4614     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4615     break;
4616   }
4617   }
4618 
4619   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4620   if (BaseInit.isInvalid())
4621     return true;
4622 
4623   CXXBaseInit =
4624     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4625                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4626                                                         SourceLocation()),
4627                                              BaseSpec->isVirtual(),
4628                                              SourceLocation(),
4629                                              BaseInit.getAs<Expr>(),
4630                                              SourceLocation(),
4631                                              SourceLocation());
4632 
4633   return false;
4634 }
4635 
4636 static bool RefersToRValueRef(Expr *MemRef) {
4637   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4638   return Referenced->getType()->isRValueReferenceType();
4639 }
4640 
4641 static bool
4642 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4643                                ImplicitInitializerKind ImplicitInitKind,
4644                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4645                                CXXCtorInitializer *&CXXMemberInit) {
4646   if (Field->isInvalidDecl())
4647     return true;
4648 
4649   SourceLocation Loc = Constructor->getLocation();
4650 
4651   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4652     bool Moving = ImplicitInitKind == IIK_Move;
4653     ParmVarDecl *Param = Constructor->getParamDecl(0);
4654     QualType ParamType = Param->getType().getNonReferenceType();
4655 
4656     // Suppress copying zero-width bitfields.
4657     if (Field->isZeroLengthBitField(SemaRef.Context))
4658       return false;
4659 
4660     Expr *MemberExprBase =
4661       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4662                           SourceLocation(), Param, false,
4663                           Loc, ParamType, VK_LValue, nullptr);
4664 
4665     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4666 
4667     if (Moving) {
4668       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4669     }
4670 
4671     // Build a reference to this field within the parameter.
4672     CXXScopeSpec SS;
4673     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4674                               Sema::LookupMemberName);
4675     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4676                                   : cast<ValueDecl>(Field), AS_public);
4677     MemberLookup.resolveKind();
4678     ExprResult CtorArg
4679       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4680                                          ParamType, Loc,
4681                                          /*IsArrow=*/false,
4682                                          SS,
4683                                          /*TemplateKWLoc=*/SourceLocation(),
4684                                          /*FirstQualifierInScope=*/nullptr,
4685                                          MemberLookup,
4686                                          /*TemplateArgs=*/nullptr,
4687                                          /*S*/nullptr);
4688     if (CtorArg.isInvalid())
4689       return true;
4690 
4691     // C++11 [class.copy]p15:
4692     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4693     //     with static_cast<T&&>(x.m);
4694     if (RefersToRValueRef(CtorArg.get())) {
4695       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4696     }
4697 
4698     InitializedEntity Entity =
4699         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4700                                                        /*Implicit*/ true)
4701                  : InitializedEntity::InitializeMember(Field, nullptr,
4702                                                        /*Implicit*/ true);
4703 
4704     // Direct-initialize to use the copy constructor.
4705     InitializationKind InitKind =
4706       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4707 
4708     Expr *CtorArgE = CtorArg.getAs<Expr>();
4709     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4710     ExprResult MemberInit =
4711         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4712     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4713     if (MemberInit.isInvalid())
4714       return true;
4715 
4716     if (Indirect)
4717       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4718           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4719     else
4720       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4721           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4722     return false;
4723   }
4724 
4725   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4726          "Unhandled implicit init kind!");
4727 
4728   QualType FieldBaseElementType =
4729     SemaRef.Context.getBaseElementType(Field->getType());
4730 
4731   if (FieldBaseElementType->isRecordType()) {
4732     InitializedEntity InitEntity =
4733         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4734                                                        /*Implicit*/ true)
4735                  : InitializedEntity::InitializeMember(Field, nullptr,
4736                                                        /*Implicit*/ true);
4737     InitializationKind InitKind =
4738       InitializationKind::CreateDefault(Loc);
4739 
4740     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4741     ExprResult MemberInit =
4742       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4743 
4744     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4745     if (MemberInit.isInvalid())
4746       return true;
4747 
4748     if (Indirect)
4749       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4750                                                                Indirect, Loc,
4751                                                                Loc,
4752                                                                MemberInit.get(),
4753                                                                Loc);
4754     else
4755       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4756                                                                Field, Loc, Loc,
4757                                                                MemberInit.get(),
4758                                                                Loc);
4759     return false;
4760   }
4761 
4762   if (!Field->getParent()->isUnion()) {
4763     if (FieldBaseElementType->isReferenceType()) {
4764       SemaRef.Diag(Constructor->getLocation(),
4765                    diag::err_uninitialized_member_in_ctor)
4766       << (int)Constructor->isImplicit()
4767       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4768       << 0 << Field->getDeclName();
4769       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4770       return true;
4771     }
4772 
4773     if (FieldBaseElementType.isConstQualified()) {
4774       SemaRef.Diag(Constructor->getLocation(),
4775                    diag::err_uninitialized_member_in_ctor)
4776       << (int)Constructor->isImplicit()
4777       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4778       << 1 << Field->getDeclName();
4779       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4780       return true;
4781     }
4782   }
4783 
4784   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4785     // ARC and Weak:
4786     //   Default-initialize Objective-C pointers to NULL.
4787     CXXMemberInit
4788       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4789                                                  Loc, Loc,
4790                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4791                                                  Loc);
4792     return false;
4793   }
4794 
4795   // Nothing to initialize.
4796   CXXMemberInit = nullptr;
4797   return false;
4798 }
4799 
4800 namespace {
4801 struct BaseAndFieldInfo {
4802   Sema &S;
4803   CXXConstructorDecl *Ctor;
4804   bool AnyErrorsInInits;
4805   ImplicitInitializerKind IIK;
4806   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4807   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4808   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4809 
4810   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4811     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4812     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4813     if (Ctor->getInheritedConstructor())
4814       IIK = IIK_Inherit;
4815     else if (Generated && Ctor->isCopyConstructor())
4816       IIK = IIK_Copy;
4817     else if (Generated && Ctor->isMoveConstructor())
4818       IIK = IIK_Move;
4819     else
4820       IIK = IIK_Default;
4821   }
4822 
4823   bool isImplicitCopyOrMove() const {
4824     switch (IIK) {
4825     case IIK_Copy:
4826     case IIK_Move:
4827       return true;
4828 
4829     case IIK_Default:
4830     case IIK_Inherit:
4831       return false;
4832     }
4833 
4834     llvm_unreachable("Invalid ImplicitInitializerKind!");
4835   }
4836 
4837   bool addFieldInitializer(CXXCtorInitializer *Init) {
4838     AllToInit.push_back(Init);
4839 
4840     // Check whether this initializer makes the field "used".
4841     if (Init->getInit()->HasSideEffects(S.Context))
4842       S.UnusedPrivateFields.remove(Init->getAnyMember());
4843 
4844     return false;
4845   }
4846 
4847   bool isInactiveUnionMember(FieldDecl *Field) {
4848     RecordDecl *Record = Field->getParent();
4849     if (!Record->isUnion())
4850       return false;
4851 
4852     if (FieldDecl *Active =
4853             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4854       return Active != Field->getCanonicalDecl();
4855 
4856     // In an implicit copy or move constructor, ignore any in-class initializer.
4857     if (isImplicitCopyOrMove())
4858       return true;
4859 
4860     // If there's no explicit initialization, the field is active only if it
4861     // has an in-class initializer...
4862     if (Field->hasInClassInitializer())
4863       return false;
4864     // ... or it's an anonymous struct or union whose class has an in-class
4865     // initializer.
4866     if (!Field->isAnonymousStructOrUnion())
4867       return true;
4868     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4869     return !FieldRD->hasInClassInitializer();
4870   }
4871 
4872   /// Determine whether the given field is, or is within, a union member
4873   /// that is inactive (because there was an initializer given for a different
4874   /// member of the union, or because the union was not initialized at all).
4875   bool isWithinInactiveUnionMember(FieldDecl *Field,
4876                                    IndirectFieldDecl *Indirect) {
4877     if (!Indirect)
4878       return isInactiveUnionMember(Field);
4879 
4880     for (auto *C : Indirect->chain()) {
4881       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4882       if (Field && isInactiveUnionMember(Field))
4883         return true;
4884     }
4885     return false;
4886   }
4887 };
4888 }
4889 
4890 /// Determine whether the given type is an incomplete or zero-lenfgth
4891 /// array type.
4892 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4893   if (T->isIncompleteArrayType())
4894     return true;
4895 
4896   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4897     if (!ArrayT->getSize())
4898       return true;
4899 
4900     T = ArrayT->getElementType();
4901   }
4902 
4903   return false;
4904 }
4905 
4906 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4907                                     FieldDecl *Field,
4908                                     IndirectFieldDecl *Indirect = nullptr) {
4909   if (Field->isInvalidDecl())
4910     return false;
4911 
4912   // Overwhelmingly common case: we have a direct initializer for this field.
4913   if (CXXCtorInitializer *Init =
4914           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4915     return Info.addFieldInitializer(Init);
4916 
4917   // C++11 [class.base.init]p8:
4918   //   if the entity is a non-static data member that has a
4919   //   brace-or-equal-initializer and either
4920   //   -- the constructor's class is a union and no other variant member of that
4921   //      union is designated by a mem-initializer-id or
4922   //   -- the constructor's class is not a union, and, if the entity is a member
4923   //      of an anonymous union, no other member of that union is designated by
4924   //      a mem-initializer-id,
4925   //   the entity is initialized as specified in [dcl.init].
4926   //
4927   // We also apply the same rules to handle anonymous structs within anonymous
4928   // unions.
4929   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4930     return false;
4931 
4932   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4933     ExprResult DIE =
4934         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4935     if (DIE.isInvalid())
4936       return true;
4937 
4938     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4939     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4940 
4941     CXXCtorInitializer *Init;
4942     if (Indirect)
4943       Init = new (SemaRef.Context)
4944           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4945                              SourceLocation(), DIE.get(), SourceLocation());
4946     else
4947       Init = new (SemaRef.Context)
4948           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4949                              SourceLocation(), DIE.get(), SourceLocation());
4950     return Info.addFieldInitializer(Init);
4951   }
4952 
4953   // Don't initialize incomplete or zero-length arrays.
4954   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4955     return false;
4956 
4957   // Don't try to build an implicit initializer if there were semantic
4958   // errors in any of the initializers (and therefore we might be
4959   // missing some that the user actually wrote).
4960   if (Info.AnyErrorsInInits)
4961     return false;
4962 
4963   CXXCtorInitializer *Init = nullptr;
4964   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4965                                      Indirect, Init))
4966     return true;
4967 
4968   if (!Init)
4969     return false;
4970 
4971   return Info.addFieldInitializer(Init);
4972 }
4973 
4974 bool
4975 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4976                                CXXCtorInitializer *Initializer) {
4977   assert(Initializer->isDelegatingInitializer());
4978   Constructor->setNumCtorInitializers(1);
4979   CXXCtorInitializer **initializer =
4980     new (Context) CXXCtorInitializer*[1];
4981   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4982   Constructor->setCtorInitializers(initializer);
4983 
4984   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4985     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4986     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4987   }
4988 
4989   DelegatingCtorDecls.push_back(Constructor);
4990 
4991   DiagnoseUninitializedFields(*this, Constructor);
4992 
4993   return false;
4994 }
4995 
4996 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4997                                ArrayRef<CXXCtorInitializer *> Initializers) {
4998   if (Constructor->isDependentContext()) {
4999     // Just store the initializers as written, they will be checked during
5000     // instantiation.
5001     if (!Initializers.empty()) {
5002       Constructor->setNumCtorInitializers(Initializers.size());
5003       CXXCtorInitializer **baseOrMemberInitializers =
5004         new (Context) CXXCtorInitializer*[Initializers.size()];
5005       memcpy(baseOrMemberInitializers, Initializers.data(),
5006              Initializers.size() * sizeof(CXXCtorInitializer*));
5007       Constructor->setCtorInitializers(baseOrMemberInitializers);
5008     }
5009 
5010     // Let template instantiation know whether we had errors.
5011     if (AnyErrors)
5012       Constructor->setInvalidDecl();
5013 
5014     return false;
5015   }
5016 
5017   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5018 
5019   // We need to build the initializer AST according to order of construction
5020   // and not what user specified in the Initializers list.
5021   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5022   if (!ClassDecl)
5023     return true;
5024 
5025   bool HadError = false;
5026 
5027   for (unsigned i = 0; i < Initializers.size(); i++) {
5028     CXXCtorInitializer *Member = Initializers[i];
5029 
5030     if (Member->isBaseInitializer())
5031       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5032     else {
5033       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5034 
5035       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5036         for (auto *C : F->chain()) {
5037           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5038           if (FD && FD->getParent()->isUnion())
5039             Info.ActiveUnionMember.insert(std::make_pair(
5040                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5041         }
5042       } else if (FieldDecl *FD = Member->getMember()) {
5043         if (FD->getParent()->isUnion())
5044           Info.ActiveUnionMember.insert(std::make_pair(
5045               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5046       }
5047     }
5048   }
5049 
5050   // Keep track of the direct virtual bases.
5051   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5052   for (auto &I : ClassDecl->bases()) {
5053     if (I.isVirtual())
5054       DirectVBases.insert(&I);
5055   }
5056 
5057   // Push virtual bases before others.
5058   for (auto &VBase : ClassDecl->vbases()) {
5059     if (CXXCtorInitializer *Value
5060         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5061       // [class.base.init]p7, per DR257:
5062       //   A mem-initializer where the mem-initializer-id names a virtual base
5063       //   class is ignored during execution of a constructor of any class that
5064       //   is not the most derived class.
5065       if (ClassDecl->isAbstract()) {
5066         // FIXME: Provide a fixit to remove the base specifier. This requires
5067         // tracking the location of the associated comma for a base specifier.
5068         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5069           << VBase.getType() << ClassDecl;
5070         DiagnoseAbstractType(ClassDecl);
5071       }
5072 
5073       Info.AllToInit.push_back(Value);
5074     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5075       // [class.base.init]p8, per DR257:
5076       //   If a given [...] base class is not named by a mem-initializer-id
5077       //   [...] and the entity is not a virtual base class of an abstract
5078       //   class, then [...] the entity is default-initialized.
5079       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5080       CXXCtorInitializer *CXXBaseInit;
5081       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5082                                        &VBase, IsInheritedVirtualBase,
5083                                        CXXBaseInit)) {
5084         HadError = true;
5085         continue;
5086       }
5087 
5088       Info.AllToInit.push_back(CXXBaseInit);
5089     }
5090   }
5091 
5092   // Non-virtual bases.
5093   for (auto &Base : ClassDecl->bases()) {
5094     // Virtuals are in the virtual base list and already constructed.
5095     if (Base.isVirtual())
5096       continue;
5097 
5098     if (CXXCtorInitializer *Value
5099           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5100       Info.AllToInit.push_back(Value);
5101     } else if (!AnyErrors) {
5102       CXXCtorInitializer *CXXBaseInit;
5103       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5104                                        &Base, /*IsInheritedVirtualBase=*/false,
5105                                        CXXBaseInit)) {
5106         HadError = true;
5107         continue;
5108       }
5109 
5110       Info.AllToInit.push_back(CXXBaseInit);
5111     }
5112   }
5113 
5114   // Fields.
5115   for (auto *Mem : ClassDecl->decls()) {
5116     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5117       // C++ [class.bit]p2:
5118       //   A declaration for a bit-field that omits the identifier declares an
5119       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5120       //   initialized.
5121       if (F->isUnnamedBitfield())
5122         continue;
5123 
5124       // If we're not generating the implicit copy/move constructor, then we'll
5125       // handle anonymous struct/union fields based on their individual
5126       // indirect fields.
5127       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5128         continue;
5129 
5130       if (CollectFieldInitializer(*this, Info, F))
5131         HadError = true;
5132       continue;
5133     }
5134 
5135     // Beyond this point, we only consider default initialization.
5136     if (Info.isImplicitCopyOrMove())
5137       continue;
5138 
5139     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5140       if (F->getType()->isIncompleteArrayType()) {
5141         assert(ClassDecl->hasFlexibleArrayMember() &&
5142                "Incomplete array type is not valid");
5143         continue;
5144       }
5145 
5146       // Initialize each field of an anonymous struct individually.
5147       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5148         HadError = true;
5149 
5150       continue;
5151     }
5152   }
5153 
5154   unsigned NumInitializers = Info.AllToInit.size();
5155   if (NumInitializers > 0) {
5156     Constructor->setNumCtorInitializers(NumInitializers);
5157     CXXCtorInitializer **baseOrMemberInitializers =
5158       new (Context) CXXCtorInitializer*[NumInitializers];
5159     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5160            NumInitializers * sizeof(CXXCtorInitializer*));
5161     Constructor->setCtorInitializers(baseOrMemberInitializers);
5162 
5163     // Constructors implicitly reference the base and member
5164     // destructors.
5165     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5166                                            Constructor->getParent());
5167   }
5168 
5169   return HadError;
5170 }
5171 
5172 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5173   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5174     const RecordDecl *RD = RT->getDecl();
5175     if (RD->isAnonymousStructOrUnion()) {
5176       for (auto *Field : RD->fields())
5177         PopulateKeysForFields(Field, IdealInits);
5178       return;
5179     }
5180   }
5181   IdealInits.push_back(Field->getCanonicalDecl());
5182 }
5183 
5184 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5185   return Context.getCanonicalType(BaseType).getTypePtr();
5186 }
5187 
5188 static const void *GetKeyForMember(ASTContext &Context,
5189                                    CXXCtorInitializer *Member) {
5190   if (!Member->isAnyMemberInitializer())
5191     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5192 
5193   return Member->getAnyMember()->getCanonicalDecl();
5194 }
5195 
5196 static void DiagnoseBaseOrMemInitializerOrder(
5197     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5198     ArrayRef<CXXCtorInitializer *> Inits) {
5199   if (Constructor->getDeclContext()->isDependentContext())
5200     return;
5201 
5202   // Don't check initializers order unless the warning is enabled at the
5203   // location of at least one initializer.
5204   bool ShouldCheckOrder = false;
5205   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5206     CXXCtorInitializer *Init = Inits[InitIndex];
5207     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5208                                  Init->getSourceLocation())) {
5209       ShouldCheckOrder = true;
5210       break;
5211     }
5212   }
5213   if (!ShouldCheckOrder)
5214     return;
5215 
5216   // Build the list of bases and members in the order that they'll
5217   // actually be initialized.  The explicit initializers should be in
5218   // this same order but may be missing things.
5219   SmallVector<const void*, 32> IdealInitKeys;
5220 
5221   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5222 
5223   // 1. Virtual bases.
5224   for (const auto &VBase : ClassDecl->vbases())
5225     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5226 
5227   // 2. Non-virtual bases.
5228   for (const auto &Base : ClassDecl->bases()) {
5229     if (Base.isVirtual())
5230       continue;
5231     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5232   }
5233 
5234   // 3. Direct fields.
5235   for (auto *Field : ClassDecl->fields()) {
5236     if (Field->isUnnamedBitfield())
5237       continue;
5238 
5239     PopulateKeysForFields(Field, IdealInitKeys);
5240   }
5241 
5242   unsigned NumIdealInits = IdealInitKeys.size();
5243   unsigned IdealIndex = 0;
5244 
5245   CXXCtorInitializer *PrevInit = nullptr;
5246   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5247     CXXCtorInitializer *Init = Inits[InitIndex];
5248     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5249 
5250     // Scan forward to try to find this initializer in the idealized
5251     // initializers list.
5252     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5253       if (InitKey == IdealInitKeys[IdealIndex])
5254         break;
5255 
5256     // If we didn't find this initializer, it must be because we
5257     // scanned past it on a previous iteration.  That can only
5258     // happen if we're out of order;  emit a warning.
5259     if (IdealIndex == NumIdealInits && PrevInit) {
5260       Sema::SemaDiagnosticBuilder D =
5261         SemaRef.Diag(PrevInit->getSourceLocation(),
5262                      diag::warn_initializer_out_of_order);
5263 
5264       if (PrevInit->isAnyMemberInitializer())
5265         D << 0 << PrevInit->getAnyMember()->getDeclName();
5266       else
5267         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5268 
5269       if (Init->isAnyMemberInitializer())
5270         D << 0 << Init->getAnyMember()->getDeclName();
5271       else
5272         D << 1 << Init->getTypeSourceInfo()->getType();
5273 
5274       // Move back to the initializer's location in the ideal list.
5275       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5276         if (InitKey == IdealInitKeys[IdealIndex])
5277           break;
5278 
5279       assert(IdealIndex < NumIdealInits &&
5280              "initializer not found in initializer list");
5281     }
5282 
5283     PrevInit = Init;
5284   }
5285 }
5286 
5287 namespace {
5288 bool CheckRedundantInit(Sema &S,
5289                         CXXCtorInitializer *Init,
5290                         CXXCtorInitializer *&PrevInit) {
5291   if (!PrevInit) {
5292     PrevInit = Init;
5293     return false;
5294   }
5295 
5296   if (FieldDecl *Field = Init->getAnyMember())
5297     S.Diag(Init->getSourceLocation(),
5298            diag::err_multiple_mem_initialization)
5299       << Field->getDeclName()
5300       << Init->getSourceRange();
5301   else {
5302     const Type *BaseClass = Init->getBaseClass();
5303     assert(BaseClass && "neither field nor base");
5304     S.Diag(Init->getSourceLocation(),
5305            diag::err_multiple_base_initialization)
5306       << QualType(BaseClass, 0)
5307       << Init->getSourceRange();
5308   }
5309   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5310     << 0 << PrevInit->getSourceRange();
5311 
5312   return true;
5313 }
5314 
5315 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5316 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5317 
5318 bool CheckRedundantUnionInit(Sema &S,
5319                              CXXCtorInitializer *Init,
5320                              RedundantUnionMap &Unions) {
5321   FieldDecl *Field = Init->getAnyMember();
5322   RecordDecl *Parent = Field->getParent();
5323   NamedDecl *Child = Field;
5324 
5325   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5326     if (Parent->isUnion()) {
5327       UnionEntry &En = Unions[Parent];
5328       if (En.first && En.first != Child) {
5329         S.Diag(Init->getSourceLocation(),
5330                diag::err_multiple_mem_union_initialization)
5331           << Field->getDeclName()
5332           << Init->getSourceRange();
5333         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5334           << 0 << En.second->getSourceRange();
5335         return true;
5336       }
5337       if (!En.first) {
5338         En.first = Child;
5339         En.second = Init;
5340       }
5341       if (!Parent->isAnonymousStructOrUnion())
5342         return false;
5343     }
5344 
5345     Child = Parent;
5346     Parent = cast<RecordDecl>(Parent->getDeclContext());
5347   }
5348 
5349   return false;
5350 }
5351 }
5352 
5353 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5354 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5355                                 SourceLocation ColonLoc,
5356                                 ArrayRef<CXXCtorInitializer*> MemInits,
5357                                 bool AnyErrors) {
5358   if (!ConstructorDecl)
5359     return;
5360 
5361   AdjustDeclIfTemplate(ConstructorDecl);
5362 
5363   CXXConstructorDecl *Constructor
5364     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5365 
5366   if (!Constructor) {
5367     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5368     return;
5369   }
5370 
5371   // Mapping for the duplicate initializers check.
5372   // For member initializers, this is keyed with a FieldDecl*.
5373   // For base initializers, this is keyed with a Type*.
5374   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5375 
5376   // Mapping for the inconsistent anonymous-union initializers check.
5377   RedundantUnionMap MemberUnions;
5378 
5379   bool HadError = false;
5380   for (unsigned i = 0; i < MemInits.size(); i++) {
5381     CXXCtorInitializer *Init = MemInits[i];
5382 
5383     // Set the source order index.
5384     Init->setSourceOrder(i);
5385 
5386     if (Init->isAnyMemberInitializer()) {
5387       const void *Key = GetKeyForMember(Context, Init);
5388       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5389           CheckRedundantUnionInit(*this, Init, MemberUnions))
5390         HadError = true;
5391     } else if (Init->isBaseInitializer()) {
5392       const void *Key = GetKeyForMember(Context, Init);
5393       if (CheckRedundantInit(*this, Init, Members[Key]))
5394         HadError = true;
5395     } else {
5396       assert(Init->isDelegatingInitializer());
5397       // This must be the only initializer
5398       if (MemInits.size() != 1) {
5399         Diag(Init->getSourceLocation(),
5400              diag::err_delegating_initializer_alone)
5401           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5402         // We will treat this as being the only initializer.
5403       }
5404       SetDelegatingInitializer(Constructor, MemInits[i]);
5405       // Return immediately as the initializer is set.
5406       return;
5407     }
5408   }
5409 
5410   if (HadError)
5411     return;
5412 
5413   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5414 
5415   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5416 
5417   DiagnoseUninitializedFields(*this, Constructor);
5418 }
5419 
5420 void
5421 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5422                                              CXXRecordDecl *ClassDecl) {
5423   // Ignore dependent contexts. Also ignore unions, since their members never
5424   // have destructors implicitly called.
5425   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5426     return;
5427 
5428   // FIXME: all the access-control diagnostics are positioned on the
5429   // field/base declaration.  That's probably good; that said, the
5430   // user might reasonably want to know why the destructor is being
5431   // emitted, and we currently don't say.
5432 
5433   // Non-static data members.
5434   for (auto *Field : ClassDecl->fields()) {
5435     if (Field->isInvalidDecl())
5436       continue;
5437 
5438     // Don't destroy incomplete or zero-length arrays.
5439     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5440       continue;
5441 
5442     QualType FieldType = Context.getBaseElementType(Field->getType());
5443 
5444     const RecordType* RT = FieldType->getAs<RecordType>();
5445     if (!RT)
5446       continue;
5447 
5448     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5449     if (FieldClassDecl->isInvalidDecl())
5450       continue;
5451     if (FieldClassDecl->hasIrrelevantDestructor())
5452       continue;
5453     // The destructor for an implicit anonymous union member is never invoked.
5454     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5455       continue;
5456 
5457     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5458     assert(Dtor && "No dtor found for FieldClassDecl!");
5459     CheckDestructorAccess(Field->getLocation(), Dtor,
5460                           PDiag(diag::err_access_dtor_field)
5461                             << Field->getDeclName()
5462                             << FieldType);
5463 
5464     MarkFunctionReferenced(Location, Dtor);
5465     DiagnoseUseOfDecl(Dtor, Location);
5466   }
5467 
5468   // We only potentially invoke the destructors of potentially constructed
5469   // subobjects.
5470   bool VisitVirtualBases = !ClassDecl->isAbstract();
5471 
5472   // If the destructor exists and has already been marked used in the MS ABI,
5473   // then virtual base destructors have already been checked and marked used.
5474   // Skip checking them again to avoid duplicate diagnostics.
5475   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5476     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5477     if (Dtor && Dtor->isUsed())
5478       VisitVirtualBases = false;
5479   }
5480 
5481   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5482 
5483   // Bases.
5484   for (const auto &Base : ClassDecl->bases()) {
5485     // Bases are always records in a well-formed non-dependent class.
5486     const RecordType *RT = Base.getType()->getAs<RecordType>();
5487 
5488     // Remember direct virtual bases.
5489     if (Base.isVirtual()) {
5490       if (!VisitVirtualBases)
5491         continue;
5492       DirectVirtualBases.insert(RT);
5493     }
5494 
5495     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5496     // If our base class is invalid, we probably can't get its dtor anyway.
5497     if (BaseClassDecl->isInvalidDecl())
5498       continue;
5499     if (BaseClassDecl->hasIrrelevantDestructor())
5500       continue;
5501 
5502     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5503     assert(Dtor && "No dtor found for BaseClassDecl!");
5504 
5505     // FIXME: caret should be on the start of the class name
5506     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5507                           PDiag(diag::err_access_dtor_base)
5508                               << Base.getType() << Base.getSourceRange(),
5509                           Context.getTypeDeclType(ClassDecl));
5510 
5511     MarkFunctionReferenced(Location, Dtor);
5512     DiagnoseUseOfDecl(Dtor, Location);
5513   }
5514 
5515   if (VisitVirtualBases)
5516     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5517                                          &DirectVirtualBases);
5518 }
5519 
5520 void Sema::MarkVirtualBaseDestructorsReferenced(
5521     SourceLocation Location, CXXRecordDecl *ClassDecl,
5522     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5523   // Virtual bases.
5524   for (const auto &VBase : ClassDecl->vbases()) {
5525     // Bases are always records in a well-formed non-dependent class.
5526     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5527 
5528     // Ignore already visited direct virtual bases.
5529     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5530       continue;
5531 
5532     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5533     // If our base class is invalid, we probably can't get its dtor anyway.
5534     if (BaseClassDecl->isInvalidDecl())
5535       continue;
5536     if (BaseClassDecl->hasIrrelevantDestructor())
5537       continue;
5538 
5539     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5540     assert(Dtor && "No dtor found for BaseClassDecl!");
5541     if (CheckDestructorAccess(
5542             ClassDecl->getLocation(), Dtor,
5543             PDiag(diag::err_access_dtor_vbase)
5544                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5545             Context.getTypeDeclType(ClassDecl)) ==
5546         AR_accessible) {
5547       CheckDerivedToBaseConversion(
5548           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5549           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5550           SourceRange(), DeclarationName(), nullptr);
5551     }
5552 
5553     MarkFunctionReferenced(Location, Dtor);
5554     DiagnoseUseOfDecl(Dtor, Location);
5555   }
5556 }
5557 
5558 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5559   if (!CDtorDecl)
5560     return;
5561 
5562   if (CXXConstructorDecl *Constructor
5563       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5564     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5565     DiagnoseUninitializedFields(*this, Constructor);
5566   }
5567 }
5568 
5569 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5570   if (!getLangOpts().CPlusPlus)
5571     return false;
5572 
5573   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5574   if (!RD)
5575     return false;
5576 
5577   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5578   // class template specialization here, but doing so breaks a lot of code.
5579 
5580   // We can't answer whether something is abstract until it has a
5581   // definition. If it's currently being defined, we'll walk back
5582   // over all the declarations when we have a full definition.
5583   const CXXRecordDecl *Def = RD->getDefinition();
5584   if (!Def || Def->isBeingDefined())
5585     return false;
5586 
5587   return RD->isAbstract();
5588 }
5589 
5590 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5591                                   TypeDiagnoser &Diagnoser) {
5592   if (!isAbstractType(Loc, T))
5593     return false;
5594 
5595   T = Context.getBaseElementType(T);
5596   Diagnoser.diagnose(*this, Loc, T);
5597   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5598   return true;
5599 }
5600 
5601 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5602   // Check if we've already emitted the list of pure virtual functions
5603   // for this class.
5604   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5605     return;
5606 
5607   // If the diagnostic is suppressed, don't emit the notes. We're only
5608   // going to emit them once, so try to attach them to a diagnostic we're
5609   // actually going to show.
5610   if (Diags.isLastDiagnosticIgnored())
5611     return;
5612 
5613   CXXFinalOverriderMap FinalOverriders;
5614   RD->getFinalOverriders(FinalOverriders);
5615 
5616   // Keep a set of seen pure methods so we won't diagnose the same method
5617   // more than once.
5618   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5619 
5620   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5621                                    MEnd = FinalOverriders.end();
5622        M != MEnd;
5623        ++M) {
5624     for (OverridingMethods::iterator SO = M->second.begin(),
5625                                   SOEnd = M->second.end();
5626          SO != SOEnd; ++SO) {
5627       // C++ [class.abstract]p4:
5628       //   A class is abstract if it contains or inherits at least one
5629       //   pure virtual function for which the final overrider is pure
5630       //   virtual.
5631 
5632       //
5633       if (SO->second.size() != 1)
5634         continue;
5635 
5636       if (!SO->second.front().Method->isPure())
5637         continue;
5638 
5639       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5640         continue;
5641 
5642       Diag(SO->second.front().Method->getLocation(),
5643            diag::note_pure_virtual_function)
5644         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5645     }
5646   }
5647 
5648   if (!PureVirtualClassDiagSet)
5649     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5650   PureVirtualClassDiagSet->insert(RD);
5651 }
5652 
5653 namespace {
5654 struct AbstractUsageInfo {
5655   Sema &S;
5656   CXXRecordDecl *Record;
5657   CanQualType AbstractType;
5658   bool Invalid;
5659 
5660   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5661     : S(S), Record(Record),
5662       AbstractType(S.Context.getCanonicalType(
5663                    S.Context.getTypeDeclType(Record))),
5664       Invalid(false) {}
5665 
5666   void DiagnoseAbstractType() {
5667     if (Invalid) return;
5668     S.DiagnoseAbstractType(Record);
5669     Invalid = true;
5670   }
5671 
5672   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5673 };
5674 
5675 struct CheckAbstractUsage {
5676   AbstractUsageInfo &Info;
5677   const NamedDecl *Ctx;
5678 
5679   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5680     : Info(Info), Ctx(Ctx) {}
5681 
5682   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5683     switch (TL.getTypeLocClass()) {
5684 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5685 #define TYPELOC(CLASS, PARENT) \
5686     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5687 #include "clang/AST/TypeLocNodes.def"
5688     }
5689   }
5690 
5691   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5692     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5693     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5694       if (!TL.getParam(I))
5695         continue;
5696 
5697       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5698       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5699     }
5700   }
5701 
5702   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5703     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5704   }
5705 
5706   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5707     // Visit the type parameters from a permissive context.
5708     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5709       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5710       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5711         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5712           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5713       // TODO: other template argument types?
5714     }
5715   }
5716 
5717   // Visit pointee types from a permissive context.
5718 #define CheckPolymorphic(Type) \
5719   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5720     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5721   }
5722   CheckPolymorphic(PointerTypeLoc)
5723   CheckPolymorphic(ReferenceTypeLoc)
5724   CheckPolymorphic(MemberPointerTypeLoc)
5725   CheckPolymorphic(BlockPointerTypeLoc)
5726   CheckPolymorphic(AtomicTypeLoc)
5727 
5728   /// Handle all the types we haven't given a more specific
5729   /// implementation for above.
5730   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5731     // Every other kind of type that we haven't called out already
5732     // that has an inner type is either (1) sugar or (2) contains that
5733     // inner type in some way as a subobject.
5734     if (TypeLoc Next = TL.getNextTypeLoc())
5735       return Visit(Next, Sel);
5736 
5737     // If there's no inner type and we're in a permissive context,
5738     // don't diagnose.
5739     if (Sel == Sema::AbstractNone) return;
5740 
5741     // Check whether the type matches the abstract type.
5742     QualType T = TL.getType();
5743     if (T->isArrayType()) {
5744       Sel = Sema::AbstractArrayType;
5745       T = Info.S.Context.getBaseElementType(T);
5746     }
5747     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5748     if (CT != Info.AbstractType) return;
5749 
5750     // It matched; do some magic.
5751     if (Sel == Sema::AbstractArrayType) {
5752       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5753         << T << TL.getSourceRange();
5754     } else {
5755       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5756         << Sel << T << TL.getSourceRange();
5757     }
5758     Info.DiagnoseAbstractType();
5759   }
5760 };
5761 
5762 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5763                                   Sema::AbstractDiagSelID Sel) {
5764   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5765 }
5766 
5767 }
5768 
5769 /// Check for invalid uses of an abstract type in a method declaration.
5770 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5771                                     CXXMethodDecl *MD) {
5772   // No need to do the check on definitions, which require that
5773   // the return/param types be complete.
5774   if (MD->doesThisDeclarationHaveABody())
5775     return;
5776 
5777   // For safety's sake, just ignore it if we don't have type source
5778   // information.  This should never happen for non-implicit methods,
5779   // but...
5780   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5781     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5782 }
5783 
5784 /// Check for invalid uses of an abstract type within a class definition.
5785 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5786                                     CXXRecordDecl *RD) {
5787   for (auto *D : RD->decls()) {
5788     if (D->isImplicit()) continue;
5789 
5790     // Methods and method templates.
5791     if (isa<CXXMethodDecl>(D)) {
5792       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5793     } else if (isa<FunctionTemplateDecl>(D)) {
5794       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5795       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5796 
5797     // Fields and static variables.
5798     } else if (isa<FieldDecl>(D)) {
5799       FieldDecl *FD = cast<FieldDecl>(D);
5800       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5801         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5802     } else if (isa<VarDecl>(D)) {
5803       VarDecl *VD = cast<VarDecl>(D);
5804       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5805         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5806 
5807     // Nested classes and class templates.
5808     } else if (isa<CXXRecordDecl>(D)) {
5809       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5810     } else if (isa<ClassTemplateDecl>(D)) {
5811       CheckAbstractClassUsage(Info,
5812                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5813     }
5814   }
5815 }
5816 
5817 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5818   Attr *ClassAttr = getDLLAttr(Class);
5819   if (!ClassAttr)
5820     return;
5821 
5822   assert(ClassAttr->getKind() == attr::DLLExport);
5823 
5824   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5825 
5826   if (TSK == TSK_ExplicitInstantiationDeclaration)
5827     // Don't go any further if this is just an explicit instantiation
5828     // declaration.
5829     return;
5830 
5831   // Add a context note to explain how we got to any diagnostics produced below.
5832   struct MarkingClassDllexported {
5833     Sema &S;
5834     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5835                             SourceLocation AttrLoc)
5836         : S(S) {
5837       Sema::CodeSynthesisContext Ctx;
5838       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5839       Ctx.PointOfInstantiation = AttrLoc;
5840       Ctx.Entity = Class;
5841       S.pushCodeSynthesisContext(Ctx);
5842     }
5843     ~MarkingClassDllexported() {
5844       S.popCodeSynthesisContext();
5845     }
5846   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5847 
5848   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5849     S.MarkVTableUsed(Class->getLocation(), Class, true);
5850 
5851   for (Decl *Member : Class->decls()) {
5852     // Defined static variables that are members of an exported base
5853     // class must be marked export too.
5854     auto *VD = dyn_cast<VarDecl>(Member);
5855     if (VD && Member->getAttr<DLLExportAttr>() &&
5856         VD->getStorageClass() == SC_Static &&
5857         TSK == TSK_ImplicitInstantiation)
5858       S.MarkVariableReferenced(VD->getLocation(), VD);
5859 
5860     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5861     if (!MD)
5862       continue;
5863 
5864     if (Member->getAttr<DLLExportAttr>()) {
5865       if (MD->isUserProvided()) {
5866         // Instantiate non-default class member functions ...
5867 
5868         // .. except for certain kinds of template specializations.
5869         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5870           continue;
5871 
5872         S.MarkFunctionReferenced(Class->getLocation(), MD);
5873 
5874         // The function will be passed to the consumer when its definition is
5875         // encountered.
5876       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5877                  MD->isCopyAssignmentOperator() ||
5878                  MD->isMoveAssignmentOperator()) {
5879         // Synthesize and instantiate non-trivial implicit methods, explicitly
5880         // defaulted methods, and the copy and move assignment operators. The
5881         // latter are exported even if they are trivial, because the address of
5882         // an operator can be taken and should compare equal across libraries.
5883         S.MarkFunctionReferenced(Class->getLocation(), MD);
5884 
5885         // There is no later point when we will see the definition of this
5886         // function, so pass it to the consumer now.
5887         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5888       }
5889     }
5890   }
5891 }
5892 
5893 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5894                                                         CXXRecordDecl *Class) {
5895   // Only the MS ABI has default constructor closures, so we don't need to do
5896   // this semantic checking anywhere else.
5897   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5898     return;
5899 
5900   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5901   for (Decl *Member : Class->decls()) {
5902     // Look for exported default constructors.
5903     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5904     if (!CD || !CD->isDefaultConstructor())
5905       continue;
5906     auto *Attr = CD->getAttr<DLLExportAttr>();
5907     if (!Attr)
5908       continue;
5909 
5910     // If the class is non-dependent, mark the default arguments as ODR-used so
5911     // that we can properly codegen the constructor closure.
5912     if (!Class->isDependentContext()) {
5913       for (ParmVarDecl *PD : CD->parameters()) {
5914         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5915         S.DiscardCleanupsInEvaluationContext();
5916       }
5917     }
5918 
5919     if (LastExportedDefaultCtor) {
5920       S.Diag(LastExportedDefaultCtor->getLocation(),
5921              diag::err_attribute_dll_ambiguous_default_ctor)
5922           << Class;
5923       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5924           << CD->getDeclName();
5925       return;
5926     }
5927     LastExportedDefaultCtor = CD;
5928   }
5929 }
5930 
5931 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5932                                                        CXXRecordDecl *Class) {
5933   bool ErrorReported = false;
5934   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5935                                                      ClassTemplateDecl *TD) {
5936     if (ErrorReported)
5937       return;
5938     S.Diag(TD->getLocation(),
5939            diag::err_cuda_device_builtin_surftex_cls_template)
5940         << /*surface*/ 0 << TD;
5941     ErrorReported = true;
5942   };
5943 
5944   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5945   if (!TD) {
5946     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5947     if (!SD) {
5948       S.Diag(Class->getLocation(),
5949              diag::err_cuda_device_builtin_surftex_ref_decl)
5950           << /*surface*/ 0 << Class;
5951       S.Diag(Class->getLocation(),
5952              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5953           << Class;
5954       return;
5955     }
5956     TD = SD->getSpecializedTemplate();
5957   }
5958 
5959   TemplateParameterList *Params = TD->getTemplateParameters();
5960   unsigned N = Params->size();
5961 
5962   if (N != 2) {
5963     reportIllegalClassTemplate(S, TD);
5964     S.Diag(TD->getLocation(),
5965            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5966         << TD << 2;
5967   }
5968   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5969     reportIllegalClassTemplate(S, TD);
5970     S.Diag(TD->getLocation(),
5971            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5972         << TD << /*1st*/ 0 << /*type*/ 0;
5973   }
5974   if (N > 1) {
5975     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5976     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5977       reportIllegalClassTemplate(S, TD);
5978       S.Diag(TD->getLocation(),
5979              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5980           << TD << /*2nd*/ 1 << /*integer*/ 1;
5981     }
5982   }
5983 }
5984 
5985 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5986                                                        CXXRecordDecl *Class) {
5987   bool ErrorReported = false;
5988   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5989                                                      ClassTemplateDecl *TD) {
5990     if (ErrorReported)
5991       return;
5992     S.Diag(TD->getLocation(),
5993            diag::err_cuda_device_builtin_surftex_cls_template)
5994         << /*texture*/ 1 << TD;
5995     ErrorReported = true;
5996   };
5997 
5998   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5999   if (!TD) {
6000     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6001     if (!SD) {
6002       S.Diag(Class->getLocation(),
6003              diag::err_cuda_device_builtin_surftex_ref_decl)
6004           << /*texture*/ 1 << Class;
6005       S.Diag(Class->getLocation(),
6006              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6007           << Class;
6008       return;
6009     }
6010     TD = SD->getSpecializedTemplate();
6011   }
6012 
6013   TemplateParameterList *Params = TD->getTemplateParameters();
6014   unsigned N = Params->size();
6015 
6016   if (N != 3) {
6017     reportIllegalClassTemplate(S, TD);
6018     S.Diag(TD->getLocation(),
6019            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6020         << TD << 3;
6021   }
6022   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6023     reportIllegalClassTemplate(S, TD);
6024     S.Diag(TD->getLocation(),
6025            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6026         << TD << /*1st*/ 0 << /*type*/ 0;
6027   }
6028   if (N > 1) {
6029     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6030     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6031       reportIllegalClassTemplate(S, TD);
6032       S.Diag(TD->getLocation(),
6033              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6034           << TD << /*2nd*/ 1 << /*integer*/ 1;
6035     }
6036   }
6037   if (N > 2) {
6038     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6039     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6040       reportIllegalClassTemplate(S, TD);
6041       S.Diag(TD->getLocation(),
6042              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6043           << TD << /*3rd*/ 2 << /*integer*/ 1;
6044     }
6045   }
6046 }
6047 
6048 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6049   // Mark any compiler-generated routines with the implicit code_seg attribute.
6050   for (auto *Method : Class->methods()) {
6051     if (Method->isUserProvided())
6052       continue;
6053     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6054       Method->addAttr(A);
6055   }
6056 }
6057 
6058 /// Check class-level dllimport/dllexport attribute.
6059 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6060   Attr *ClassAttr = getDLLAttr(Class);
6061 
6062   // MSVC inherits DLL attributes to partial class template specializations.
6063   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6064        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) && !ClassAttr) {
6065     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6066       if (Attr *TemplateAttr =
6067               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6068         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6069         A->setInherited(true);
6070         ClassAttr = A;
6071       }
6072     }
6073   }
6074 
6075   if (!ClassAttr)
6076     return;
6077 
6078   if (!Class->isExternallyVisible()) {
6079     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6080         << Class << ClassAttr;
6081     return;
6082   }
6083 
6084   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6085        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
6086       !ClassAttr->isInherited()) {
6087     // Diagnose dll attributes on members of class with dll attribute.
6088     for (Decl *Member : Class->decls()) {
6089       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6090         continue;
6091       InheritableAttr *MemberAttr = getDLLAttr(Member);
6092       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6093         continue;
6094 
6095       Diag(MemberAttr->getLocation(),
6096              diag::err_attribute_dll_member_of_dll_class)
6097           << MemberAttr << ClassAttr;
6098       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6099       Member->setInvalidDecl();
6100     }
6101   }
6102 
6103   if (Class->getDescribedClassTemplate())
6104     // Don't inherit dll attribute until the template is instantiated.
6105     return;
6106 
6107   // The class is either imported or exported.
6108   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6109 
6110   // Check if this was a dllimport attribute propagated from a derived class to
6111   // a base class template specialization. We don't apply these attributes to
6112   // static data members.
6113   const bool PropagatedImport =
6114       !ClassExported &&
6115       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6116 
6117   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6118 
6119   // Ignore explicit dllexport on explicit class template instantiation
6120   // declarations, except in MinGW mode.
6121   if (ClassExported && !ClassAttr->isInherited() &&
6122       TSK == TSK_ExplicitInstantiationDeclaration &&
6123       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6124     Class->dropAttr<DLLExportAttr>();
6125     return;
6126   }
6127 
6128   // Force declaration of implicit members so they can inherit the attribute.
6129   ForceDeclarationOfImplicitMembers(Class);
6130 
6131   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6132   // seem to be true in practice?
6133 
6134   for (Decl *Member : Class->decls()) {
6135     VarDecl *VD = dyn_cast<VarDecl>(Member);
6136     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6137 
6138     // Only methods and static fields inherit the attributes.
6139     if (!VD && !MD)
6140       continue;
6141 
6142     if (MD) {
6143       // Don't process deleted methods.
6144       if (MD->isDeleted())
6145         continue;
6146 
6147       if (MD->isInlined()) {
6148         // MinGW does not import or export inline methods. But do it for
6149         // template instantiations.
6150         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6151             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6152             TSK != TSK_ExplicitInstantiationDeclaration &&
6153             TSK != TSK_ExplicitInstantiationDefinition)
6154           continue;
6155 
6156         // MSVC versions before 2015 don't export the move assignment operators
6157         // and move constructor, so don't attempt to import/export them if
6158         // we have a definition.
6159         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6160         if ((MD->isMoveAssignmentOperator() ||
6161              (Ctor && Ctor->isMoveConstructor())) &&
6162             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6163           continue;
6164 
6165         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6166         // operator is exported anyway.
6167         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6168             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6169           continue;
6170       }
6171     }
6172 
6173     // Don't apply dllimport attributes to static data members of class template
6174     // instantiations when the attribute is propagated from a derived class.
6175     if (VD && PropagatedImport)
6176       continue;
6177 
6178     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6179       continue;
6180 
6181     if (!getDLLAttr(Member)) {
6182       InheritableAttr *NewAttr = nullptr;
6183 
6184       // Do not export/import inline function when -fno-dllexport-inlines is
6185       // passed. But add attribute for later local static var check.
6186       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6187           TSK != TSK_ExplicitInstantiationDeclaration &&
6188           TSK != TSK_ExplicitInstantiationDefinition) {
6189         if (ClassExported) {
6190           NewAttr = ::new (getASTContext())
6191               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6192         } else {
6193           NewAttr = ::new (getASTContext())
6194               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6195         }
6196       } else {
6197         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6198       }
6199 
6200       NewAttr->setInherited(true);
6201       Member->addAttr(NewAttr);
6202 
6203       if (MD) {
6204         // Propagate DLLAttr to friend re-declarations of MD that have already
6205         // been constructed.
6206         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6207              FD = FD->getPreviousDecl()) {
6208           if (FD->getFriendObjectKind() == Decl::FOK_None)
6209             continue;
6210           assert(!getDLLAttr(FD) &&
6211                  "friend re-decl should not already have a DLLAttr");
6212           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6213           NewAttr->setInherited(true);
6214           FD->addAttr(NewAttr);
6215         }
6216       }
6217     }
6218   }
6219 
6220   if (ClassExported)
6221     DelayedDllExportClasses.push_back(Class);
6222 }
6223 
6224 /// Perform propagation of DLL attributes from a derived class to a
6225 /// templated base class for MS compatibility.
6226 void Sema::propagateDLLAttrToBaseClassTemplate(
6227     CXXRecordDecl *Class, Attr *ClassAttr,
6228     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6229   if (getDLLAttr(
6230           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6231     // If the base class template has a DLL attribute, don't try to change it.
6232     return;
6233   }
6234 
6235   auto TSK = BaseTemplateSpec->getSpecializationKind();
6236   if (!getDLLAttr(BaseTemplateSpec) &&
6237       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6238        TSK == TSK_ImplicitInstantiation)) {
6239     // The template hasn't been instantiated yet (or it has, but only as an
6240     // explicit instantiation declaration or implicit instantiation, which means
6241     // we haven't codegenned any members yet), so propagate the attribute.
6242     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6243     NewAttr->setInherited(true);
6244     BaseTemplateSpec->addAttr(NewAttr);
6245 
6246     // If this was an import, mark that we propagated it from a derived class to
6247     // a base class template specialization.
6248     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6249       ImportAttr->setPropagatedToBaseTemplate();
6250 
6251     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6252     // needs to be run again to work see the new attribute. Otherwise this will
6253     // get run whenever the template is instantiated.
6254     if (TSK != TSK_Undeclared)
6255       checkClassLevelDLLAttribute(BaseTemplateSpec);
6256 
6257     return;
6258   }
6259 
6260   if (getDLLAttr(BaseTemplateSpec)) {
6261     // The template has already been specialized or instantiated with an
6262     // attribute, explicitly or through propagation. We should not try to change
6263     // it.
6264     return;
6265   }
6266 
6267   // The template was previously instantiated or explicitly specialized without
6268   // a dll attribute, It's too late for us to add an attribute, so warn that
6269   // this is unsupported.
6270   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6271       << BaseTemplateSpec->isExplicitSpecialization();
6272   Diag(ClassAttr->getLocation(), diag::note_attribute);
6273   if (BaseTemplateSpec->isExplicitSpecialization()) {
6274     Diag(BaseTemplateSpec->getLocation(),
6275            diag::note_template_class_explicit_specialization_was_here)
6276         << BaseTemplateSpec;
6277   } else {
6278     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6279            diag::note_template_class_instantiation_was_here)
6280         << BaseTemplateSpec;
6281   }
6282 }
6283 
6284 /// Determine the kind of defaulting that would be done for a given function.
6285 ///
6286 /// If the function is both a default constructor and a copy / move constructor
6287 /// (due to having a default argument for the first parameter), this picks
6288 /// CXXDefaultConstructor.
6289 ///
6290 /// FIXME: Check that case is properly handled by all callers.
6291 Sema::DefaultedFunctionKind
6292 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6293   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6294     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6295       if (Ctor->isDefaultConstructor())
6296         return Sema::CXXDefaultConstructor;
6297 
6298       if (Ctor->isCopyConstructor())
6299         return Sema::CXXCopyConstructor;
6300 
6301       if (Ctor->isMoveConstructor())
6302         return Sema::CXXMoveConstructor;
6303     }
6304 
6305     if (MD->isCopyAssignmentOperator())
6306       return Sema::CXXCopyAssignment;
6307 
6308     if (MD->isMoveAssignmentOperator())
6309       return Sema::CXXMoveAssignment;
6310 
6311     if (isa<CXXDestructorDecl>(FD))
6312       return Sema::CXXDestructor;
6313   }
6314 
6315   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6316   case OO_EqualEqual:
6317     return DefaultedComparisonKind::Equal;
6318 
6319   case OO_ExclaimEqual:
6320     return DefaultedComparisonKind::NotEqual;
6321 
6322   case OO_Spaceship:
6323     // No point allowing this if <=> doesn't exist in the current language mode.
6324     if (!getLangOpts().CPlusPlus20)
6325       break;
6326     return DefaultedComparisonKind::ThreeWay;
6327 
6328   case OO_Less:
6329   case OO_LessEqual:
6330   case OO_Greater:
6331   case OO_GreaterEqual:
6332     // No point allowing this if <=> doesn't exist in the current language mode.
6333     if (!getLangOpts().CPlusPlus20)
6334       break;
6335     return DefaultedComparisonKind::Relational;
6336 
6337   default:
6338     break;
6339   }
6340 
6341   // Not defaultable.
6342   return DefaultedFunctionKind();
6343 }
6344 
6345 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6346                                     SourceLocation DefaultLoc) {
6347   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6348   if (DFK.isComparison())
6349     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6350 
6351   switch (DFK.asSpecialMember()) {
6352   case Sema::CXXDefaultConstructor:
6353     S.DefineImplicitDefaultConstructor(DefaultLoc,
6354                                        cast<CXXConstructorDecl>(FD));
6355     break;
6356   case Sema::CXXCopyConstructor:
6357     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6358     break;
6359   case Sema::CXXCopyAssignment:
6360     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6361     break;
6362   case Sema::CXXDestructor:
6363     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6364     break;
6365   case Sema::CXXMoveConstructor:
6366     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6367     break;
6368   case Sema::CXXMoveAssignment:
6369     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6370     break;
6371   case Sema::CXXInvalid:
6372     llvm_unreachable("Invalid special member.");
6373   }
6374 }
6375 
6376 /// Determine whether a type is permitted to be passed or returned in
6377 /// registers, per C++ [class.temporary]p3.
6378 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6379                                TargetInfo::CallingConvKind CCK) {
6380   if (D->isDependentType() || D->isInvalidDecl())
6381     return false;
6382 
6383   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6384   // The PS4 platform ABI follows the behavior of Clang 3.2.
6385   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6386     return !D->hasNonTrivialDestructorForCall() &&
6387            !D->hasNonTrivialCopyConstructorForCall();
6388 
6389   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6390     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6391     bool DtorIsTrivialForCall = false;
6392 
6393     // If a class has at least one non-deleted, trivial copy constructor, it
6394     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6395     //
6396     // Note: This permits classes with non-trivial copy or move ctors to be
6397     // passed in registers, so long as they *also* have a trivial copy ctor,
6398     // which is non-conforming.
6399     if (D->needsImplicitCopyConstructor()) {
6400       if (!D->defaultedCopyConstructorIsDeleted()) {
6401         if (D->hasTrivialCopyConstructor())
6402           CopyCtorIsTrivial = true;
6403         if (D->hasTrivialCopyConstructorForCall())
6404           CopyCtorIsTrivialForCall = true;
6405       }
6406     } else {
6407       for (const CXXConstructorDecl *CD : D->ctors()) {
6408         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6409           if (CD->isTrivial())
6410             CopyCtorIsTrivial = true;
6411           if (CD->isTrivialForCall())
6412             CopyCtorIsTrivialForCall = true;
6413         }
6414       }
6415     }
6416 
6417     if (D->needsImplicitDestructor()) {
6418       if (!D->defaultedDestructorIsDeleted() &&
6419           D->hasTrivialDestructorForCall())
6420         DtorIsTrivialForCall = true;
6421     } else if (const auto *DD = D->getDestructor()) {
6422       if (!DD->isDeleted() && DD->isTrivialForCall())
6423         DtorIsTrivialForCall = true;
6424     }
6425 
6426     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6427     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6428       return true;
6429 
6430     // If a class has a destructor, we'd really like to pass it indirectly
6431     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6432     // impossible for small types, which it will pass in a single register or
6433     // stack slot. Most objects with dtors are large-ish, so handle that early.
6434     // We can't call out all large objects as being indirect because there are
6435     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6436     // how we pass large POD types.
6437 
6438     // Note: This permits small classes with nontrivial destructors to be
6439     // passed in registers, which is non-conforming.
6440     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6441     uint64_t TypeSize = isAArch64 ? 128 : 64;
6442 
6443     if (CopyCtorIsTrivial &&
6444         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6445       return true;
6446     return false;
6447   }
6448 
6449   // Per C++ [class.temporary]p3, the relevant condition is:
6450   //   each copy constructor, move constructor, and destructor of X is
6451   //   either trivial or deleted, and X has at least one non-deleted copy
6452   //   or move constructor
6453   bool HasNonDeletedCopyOrMove = false;
6454 
6455   if (D->needsImplicitCopyConstructor() &&
6456       !D->defaultedCopyConstructorIsDeleted()) {
6457     if (!D->hasTrivialCopyConstructorForCall())
6458       return false;
6459     HasNonDeletedCopyOrMove = true;
6460   }
6461 
6462   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6463       !D->defaultedMoveConstructorIsDeleted()) {
6464     if (!D->hasTrivialMoveConstructorForCall())
6465       return false;
6466     HasNonDeletedCopyOrMove = true;
6467   }
6468 
6469   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6470       !D->hasTrivialDestructorForCall())
6471     return false;
6472 
6473   for (const CXXMethodDecl *MD : D->methods()) {
6474     if (MD->isDeleted())
6475       continue;
6476 
6477     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6478     if (CD && CD->isCopyOrMoveConstructor())
6479       HasNonDeletedCopyOrMove = true;
6480     else if (!isa<CXXDestructorDecl>(MD))
6481       continue;
6482 
6483     if (!MD->isTrivialForCall())
6484       return false;
6485   }
6486 
6487   return HasNonDeletedCopyOrMove;
6488 }
6489 
6490 /// Report an error regarding overriding, along with any relevant
6491 /// overridden methods.
6492 ///
6493 /// \param DiagID the primary error to report.
6494 /// \param MD the overriding method.
6495 static bool
6496 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6497                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6498   bool IssuedDiagnostic = false;
6499   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6500     if (Report(O)) {
6501       if (!IssuedDiagnostic) {
6502         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6503         IssuedDiagnostic = true;
6504       }
6505       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6506     }
6507   }
6508   return IssuedDiagnostic;
6509 }
6510 
6511 /// Perform semantic checks on a class definition that has been
6512 /// completing, introducing implicitly-declared members, checking for
6513 /// abstract types, etc.
6514 ///
6515 /// \param S The scope in which the class was parsed. Null if we didn't just
6516 ///        parse a class definition.
6517 /// \param Record The completed class.
6518 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6519   if (!Record)
6520     return;
6521 
6522   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6523     AbstractUsageInfo Info(*this, Record);
6524     CheckAbstractClassUsage(Info, Record);
6525   }
6526 
6527   // If this is not an aggregate type and has no user-declared constructor,
6528   // complain about any non-static data members of reference or const scalar
6529   // type, since they will never get initializers.
6530   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6531       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6532       !Record->isLambda()) {
6533     bool Complained = false;
6534     for (const auto *F : Record->fields()) {
6535       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6536         continue;
6537 
6538       if (F->getType()->isReferenceType() ||
6539           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6540         if (!Complained) {
6541           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6542             << Record->getTagKind() << Record;
6543           Complained = true;
6544         }
6545 
6546         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6547           << F->getType()->isReferenceType()
6548           << F->getDeclName();
6549       }
6550     }
6551   }
6552 
6553   if (Record->getIdentifier()) {
6554     // C++ [class.mem]p13:
6555     //   If T is the name of a class, then each of the following shall have a
6556     //   name different from T:
6557     //     - every member of every anonymous union that is a member of class T.
6558     //
6559     // C++ [class.mem]p14:
6560     //   In addition, if class T has a user-declared constructor (12.1), every
6561     //   non-static data member of class T shall have a name different from T.
6562     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6563     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6564          ++I) {
6565       NamedDecl *D = (*I)->getUnderlyingDecl();
6566       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6567            Record->hasUserDeclaredConstructor()) ||
6568           isa<IndirectFieldDecl>(D)) {
6569         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6570           << D->getDeclName();
6571         break;
6572       }
6573     }
6574   }
6575 
6576   // Warn if the class has virtual methods but non-virtual public destructor.
6577   if (Record->isPolymorphic() && !Record->isDependentType()) {
6578     CXXDestructorDecl *dtor = Record->getDestructor();
6579     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6580         !Record->hasAttr<FinalAttr>())
6581       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6582            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6583   }
6584 
6585   if (Record->isAbstract()) {
6586     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6587       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6588         << FA->isSpelledAsSealed();
6589       DiagnoseAbstractType(Record);
6590     }
6591   }
6592 
6593   // Warn if the class has a final destructor but is not itself marked final.
6594   if (!Record->hasAttr<FinalAttr>()) {
6595     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6596       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6597         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6598             << FA->isSpelledAsSealed()
6599             << FixItHint::CreateInsertion(
6600                    getLocForEndOfToken(Record->getLocation()),
6601                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6602         Diag(Record->getLocation(),
6603              diag::note_final_dtor_non_final_class_silence)
6604             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6605       }
6606     }
6607   }
6608 
6609   // See if trivial_abi has to be dropped.
6610   if (Record->hasAttr<TrivialABIAttr>())
6611     checkIllFormedTrivialABIStruct(*Record);
6612 
6613   // Set HasTrivialSpecialMemberForCall if the record has attribute
6614   // "trivial_abi".
6615   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6616 
6617   if (HasTrivialABI)
6618     Record->setHasTrivialSpecialMemberForCall();
6619 
6620   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6621   // We check these last because they can depend on the properties of the
6622   // primary comparison functions (==, <=>).
6623   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6624 
6625   // Perform checks that can't be done until we know all the properties of a
6626   // member function (whether it's defaulted, deleted, virtual, overriding,
6627   // ...).
6628   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6629     // A static function cannot override anything.
6630     if (MD->getStorageClass() == SC_Static) {
6631       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6632                           [](const CXXMethodDecl *) { return true; }))
6633         return;
6634     }
6635 
6636     // A deleted function cannot override a non-deleted function and vice
6637     // versa.
6638     if (ReportOverrides(*this,
6639                         MD->isDeleted() ? diag::err_deleted_override
6640                                         : diag::err_non_deleted_override,
6641                         MD, [&](const CXXMethodDecl *V) {
6642                           return MD->isDeleted() != V->isDeleted();
6643                         })) {
6644       if (MD->isDefaulted() && MD->isDeleted())
6645         // Explain why this defaulted function was deleted.
6646         DiagnoseDeletedDefaultedFunction(MD);
6647       return;
6648     }
6649 
6650     // A consteval function cannot override a non-consteval function and vice
6651     // versa.
6652     if (ReportOverrides(*this,
6653                         MD->isConsteval() ? diag::err_consteval_override
6654                                           : diag::err_non_consteval_override,
6655                         MD, [&](const CXXMethodDecl *V) {
6656                           return MD->isConsteval() != V->isConsteval();
6657                         })) {
6658       if (MD->isDefaulted() && MD->isDeleted())
6659         // Explain why this defaulted function was deleted.
6660         DiagnoseDeletedDefaultedFunction(MD);
6661       return;
6662     }
6663   };
6664 
6665   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6666     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6667       return false;
6668 
6669     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6670     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6671         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6672       DefaultedSecondaryComparisons.push_back(FD);
6673       return true;
6674     }
6675 
6676     CheckExplicitlyDefaultedFunction(S, FD);
6677     return false;
6678   };
6679 
6680   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6681     // Check whether the explicitly-defaulted members are valid.
6682     bool Incomplete = CheckForDefaultedFunction(M);
6683 
6684     // Skip the rest of the checks for a member of a dependent class.
6685     if (Record->isDependentType())
6686       return;
6687 
6688     // For an explicitly defaulted or deleted special member, we defer
6689     // determining triviality until the class is complete. That time is now!
6690     CXXSpecialMember CSM = getSpecialMember(M);
6691     if (!M->isImplicit() && !M->isUserProvided()) {
6692       if (CSM != CXXInvalid) {
6693         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6694         // Inform the class that we've finished declaring this member.
6695         Record->finishedDefaultedOrDeletedMember(M);
6696         M->setTrivialForCall(
6697             HasTrivialABI ||
6698             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6699         Record->setTrivialForCallFlags(M);
6700       }
6701     }
6702 
6703     // Set triviality for the purpose of calls if this is a user-provided
6704     // copy/move constructor or destructor.
6705     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6706          CSM == CXXDestructor) && M->isUserProvided()) {
6707       M->setTrivialForCall(HasTrivialABI);
6708       Record->setTrivialForCallFlags(M);
6709     }
6710 
6711     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6712         M->hasAttr<DLLExportAttr>()) {
6713       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6714           M->isTrivial() &&
6715           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6716            CSM == CXXDestructor))
6717         M->dropAttr<DLLExportAttr>();
6718 
6719       if (M->hasAttr<DLLExportAttr>()) {
6720         // Define after any fields with in-class initializers have been parsed.
6721         DelayedDllExportMemberFunctions.push_back(M);
6722       }
6723     }
6724 
6725     // Define defaulted constexpr virtual functions that override a base class
6726     // function right away.
6727     // FIXME: We can defer doing this until the vtable is marked as used.
6728     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6729       DefineDefaultedFunction(*this, M, M->getLocation());
6730 
6731     if (!Incomplete)
6732       CheckCompletedMemberFunction(M);
6733   };
6734 
6735   // Check the destructor before any other member function. We need to
6736   // determine whether it's trivial in order to determine whether the claas
6737   // type is a literal type, which is a prerequisite for determining whether
6738   // other special member functions are valid and whether they're implicitly
6739   // 'constexpr'.
6740   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6741     CompleteMemberFunction(Dtor);
6742 
6743   bool HasMethodWithOverrideControl = false,
6744        HasOverridingMethodWithoutOverrideControl = false;
6745   for (auto *D : Record->decls()) {
6746     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6747       // FIXME: We could do this check for dependent types with non-dependent
6748       // bases.
6749       if (!Record->isDependentType()) {
6750         // See if a method overloads virtual methods in a base
6751         // class without overriding any.
6752         if (!M->isStatic())
6753           DiagnoseHiddenVirtualMethods(M);
6754         if (M->hasAttr<OverrideAttr>())
6755           HasMethodWithOverrideControl = true;
6756         else if (M->size_overridden_methods() > 0)
6757           HasOverridingMethodWithoutOverrideControl = true;
6758       }
6759 
6760       if (!isa<CXXDestructorDecl>(M))
6761         CompleteMemberFunction(M);
6762     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6763       CheckForDefaultedFunction(
6764           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6765     }
6766   }
6767 
6768   if (HasOverridingMethodWithoutOverrideControl) {
6769     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6770     for (auto *M : Record->methods())
6771       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6772   }
6773 
6774   // Check the defaulted secondary comparisons after any other member functions.
6775   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6776     CheckExplicitlyDefaultedFunction(S, FD);
6777 
6778     // If this is a member function, we deferred checking it until now.
6779     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6780       CheckCompletedMemberFunction(MD);
6781   }
6782 
6783   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6784   // whether this class uses any C++ features that are implemented
6785   // completely differently in MSVC, and if so, emit a diagnostic.
6786   // That diagnostic defaults to an error, but we allow projects to
6787   // map it down to a warning (or ignore it).  It's a fairly common
6788   // practice among users of the ms_struct pragma to mass-annotate
6789   // headers, sweeping up a bunch of types that the project doesn't
6790   // really rely on MSVC-compatible layout for.  We must therefore
6791   // support "ms_struct except for C++ stuff" as a secondary ABI.
6792   // Don't emit this diagnostic if the feature was enabled as a
6793   // language option (as opposed to via a pragma or attribute), as
6794   // the option -mms-bitfields otherwise essentially makes it impossible
6795   // to build C++ code, unless this diagnostic is turned off.
6796   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6797       (Record->isPolymorphic() || Record->getNumBases())) {
6798     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6799   }
6800 
6801   checkClassLevelDLLAttribute(Record);
6802   checkClassLevelCodeSegAttribute(Record);
6803 
6804   bool ClangABICompat4 =
6805       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6806   TargetInfo::CallingConvKind CCK =
6807       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6808   bool CanPass = canPassInRegisters(*this, Record, CCK);
6809 
6810   // Do not change ArgPassingRestrictions if it has already been set to
6811   // APK_CanNeverPassInRegs.
6812   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6813     Record->setArgPassingRestrictions(CanPass
6814                                           ? RecordDecl::APK_CanPassInRegs
6815                                           : RecordDecl::APK_CannotPassInRegs);
6816 
6817   // If canPassInRegisters returns true despite the record having a non-trivial
6818   // destructor, the record is destructed in the callee. This happens only when
6819   // the record or one of its subobjects has a field annotated with trivial_abi
6820   // or a field qualified with ObjC __strong/__weak.
6821   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6822     Record->setParamDestroyedInCallee(true);
6823   else if (Record->hasNonTrivialDestructor())
6824     Record->setParamDestroyedInCallee(CanPass);
6825 
6826   if (getLangOpts().ForceEmitVTables) {
6827     // If we want to emit all the vtables, we need to mark it as used.  This
6828     // is especially required for cases like vtable assumption loads.
6829     MarkVTableUsed(Record->getInnerLocStart(), Record);
6830   }
6831 
6832   if (getLangOpts().CUDA) {
6833     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6834       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6835     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6836       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6837   }
6838 }
6839 
6840 /// Look up the special member function that would be called by a special
6841 /// member function for a subobject of class type.
6842 ///
6843 /// \param Class The class type of the subobject.
6844 /// \param CSM The kind of special member function.
6845 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6846 /// \param ConstRHS True if this is a copy operation with a const object
6847 ///        on its RHS, that is, if the argument to the outer special member
6848 ///        function is 'const' and this is not a field marked 'mutable'.
6849 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6850     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6851     unsigned FieldQuals, bool ConstRHS) {
6852   unsigned LHSQuals = 0;
6853   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6854     LHSQuals = FieldQuals;
6855 
6856   unsigned RHSQuals = FieldQuals;
6857   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6858     RHSQuals = 0;
6859   else if (ConstRHS)
6860     RHSQuals |= Qualifiers::Const;
6861 
6862   return S.LookupSpecialMember(Class, CSM,
6863                                RHSQuals & Qualifiers::Const,
6864                                RHSQuals & Qualifiers::Volatile,
6865                                false,
6866                                LHSQuals & Qualifiers::Const,
6867                                LHSQuals & Qualifiers::Volatile);
6868 }
6869 
6870 class Sema::InheritedConstructorInfo {
6871   Sema &S;
6872   SourceLocation UseLoc;
6873 
6874   /// A mapping from the base classes through which the constructor was
6875   /// inherited to the using shadow declaration in that base class (or a null
6876   /// pointer if the constructor was declared in that base class).
6877   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6878       InheritedFromBases;
6879 
6880 public:
6881   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6882                            ConstructorUsingShadowDecl *Shadow)
6883       : S(S), UseLoc(UseLoc) {
6884     bool DiagnosedMultipleConstructedBases = false;
6885     CXXRecordDecl *ConstructedBase = nullptr;
6886     UsingDecl *ConstructedBaseUsing = nullptr;
6887 
6888     // Find the set of such base class subobjects and check that there's a
6889     // unique constructed subobject.
6890     for (auto *D : Shadow->redecls()) {
6891       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6892       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6893       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6894 
6895       InheritedFromBases.insert(
6896           std::make_pair(DNominatedBase->getCanonicalDecl(),
6897                          DShadow->getNominatedBaseClassShadowDecl()));
6898       if (DShadow->constructsVirtualBase())
6899         InheritedFromBases.insert(
6900             std::make_pair(DConstructedBase->getCanonicalDecl(),
6901                            DShadow->getConstructedBaseClassShadowDecl()));
6902       else
6903         assert(DNominatedBase == DConstructedBase);
6904 
6905       // [class.inhctor.init]p2:
6906       //   If the constructor was inherited from multiple base class subobjects
6907       //   of type B, the program is ill-formed.
6908       if (!ConstructedBase) {
6909         ConstructedBase = DConstructedBase;
6910         ConstructedBaseUsing = D->getUsingDecl();
6911       } else if (ConstructedBase != DConstructedBase &&
6912                  !Shadow->isInvalidDecl()) {
6913         if (!DiagnosedMultipleConstructedBases) {
6914           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6915               << Shadow->getTargetDecl();
6916           S.Diag(ConstructedBaseUsing->getLocation(),
6917                diag::note_ambiguous_inherited_constructor_using)
6918               << ConstructedBase;
6919           DiagnosedMultipleConstructedBases = true;
6920         }
6921         S.Diag(D->getUsingDecl()->getLocation(),
6922                diag::note_ambiguous_inherited_constructor_using)
6923             << DConstructedBase;
6924       }
6925     }
6926 
6927     if (DiagnosedMultipleConstructedBases)
6928       Shadow->setInvalidDecl();
6929   }
6930 
6931   /// Find the constructor to use for inherited construction of a base class,
6932   /// and whether that base class constructor inherits the constructor from a
6933   /// virtual base class (in which case it won't actually invoke it).
6934   std::pair<CXXConstructorDecl *, bool>
6935   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6936     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6937     if (It == InheritedFromBases.end())
6938       return std::make_pair(nullptr, false);
6939 
6940     // This is an intermediary class.
6941     if (It->second)
6942       return std::make_pair(
6943           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6944           It->second->constructsVirtualBase());
6945 
6946     // This is the base class from which the constructor was inherited.
6947     return std::make_pair(Ctor, false);
6948   }
6949 };
6950 
6951 /// Is the special member function which would be selected to perform the
6952 /// specified operation on the specified class type a constexpr constructor?
6953 static bool
6954 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6955                          Sema::CXXSpecialMember CSM, unsigned Quals,
6956                          bool ConstRHS,
6957                          CXXConstructorDecl *InheritedCtor = nullptr,
6958                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6959   // If we're inheriting a constructor, see if we need to call it for this base
6960   // class.
6961   if (InheritedCtor) {
6962     assert(CSM == Sema::CXXDefaultConstructor);
6963     auto BaseCtor =
6964         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6965     if (BaseCtor)
6966       return BaseCtor->isConstexpr();
6967   }
6968 
6969   if (CSM == Sema::CXXDefaultConstructor)
6970     return ClassDecl->hasConstexprDefaultConstructor();
6971   if (CSM == Sema::CXXDestructor)
6972     return ClassDecl->hasConstexprDestructor();
6973 
6974   Sema::SpecialMemberOverloadResult SMOR =
6975       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6976   if (!SMOR.getMethod())
6977     // A constructor we wouldn't select can't be "involved in initializing"
6978     // anything.
6979     return true;
6980   return SMOR.getMethod()->isConstexpr();
6981 }
6982 
6983 /// Determine whether the specified special member function would be constexpr
6984 /// if it were implicitly defined.
6985 static bool defaultedSpecialMemberIsConstexpr(
6986     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6987     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6988     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6989   if (!S.getLangOpts().CPlusPlus11)
6990     return false;
6991 
6992   // C++11 [dcl.constexpr]p4:
6993   // In the definition of a constexpr constructor [...]
6994   bool Ctor = true;
6995   switch (CSM) {
6996   case Sema::CXXDefaultConstructor:
6997     if (Inherited)
6998       break;
6999     // Since default constructor lookup is essentially trivial (and cannot
7000     // involve, for instance, template instantiation), we compute whether a
7001     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7002     //
7003     // This is important for performance; we need to know whether the default
7004     // constructor is constexpr to determine whether the type is a literal type.
7005     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7006 
7007   case Sema::CXXCopyConstructor:
7008   case Sema::CXXMoveConstructor:
7009     // For copy or move constructors, we need to perform overload resolution.
7010     break;
7011 
7012   case Sema::CXXCopyAssignment:
7013   case Sema::CXXMoveAssignment:
7014     if (!S.getLangOpts().CPlusPlus14)
7015       return false;
7016     // In C++1y, we need to perform overload resolution.
7017     Ctor = false;
7018     break;
7019 
7020   case Sema::CXXDestructor:
7021     return ClassDecl->defaultedDestructorIsConstexpr();
7022 
7023   case Sema::CXXInvalid:
7024     return false;
7025   }
7026 
7027   //   -- if the class is a non-empty union, or for each non-empty anonymous
7028   //      union member of a non-union class, exactly one non-static data member
7029   //      shall be initialized; [DR1359]
7030   //
7031   // If we squint, this is guaranteed, since exactly one non-static data member
7032   // will be initialized (if the constructor isn't deleted), we just don't know
7033   // which one.
7034   if (Ctor && ClassDecl->isUnion())
7035     return CSM == Sema::CXXDefaultConstructor
7036                ? ClassDecl->hasInClassInitializer() ||
7037                      !ClassDecl->hasVariantMembers()
7038                : true;
7039 
7040   //   -- the class shall not have any virtual base classes;
7041   if (Ctor && ClassDecl->getNumVBases())
7042     return false;
7043 
7044   // C++1y [class.copy]p26:
7045   //   -- [the class] is a literal type, and
7046   if (!Ctor && !ClassDecl->isLiteral())
7047     return false;
7048 
7049   //   -- every constructor involved in initializing [...] base class
7050   //      sub-objects shall be a constexpr constructor;
7051   //   -- the assignment operator selected to copy/move each direct base
7052   //      class is a constexpr function, and
7053   for (const auto &B : ClassDecl->bases()) {
7054     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7055     if (!BaseType) continue;
7056 
7057     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7058     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7059                                   InheritedCtor, Inherited))
7060       return false;
7061   }
7062 
7063   //   -- every constructor involved in initializing non-static data members
7064   //      [...] shall be a constexpr constructor;
7065   //   -- every non-static data member and base class sub-object shall be
7066   //      initialized
7067   //   -- for each non-static data member of X that is of class type (or array
7068   //      thereof), the assignment operator selected to copy/move that member is
7069   //      a constexpr function
7070   for (const auto *F : ClassDecl->fields()) {
7071     if (F->isInvalidDecl())
7072       continue;
7073     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7074       continue;
7075     QualType BaseType = S.Context.getBaseElementType(F->getType());
7076     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7077       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7078       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7079                                     BaseType.getCVRQualifiers(),
7080                                     ConstArg && !F->isMutable()))
7081         return false;
7082     } else if (CSM == Sema::CXXDefaultConstructor) {
7083       return false;
7084     }
7085   }
7086 
7087   // All OK, it's constexpr!
7088   return true;
7089 }
7090 
7091 namespace {
7092 /// RAII object to register a defaulted function as having its exception
7093 /// specification computed.
7094 struct ComputingExceptionSpec {
7095   Sema &S;
7096 
7097   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7098       : S(S) {
7099     Sema::CodeSynthesisContext Ctx;
7100     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7101     Ctx.PointOfInstantiation = Loc;
7102     Ctx.Entity = FD;
7103     S.pushCodeSynthesisContext(Ctx);
7104   }
7105   ~ComputingExceptionSpec() {
7106     S.popCodeSynthesisContext();
7107   }
7108 };
7109 }
7110 
7111 static Sema::ImplicitExceptionSpecification
7112 ComputeDefaultedSpecialMemberExceptionSpec(
7113     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7114     Sema::InheritedConstructorInfo *ICI);
7115 
7116 static Sema::ImplicitExceptionSpecification
7117 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7118                                         FunctionDecl *FD,
7119                                         Sema::DefaultedComparisonKind DCK);
7120 
7121 static Sema::ImplicitExceptionSpecification
7122 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7123   auto DFK = S.getDefaultedFunctionKind(FD);
7124   if (DFK.isSpecialMember())
7125     return ComputeDefaultedSpecialMemberExceptionSpec(
7126         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7127   if (DFK.isComparison())
7128     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7129                                                    DFK.asComparison());
7130 
7131   auto *CD = cast<CXXConstructorDecl>(FD);
7132   assert(CD->getInheritedConstructor() &&
7133          "only defaulted functions and inherited constructors have implicit "
7134          "exception specs");
7135   Sema::InheritedConstructorInfo ICI(
7136       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7137   return ComputeDefaultedSpecialMemberExceptionSpec(
7138       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7139 }
7140 
7141 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7142                                                             CXXMethodDecl *MD) {
7143   FunctionProtoType::ExtProtoInfo EPI;
7144 
7145   // Build an exception specification pointing back at this member.
7146   EPI.ExceptionSpec.Type = EST_Unevaluated;
7147   EPI.ExceptionSpec.SourceDecl = MD;
7148 
7149   // Set the calling convention to the default for C++ instance methods.
7150   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7151       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7152                                             /*IsCXXMethod=*/true));
7153   return EPI;
7154 }
7155 
7156 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7157   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7158   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7159     return;
7160 
7161   // Evaluate the exception specification.
7162   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7163   auto ESI = IES.getExceptionSpec();
7164 
7165   // Update the type of the special member to use it.
7166   UpdateExceptionSpec(FD, ESI);
7167 }
7168 
7169 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7170   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7171 
7172   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7173   if (!DefKind) {
7174     assert(FD->getDeclContext()->isDependentContext());
7175     return;
7176   }
7177 
7178   if (DefKind.isSpecialMember()
7179           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7180                                                   DefKind.asSpecialMember())
7181           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7182     FD->setInvalidDecl();
7183 }
7184 
7185 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7186                                                  CXXSpecialMember CSM) {
7187   CXXRecordDecl *RD = MD->getParent();
7188 
7189   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7190          "not an explicitly-defaulted special member");
7191 
7192   // Defer all checking for special members of a dependent type.
7193   if (RD->isDependentType())
7194     return false;
7195 
7196   // Whether this was the first-declared instance of the constructor.
7197   // This affects whether we implicitly add an exception spec and constexpr.
7198   bool First = MD == MD->getCanonicalDecl();
7199 
7200   bool HadError = false;
7201 
7202   // C++11 [dcl.fct.def.default]p1:
7203   //   A function that is explicitly defaulted shall
7204   //     -- be a special member function [...] (checked elsewhere),
7205   //     -- have the same type (except for ref-qualifiers, and except that a
7206   //        copy operation can take a non-const reference) as an implicit
7207   //        declaration, and
7208   //     -- not have default arguments.
7209   // C++2a changes the second bullet to instead delete the function if it's
7210   // defaulted on its first declaration, unless it's "an assignment operator,
7211   // and its return type differs or its parameter type is not a reference".
7212   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7213   bool ShouldDeleteForTypeMismatch = false;
7214   unsigned ExpectedParams = 1;
7215   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7216     ExpectedParams = 0;
7217   if (MD->getNumParams() != ExpectedParams) {
7218     // This checks for default arguments: a copy or move constructor with a
7219     // default argument is classified as a default constructor, and assignment
7220     // operations and destructors can't have default arguments.
7221     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7222       << CSM << MD->getSourceRange();
7223     HadError = true;
7224   } else if (MD->isVariadic()) {
7225     if (DeleteOnTypeMismatch)
7226       ShouldDeleteForTypeMismatch = true;
7227     else {
7228       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7229         << CSM << MD->getSourceRange();
7230       HadError = true;
7231     }
7232   }
7233 
7234   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7235 
7236   bool CanHaveConstParam = false;
7237   if (CSM == CXXCopyConstructor)
7238     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7239   else if (CSM == CXXCopyAssignment)
7240     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7241 
7242   QualType ReturnType = Context.VoidTy;
7243   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7244     // Check for return type matching.
7245     ReturnType = Type->getReturnType();
7246 
7247     QualType DeclType = Context.getTypeDeclType(RD);
7248     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7249     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7250 
7251     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7252       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7253         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7254       HadError = true;
7255     }
7256 
7257     // A defaulted special member cannot have cv-qualifiers.
7258     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7259       if (DeleteOnTypeMismatch)
7260         ShouldDeleteForTypeMismatch = true;
7261       else {
7262         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7263           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7264         HadError = true;
7265       }
7266     }
7267   }
7268 
7269   // Check for parameter type matching.
7270   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7271   bool HasConstParam = false;
7272   if (ExpectedParams && ArgType->isReferenceType()) {
7273     // Argument must be reference to possibly-const T.
7274     QualType ReferentType = ArgType->getPointeeType();
7275     HasConstParam = ReferentType.isConstQualified();
7276 
7277     if (ReferentType.isVolatileQualified()) {
7278       if (DeleteOnTypeMismatch)
7279         ShouldDeleteForTypeMismatch = true;
7280       else {
7281         Diag(MD->getLocation(),
7282              diag::err_defaulted_special_member_volatile_param) << CSM;
7283         HadError = true;
7284       }
7285     }
7286 
7287     if (HasConstParam && !CanHaveConstParam) {
7288       if (DeleteOnTypeMismatch)
7289         ShouldDeleteForTypeMismatch = true;
7290       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7291         Diag(MD->getLocation(),
7292              diag::err_defaulted_special_member_copy_const_param)
7293           << (CSM == CXXCopyAssignment);
7294         // FIXME: Explain why this special member can't be const.
7295         HadError = true;
7296       } else {
7297         Diag(MD->getLocation(),
7298              diag::err_defaulted_special_member_move_const_param)
7299           << (CSM == CXXMoveAssignment);
7300         HadError = true;
7301       }
7302     }
7303   } else if (ExpectedParams) {
7304     // A copy assignment operator can take its argument by value, but a
7305     // defaulted one cannot.
7306     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7307     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7308     HadError = true;
7309   }
7310 
7311   // C++11 [dcl.fct.def.default]p2:
7312   //   An explicitly-defaulted function may be declared constexpr only if it
7313   //   would have been implicitly declared as constexpr,
7314   // Do not apply this rule to members of class templates, since core issue 1358
7315   // makes such functions always instantiate to constexpr functions. For
7316   // functions which cannot be constexpr (for non-constructors in C++11 and for
7317   // destructors in C++14 and C++17), this is checked elsewhere.
7318   //
7319   // FIXME: This should not apply if the member is deleted.
7320   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7321                                                      HasConstParam);
7322   if ((getLangOpts().CPlusPlus20 ||
7323        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7324                                   : isa<CXXConstructorDecl>(MD))) &&
7325       MD->isConstexpr() && !Constexpr &&
7326       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7327     Diag(MD->getBeginLoc(), MD->isConsteval()
7328                                 ? diag::err_incorrect_defaulted_consteval
7329                                 : diag::err_incorrect_defaulted_constexpr)
7330         << CSM;
7331     // FIXME: Explain why the special member can't be constexpr.
7332     HadError = true;
7333   }
7334 
7335   if (First) {
7336     // C++2a [dcl.fct.def.default]p3:
7337     //   If a function is explicitly defaulted on its first declaration, it is
7338     //   implicitly considered to be constexpr if the implicit declaration
7339     //   would be.
7340     MD->setConstexprKind(
7341         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7342                   : CSK_unspecified);
7343 
7344     if (!Type->hasExceptionSpec()) {
7345       // C++2a [except.spec]p3:
7346       //   If a declaration of a function does not have a noexcept-specifier
7347       //   [and] is defaulted on its first declaration, [...] the exception
7348       //   specification is as specified below
7349       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7350       EPI.ExceptionSpec.Type = EST_Unevaluated;
7351       EPI.ExceptionSpec.SourceDecl = MD;
7352       MD->setType(Context.getFunctionType(ReturnType,
7353                                           llvm::makeArrayRef(&ArgType,
7354                                                              ExpectedParams),
7355                                           EPI));
7356     }
7357   }
7358 
7359   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7360     if (First) {
7361       SetDeclDeleted(MD, MD->getLocation());
7362       if (!inTemplateInstantiation() && !HadError) {
7363         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7364         if (ShouldDeleteForTypeMismatch) {
7365           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7366         } else {
7367           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7368         }
7369       }
7370       if (ShouldDeleteForTypeMismatch && !HadError) {
7371         Diag(MD->getLocation(),
7372              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7373       }
7374     } else {
7375       // C++11 [dcl.fct.def.default]p4:
7376       //   [For a] user-provided explicitly-defaulted function [...] if such a
7377       //   function is implicitly defined as deleted, the program is ill-formed.
7378       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7379       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7380       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7381       HadError = true;
7382     }
7383   }
7384 
7385   return HadError;
7386 }
7387 
7388 namespace {
7389 /// Helper class for building and checking a defaulted comparison.
7390 ///
7391 /// Defaulted functions are built in two phases:
7392 ///
7393 ///  * First, the set of operations that the function will perform are
7394 ///    identified, and some of them are checked. If any of the checked
7395 ///    operations is invalid in certain ways, the comparison function is
7396 ///    defined as deleted and no body is built.
7397 ///  * Then, if the function is not defined as deleted, the body is built.
7398 ///
7399 /// This is accomplished by performing two visitation steps over the eventual
7400 /// body of the function.
7401 template<typename Derived, typename ResultList, typename Result,
7402          typename Subobject>
7403 class DefaultedComparisonVisitor {
7404 public:
7405   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7406 
7407   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7408                              DefaultedComparisonKind DCK)
7409       : S(S), RD(RD), FD(FD), DCK(DCK) {
7410     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7411       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7412       // UnresolvedSet to avoid this copy.
7413       Fns.assign(Info->getUnqualifiedLookups().begin(),
7414                  Info->getUnqualifiedLookups().end());
7415     }
7416   }
7417 
7418   ResultList visit() {
7419     // The type of an lvalue naming a parameter of this function.
7420     QualType ParamLvalType =
7421         FD->getParamDecl(0)->getType().getNonReferenceType();
7422 
7423     ResultList Results;
7424 
7425     switch (DCK) {
7426     case DefaultedComparisonKind::None:
7427       llvm_unreachable("not a defaulted comparison");
7428 
7429     case DefaultedComparisonKind::Equal:
7430     case DefaultedComparisonKind::ThreeWay:
7431       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7432       return Results;
7433 
7434     case DefaultedComparisonKind::NotEqual:
7435     case DefaultedComparisonKind::Relational:
7436       Results.add(getDerived().visitExpandedSubobject(
7437           ParamLvalType, getDerived().getCompleteObject()));
7438       return Results;
7439     }
7440     llvm_unreachable("");
7441   }
7442 
7443 protected:
7444   Derived &getDerived() { return static_cast<Derived&>(*this); }
7445 
7446   /// Visit the expanded list of subobjects of the given type, as specified in
7447   /// C++2a [class.compare.default].
7448   ///
7449   /// \return \c true if the ResultList object said we're done, \c false if not.
7450   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7451                        Qualifiers Quals) {
7452     // C++2a [class.compare.default]p4:
7453     //   The direct base class subobjects of C
7454     for (CXXBaseSpecifier &Base : Record->bases())
7455       if (Results.add(getDerived().visitSubobject(
7456               S.Context.getQualifiedType(Base.getType(), Quals),
7457               getDerived().getBase(&Base))))
7458         return true;
7459 
7460     //   followed by the non-static data members of C
7461     for (FieldDecl *Field : Record->fields()) {
7462       // Recursively expand anonymous structs.
7463       if (Field->isAnonymousStructOrUnion()) {
7464         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7465                             Quals))
7466           return true;
7467         continue;
7468       }
7469 
7470       // Figure out the type of an lvalue denoting this field.
7471       Qualifiers FieldQuals = Quals;
7472       if (Field->isMutable())
7473         FieldQuals.removeConst();
7474       QualType FieldType =
7475           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7476 
7477       if (Results.add(getDerived().visitSubobject(
7478               FieldType, getDerived().getField(Field))))
7479         return true;
7480     }
7481 
7482     //   form a list of subobjects.
7483     return false;
7484   }
7485 
7486   Result visitSubobject(QualType Type, Subobject Subobj) {
7487     //   In that list, any subobject of array type is recursively expanded
7488     const ArrayType *AT = S.Context.getAsArrayType(Type);
7489     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7490       return getDerived().visitSubobjectArray(CAT->getElementType(),
7491                                               CAT->getSize(), Subobj);
7492     return getDerived().visitExpandedSubobject(Type, Subobj);
7493   }
7494 
7495   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7496                              Subobject Subobj) {
7497     return getDerived().visitSubobject(Type, Subobj);
7498   }
7499 
7500 protected:
7501   Sema &S;
7502   CXXRecordDecl *RD;
7503   FunctionDecl *FD;
7504   DefaultedComparisonKind DCK;
7505   UnresolvedSet<16> Fns;
7506 };
7507 
7508 /// Information about a defaulted comparison, as determined by
7509 /// DefaultedComparisonAnalyzer.
7510 struct DefaultedComparisonInfo {
7511   bool Deleted = false;
7512   bool Constexpr = true;
7513   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7514 
7515   static DefaultedComparisonInfo deleted() {
7516     DefaultedComparisonInfo Deleted;
7517     Deleted.Deleted = true;
7518     return Deleted;
7519   }
7520 
7521   bool add(const DefaultedComparisonInfo &R) {
7522     Deleted |= R.Deleted;
7523     Constexpr &= R.Constexpr;
7524     Category = commonComparisonType(Category, R.Category);
7525     return Deleted;
7526   }
7527 };
7528 
7529 /// An element in the expanded list of subobjects of a defaulted comparison, as
7530 /// specified in C++2a [class.compare.default]p4.
7531 struct DefaultedComparisonSubobject {
7532   enum { CompleteObject, Member, Base } Kind;
7533   NamedDecl *Decl;
7534   SourceLocation Loc;
7535 };
7536 
7537 /// A visitor over the notional body of a defaulted comparison that determines
7538 /// whether that body would be deleted or constexpr.
7539 class DefaultedComparisonAnalyzer
7540     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7541                                         DefaultedComparisonInfo,
7542                                         DefaultedComparisonInfo,
7543                                         DefaultedComparisonSubobject> {
7544 public:
7545   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7546 
7547 private:
7548   DiagnosticKind Diagnose;
7549 
7550 public:
7551   using Base = DefaultedComparisonVisitor;
7552   using Result = DefaultedComparisonInfo;
7553   using Subobject = DefaultedComparisonSubobject;
7554 
7555   friend Base;
7556 
7557   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7558                               DefaultedComparisonKind DCK,
7559                               DiagnosticKind Diagnose = NoDiagnostics)
7560       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7561 
7562   Result visit() {
7563     if ((DCK == DefaultedComparisonKind::Equal ||
7564          DCK == DefaultedComparisonKind::ThreeWay) &&
7565         RD->hasVariantMembers()) {
7566       // C++2a [class.compare.default]p2 [P2002R0]:
7567       //   A defaulted comparison operator function for class C is defined as
7568       //   deleted if [...] C has variant members.
7569       if (Diagnose == ExplainDeleted) {
7570         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7571           << FD << RD->isUnion() << RD;
7572       }
7573       return Result::deleted();
7574     }
7575 
7576     return Base::visit();
7577   }
7578 
7579 private:
7580   Subobject getCompleteObject() {
7581     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7582   }
7583 
7584   Subobject getBase(CXXBaseSpecifier *Base) {
7585     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7586                      Base->getBaseTypeLoc()};
7587   }
7588 
7589   Subobject getField(FieldDecl *Field) {
7590     return Subobject{Subobject::Member, Field, Field->getLocation()};
7591   }
7592 
7593   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7594     // C++2a [class.compare.default]p2 [P2002R0]:
7595     //   A defaulted <=> or == operator function for class C is defined as
7596     //   deleted if any non-static data member of C is of reference type
7597     if (Type->isReferenceType()) {
7598       if (Diagnose == ExplainDeleted) {
7599         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7600             << FD << RD;
7601       }
7602       return Result::deleted();
7603     }
7604 
7605     // [...] Let xi be an lvalue denoting the ith element [...]
7606     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7607     Expr *Args[] = {&Xi, &Xi};
7608 
7609     // All operators start by trying to apply that same operator recursively.
7610     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7611     assert(OO != OO_None && "not an overloaded operator!");
7612     return visitBinaryOperator(OO, Args, Subobj);
7613   }
7614 
7615   Result
7616   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7617                       Subobject Subobj,
7618                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7619     // Note that there is no need to consider rewritten candidates here if
7620     // we've already found there is no viable 'operator<=>' candidate (and are
7621     // considering synthesizing a '<=>' from '==' and '<').
7622     OverloadCandidateSet CandidateSet(
7623         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7624         OverloadCandidateSet::OperatorRewriteInfo(
7625             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7626 
7627     /// C++2a [class.compare.default]p1 [P2002R0]:
7628     ///   [...] the defaulted function itself is never a candidate for overload
7629     ///   resolution [...]
7630     CandidateSet.exclude(FD);
7631 
7632     if (Args[0]->getType()->isOverloadableType())
7633       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7634     else {
7635       // FIXME: We determine whether this is a valid expression by checking to
7636       // see if there's a viable builtin operator candidate for it. That isn't
7637       // really what the rules ask us to do, but should give the right results.
7638       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7639     }
7640 
7641     Result R;
7642 
7643     OverloadCandidateSet::iterator Best;
7644     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7645     case OR_Success: {
7646       // C++2a [class.compare.secondary]p2 [P2002R0]:
7647       //   The operator function [...] is defined as deleted if [...] the
7648       //   candidate selected by overload resolution is not a rewritten
7649       //   candidate.
7650       if ((DCK == DefaultedComparisonKind::NotEqual ||
7651            DCK == DefaultedComparisonKind::Relational) &&
7652           !Best->RewriteKind) {
7653         if (Diagnose == ExplainDeleted) {
7654           S.Diag(Best->Function->getLocation(),
7655                  diag::note_defaulted_comparison_not_rewritten_callee)
7656               << FD;
7657         }
7658         return Result::deleted();
7659       }
7660 
7661       // Throughout C++2a [class.compare]: if overload resolution does not
7662       // result in a usable function, the candidate function is defined as
7663       // deleted. This requires that we selected an accessible function.
7664       //
7665       // Note that this only considers the access of the function when named
7666       // within the type of the subobject, and not the access path for any
7667       // derived-to-base conversion.
7668       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7669       if (ArgClass && Best->FoundDecl.getDecl() &&
7670           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7671         QualType ObjectType = Subobj.Kind == Subobject::Member
7672                                   ? Args[0]->getType()
7673                                   : S.Context.getRecordType(RD);
7674         if (!S.isMemberAccessibleForDeletion(
7675                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7676                 Diagnose == ExplainDeleted
7677                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7678                           << FD << Subobj.Kind << Subobj.Decl
7679                     : S.PDiag()))
7680           return Result::deleted();
7681       }
7682 
7683       // C++2a [class.compare.default]p3 [P2002R0]:
7684       //   A defaulted comparison function is constexpr-compatible if [...]
7685       //   no overlod resolution performed [...] results in a non-constexpr
7686       //   function.
7687       if (FunctionDecl *BestFD = Best->Function) {
7688         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7689         // If it's not constexpr, explain why not.
7690         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7691           if (Subobj.Kind != Subobject::CompleteObject)
7692             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7693               << Subobj.Kind << Subobj.Decl;
7694           S.Diag(BestFD->getLocation(),
7695                  diag::note_defaulted_comparison_not_constexpr_here);
7696           // Bail out after explaining; we don't want any more notes.
7697           return Result::deleted();
7698         }
7699         R.Constexpr &= BestFD->isConstexpr();
7700       }
7701 
7702       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7703         if (auto *BestFD = Best->Function) {
7704           // If any callee has an undeduced return type, deduce it now.
7705           // FIXME: It's not clear how a failure here should be handled. For
7706           // now, we produce an eager diagnostic, because that is forward
7707           // compatible with most (all?) other reasonable options.
7708           if (BestFD->getReturnType()->isUndeducedType() &&
7709               S.DeduceReturnType(BestFD, FD->getLocation(),
7710                                  /*Diagnose=*/false)) {
7711             // Don't produce a duplicate error when asked to explain why the
7712             // comparison is deleted: we diagnosed that when initially checking
7713             // the defaulted operator.
7714             if (Diagnose == NoDiagnostics) {
7715               S.Diag(
7716                   FD->getLocation(),
7717                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7718                   << Subobj.Kind << Subobj.Decl;
7719               S.Diag(
7720                   Subobj.Loc,
7721                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7722                   << Subobj.Kind << Subobj.Decl;
7723               S.Diag(BestFD->getLocation(),
7724                      diag::note_defaulted_comparison_cannot_deduce_callee)
7725                   << Subobj.Kind << Subobj.Decl;
7726             }
7727             return Result::deleted();
7728           }
7729           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7730               BestFD->getCallResultType())) {
7731             R.Category = Info->Kind;
7732           } else {
7733             if (Diagnose == ExplainDeleted) {
7734               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7735                   << Subobj.Kind << Subobj.Decl
7736                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7737               S.Diag(BestFD->getLocation(),
7738                      diag::note_defaulted_comparison_cannot_deduce_callee)
7739                   << Subobj.Kind << Subobj.Decl;
7740             }
7741             return Result::deleted();
7742           }
7743         } else {
7744           Optional<ComparisonCategoryType> Cat =
7745               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7746           assert(Cat && "no category for builtin comparison?");
7747           R.Category = *Cat;
7748         }
7749       }
7750 
7751       // Note that we might be rewriting to a different operator. That call is
7752       // not considered until we come to actually build the comparison function.
7753       break;
7754     }
7755 
7756     case OR_Ambiguous:
7757       if (Diagnose == ExplainDeleted) {
7758         unsigned Kind = 0;
7759         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7760           Kind = OO == OO_EqualEqual ? 1 : 2;
7761         CandidateSet.NoteCandidates(
7762             PartialDiagnosticAt(
7763                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7764                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7765             S, OCD_AmbiguousCandidates, Args);
7766       }
7767       R = Result::deleted();
7768       break;
7769 
7770     case OR_Deleted:
7771       if (Diagnose == ExplainDeleted) {
7772         if ((DCK == DefaultedComparisonKind::NotEqual ||
7773              DCK == DefaultedComparisonKind::Relational) &&
7774             !Best->RewriteKind) {
7775           S.Diag(Best->Function->getLocation(),
7776                  diag::note_defaulted_comparison_not_rewritten_callee)
7777               << FD;
7778         } else {
7779           S.Diag(Subobj.Loc,
7780                  diag::note_defaulted_comparison_calls_deleted)
7781               << FD << Subobj.Kind << Subobj.Decl;
7782           S.NoteDeletedFunction(Best->Function);
7783         }
7784       }
7785       R = Result::deleted();
7786       break;
7787 
7788     case OR_No_Viable_Function:
7789       // If there's no usable candidate, we're done unless we can rewrite a
7790       // '<=>' in terms of '==' and '<'.
7791       if (OO == OO_Spaceship &&
7792           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7793         // For any kind of comparison category return type, we need a usable
7794         // '==' and a usable '<'.
7795         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7796                                        &CandidateSet)))
7797           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7798         break;
7799       }
7800 
7801       if (Diagnose == ExplainDeleted) {
7802         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7803             << FD << Subobj.Kind << Subobj.Decl;
7804 
7805         // For a three-way comparison, list both the candidates for the
7806         // original operator and the candidates for the synthesized operator.
7807         if (SpaceshipCandidates) {
7808           SpaceshipCandidates->NoteCandidates(
7809               S, Args,
7810               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7811                                                       Args, FD->getLocation()));
7812           S.Diag(Subobj.Loc,
7813                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7814               << (OO == OO_EqualEqual ? 0 : 1);
7815         }
7816 
7817         CandidateSet.NoteCandidates(
7818             S, Args,
7819             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7820                                             FD->getLocation()));
7821       }
7822       R = Result::deleted();
7823       break;
7824     }
7825 
7826     return R;
7827   }
7828 };
7829 
7830 /// A list of statements.
7831 struct StmtListResult {
7832   bool IsInvalid = false;
7833   llvm::SmallVector<Stmt*, 16> Stmts;
7834 
7835   bool add(const StmtResult &S) {
7836     IsInvalid |= S.isInvalid();
7837     if (IsInvalid)
7838       return true;
7839     Stmts.push_back(S.get());
7840     return false;
7841   }
7842 };
7843 
7844 /// A visitor over the notional body of a defaulted comparison that synthesizes
7845 /// the actual body.
7846 class DefaultedComparisonSynthesizer
7847     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7848                                         StmtListResult, StmtResult,
7849                                         std::pair<ExprResult, ExprResult>> {
7850   SourceLocation Loc;
7851   unsigned ArrayDepth = 0;
7852 
7853 public:
7854   using Base = DefaultedComparisonVisitor;
7855   using ExprPair = std::pair<ExprResult, ExprResult>;
7856 
7857   friend Base;
7858 
7859   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7860                                  DefaultedComparisonKind DCK,
7861                                  SourceLocation BodyLoc)
7862       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7863 
7864   /// Build a suitable function body for this defaulted comparison operator.
7865   StmtResult build() {
7866     Sema::CompoundScopeRAII CompoundScope(S);
7867 
7868     StmtListResult Stmts = visit();
7869     if (Stmts.IsInvalid)
7870       return StmtError();
7871 
7872     ExprResult RetVal;
7873     switch (DCK) {
7874     case DefaultedComparisonKind::None:
7875       llvm_unreachable("not a defaulted comparison");
7876 
7877     case DefaultedComparisonKind::Equal: {
7878       // C++2a [class.eq]p3:
7879       //   [...] compar[e] the corresponding elements [...] until the first
7880       //   index i where xi == yi yields [...] false. If no such index exists,
7881       //   V is true. Otherwise, V is false.
7882       //
7883       // Join the comparisons with '&&'s and return the result. Use a right
7884       // fold (traversing the conditions right-to-left), because that
7885       // short-circuits more naturally.
7886       auto OldStmts = std::move(Stmts.Stmts);
7887       Stmts.Stmts.clear();
7888       ExprResult CmpSoFar;
7889       // Finish a particular comparison chain.
7890       auto FinishCmp = [&] {
7891         if (Expr *Prior = CmpSoFar.get()) {
7892           // Convert the last expression to 'return ...;'
7893           if (RetVal.isUnset() && Stmts.Stmts.empty())
7894             RetVal = CmpSoFar;
7895           // Convert any prior comparison to 'if (!(...)) return false;'
7896           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7897             return true;
7898           CmpSoFar = ExprResult();
7899         }
7900         return false;
7901       };
7902       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7903         Expr *E = dyn_cast<Expr>(EAsStmt);
7904         if (!E) {
7905           // Found an array comparison.
7906           if (FinishCmp() || Stmts.add(EAsStmt))
7907             return StmtError();
7908           continue;
7909         }
7910 
7911         if (CmpSoFar.isUnset()) {
7912           CmpSoFar = E;
7913           continue;
7914         }
7915         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7916         if (CmpSoFar.isInvalid())
7917           return StmtError();
7918       }
7919       if (FinishCmp())
7920         return StmtError();
7921       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7922       //   If no such index exists, V is true.
7923       if (RetVal.isUnset())
7924         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7925       break;
7926     }
7927 
7928     case DefaultedComparisonKind::ThreeWay: {
7929       // Per C++2a [class.spaceship]p3, as a fallback add:
7930       // return static_cast<R>(std::strong_ordering::equal);
7931       QualType StrongOrdering = S.CheckComparisonCategoryType(
7932           ComparisonCategoryType::StrongOrdering, Loc,
7933           Sema::ComparisonCategoryUsage::DefaultedOperator);
7934       if (StrongOrdering.isNull())
7935         return StmtError();
7936       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7937                              .getValueInfo(ComparisonCategoryResult::Equal)
7938                              ->VD;
7939       RetVal = getDecl(EqualVD);
7940       if (RetVal.isInvalid())
7941         return StmtError();
7942       RetVal = buildStaticCastToR(RetVal.get());
7943       break;
7944     }
7945 
7946     case DefaultedComparisonKind::NotEqual:
7947     case DefaultedComparisonKind::Relational:
7948       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7949       break;
7950     }
7951 
7952     // Build the final return statement.
7953     if (RetVal.isInvalid())
7954       return StmtError();
7955     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7956     if (ReturnStmt.isInvalid())
7957       return StmtError();
7958     Stmts.Stmts.push_back(ReturnStmt.get());
7959 
7960     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7961   }
7962 
7963 private:
7964   ExprResult getDecl(ValueDecl *VD) {
7965     return S.BuildDeclarationNameExpr(
7966         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7967   }
7968 
7969   ExprResult getParam(unsigned I) {
7970     ParmVarDecl *PD = FD->getParamDecl(I);
7971     return getDecl(PD);
7972   }
7973 
7974   ExprPair getCompleteObject() {
7975     unsigned Param = 0;
7976     ExprResult LHS;
7977     if (isa<CXXMethodDecl>(FD)) {
7978       // LHS is '*this'.
7979       LHS = S.ActOnCXXThis(Loc);
7980       if (!LHS.isInvalid())
7981         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7982     } else {
7983       LHS = getParam(Param++);
7984     }
7985     ExprResult RHS = getParam(Param++);
7986     assert(Param == FD->getNumParams());
7987     return {LHS, RHS};
7988   }
7989 
7990   ExprPair getBase(CXXBaseSpecifier *Base) {
7991     ExprPair Obj = getCompleteObject();
7992     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7993       return {ExprError(), ExprError()};
7994     CXXCastPath Path = {Base};
7995     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7996                                 CK_DerivedToBase, VK_LValue, &Path),
7997             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7998                                 CK_DerivedToBase, VK_LValue, &Path)};
7999   }
8000 
8001   ExprPair getField(FieldDecl *Field) {
8002     ExprPair Obj = getCompleteObject();
8003     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8004       return {ExprError(), ExprError()};
8005 
8006     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8007     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8008     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8009                                       CXXScopeSpec(), Field, Found, NameInfo),
8010             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8011                                       CXXScopeSpec(), Field, Found, NameInfo)};
8012   }
8013 
8014   // FIXME: When expanding a subobject, register a note in the code synthesis
8015   // stack to say which subobject we're comparing.
8016 
8017   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8018     if (Cond.isInvalid())
8019       return StmtError();
8020 
8021     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8022     if (NotCond.isInvalid())
8023       return StmtError();
8024 
8025     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8026     assert(!False.isInvalid() && "should never fail");
8027     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8028     if (ReturnFalse.isInvalid())
8029       return StmtError();
8030 
8031     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8032                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8033                                           Sema::ConditionKind::Boolean),
8034                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8035   }
8036 
8037   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8038                                  ExprPair Subobj) {
8039     QualType SizeType = S.Context.getSizeType();
8040     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8041 
8042     // Build 'size_t i$n = 0'.
8043     IdentifierInfo *IterationVarName = nullptr;
8044     {
8045       SmallString<8> Str;
8046       llvm::raw_svector_ostream OS(Str);
8047       OS << "i" << ArrayDepth;
8048       IterationVarName = &S.Context.Idents.get(OS.str());
8049     }
8050     VarDecl *IterationVar = VarDecl::Create(
8051         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8052         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8053     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8054     IterationVar->setInit(
8055         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8056     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8057 
8058     auto IterRef = [&] {
8059       ExprResult Ref = S.BuildDeclarationNameExpr(
8060           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8061           IterationVar);
8062       assert(!Ref.isInvalid() && "can't reference our own variable?");
8063       return Ref.get();
8064     };
8065 
8066     // Build 'i$n != Size'.
8067     ExprResult Cond = S.CreateBuiltinBinOp(
8068         Loc, BO_NE, IterRef(),
8069         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8070     assert(!Cond.isInvalid() && "should never fail");
8071 
8072     // Build '++i$n'.
8073     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8074     assert(!Inc.isInvalid() && "should never fail");
8075 
8076     // Build 'a[i$n]' and 'b[i$n]'.
8077     auto Index = [&](ExprResult E) {
8078       if (E.isInvalid())
8079         return ExprError();
8080       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8081     };
8082     Subobj.first = Index(Subobj.first);
8083     Subobj.second = Index(Subobj.second);
8084 
8085     // Compare the array elements.
8086     ++ArrayDepth;
8087     StmtResult Substmt = visitSubobject(Type, Subobj);
8088     --ArrayDepth;
8089 
8090     if (Substmt.isInvalid())
8091       return StmtError();
8092 
8093     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8094     // For outer levels or for an 'operator<=>' we already have a suitable
8095     // statement that returns as necessary.
8096     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8097       assert(DCK == DefaultedComparisonKind::Equal &&
8098              "should have non-expression statement");
8099       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8100       if (Substmt.isInvalid())
8101         return StmtError();
8102     }
8103 
8104     // Build 'for (...) ...'
8105     return S.ActOnForStmt(Loc, Loc, Init,
8106                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8107                                            Sema::ConditionKind::Boolean),
8108                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8109                           Substmt.get());
8110   }
8111 
8112   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8113     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8114       return StmtError();
8115 
8116     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8117     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8118     ExprResult Op;
8119     if (Type->isOverloadableType())
8120       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8121                                    Obj.second.get(), /*PerformADL=*/true,
8122                                    /*AllowRewrittenCandidates=*/true, FD);
8123     else
8124       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8125     if (Op.isInvalid())
8126       return StmtError();
8127 
8128     switch (DCK) {
8129     case DefaultedComparisonKind::None:
8130       llvm_unreachable("not a defaulted comparison");
8131 
8132     case DefaultedComparisonKind::Equal:
8133       // Per C++2a [class.eq]p2, each comparison is individually contextually
8134       // converted to bool.
8135       Op = S.PerformContextuallyConvertToBool(Op.get());
8136       if (Op.isInvalid())
8137         return StmtError();
8138       return Op.get();
8139 
8140     case DefaultedComparisonKind::ThreeWay: {
8141       // Per C++2a [class.spaceship]p3, form:
8142       //   if (R cmp = static_cast<R>(op); cmp != 0)
8143       //     return cmp;
8144       QualType R = FD->getReturnType();
8145       Op = buildStaticCastToR(Op.get());
8146       if (Op.isInvalid())
8147         return StmtError();
8148 
8149       // R cmp = ...;
8150       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8151       VarDecl *VD =
8152           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8153                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8154       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8155       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8156 
8157       // cmp != 0
8158       ExprResult VDRef = getDecl(VD);
8159       if (VDRef.isInvalid())
8160         return StmtError();
8161       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8162       Expr *Zero =
8163           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8164       ExprResult Comp;
8165       if (VDRef.get()->getType()->isOverloadableType())
8166         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8167                                        true, FD);
8168       else
8169         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8170       if (Comp.isInvalid())
8171         return StmtError();
8172       Sema::ConditionResult Cond = S.ActOnCondition(
8173           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8174       if (Cond.isInvalid())
8175         return StmtError();
8176 
8177       // return cmp;
8178       VDRef = getDecl(VD);
8179       if (VDRef.isInvalid())
8180         return StmtError();
8181       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8182       if (ReturnStmt.isInvalid())
8183         return StmtError();
8184 
8185       // if (...)
8186       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8187                            ReturnStmt.get(),
8188                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8189     }
8190 
8191     case DefaultedComparisonKind::NotEqual:
8192     case DefaultedComparisonKind::Relational:
8193       // C++2a [class.compare.secondary]p2:
8194       //   Otherwise, the operator function yields x @ y.
8195       return Op.get();
8196     }
8197     llvm_unreachable("");
8198   }
8199 
8200   /// Build "static_cast<R>(E)".
8201   ExprResult buildStaticCastToR(Expr *E) {
8202     QualType R = FD->getReturnType();
8203     assert(!R->isUndeducedType() && "type should have been deduced already");
8204 
8205     // Don't bother forming a no-op cast in the common case.
8206     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8207       return E;
8208     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8209                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8210                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8211   }
8212 };
8213 }
8214 
8215 /// Perform the unqualified lookups that might be needed to form a defaulted
8216 /// comparison function for the given operator.
8217 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8218                                                   UnresolvedSetImpl &Operators,
8219                                                   OverloadedOperatorKind Op) {
8220   auto Lookup = [&](OverloadedOperatorKind OO) {
8221     Self.LookupOverloadedOperatorName(OO, S, Operators);
8222   };
8223 
8224   // Every defaulted operator looks up itself.
8225   Lookup(Op);
8226   // ... and the rewritten form of itself, if any.
8227   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8228     Lookup(ExtraOp);
8229 
8230   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8231   // synthesize a three-way comparison from '<' and '=='. In a dependent
8232   // context, we also need to look up '==' in case we implicitly declare a
8233   // defaulted 'operator=='.
8234   if (Op == OO_Spaceship) {
8235     Lookup(OO_ExclaimEqual);
8236     Lookup(OO_Less);
8237     Lookup(OO_EqualEqual);
8238   }
8239 }
8240 
8241 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8242                                               DefaultedComparisonKind DCK) {
8243   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8244 
8245   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8246   assert(RD && "defaulted comparison is not defaulted in a class");
8247 
8248   // Perform any unqualified lookups we're going to need to default this
8249   // function.
8250   if (S) {
8251     UnresolvedSet<32> Operators;
8252     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8253                                           FD->getOverloadedOperator());
8254     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8255         Context, Operators.pairs()));
8256   }
8257 
8258   // C++2a [class.compare.default]p1:
8259   //   A defaulted comparison operator function for some class C shall be a
8260   //   non-template function declared in the member-specification of C that is
8261   //    -- a non-static const member of C having one parameter of type
8262   //       const C&, or
8263   //    -- a friend of C having two parameters of type const C& or two
8264   //       parameters of type C.
8265   QualType ExpectedParmType1 = Context.getRecordType(RD);
8266   QualType ExpectedParmType2 =
8267       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8268   if (isa<CXXMethodDecl>(FD))
8269     ExpectedParmType1 = ExpectedParmType2;
8270   for (const ParmVarDecl *Param : FD->parameters()) {
8271     if (!Param->getType()->isDependentType() &&
8272         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8273         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8274       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8275       // corresponding defaulted 'operator<=>' already.
8276       if (!FD->isImplicit()) {
8277         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8278             << (int)DCK << Param->getType() << ExpectedParmType1
8279             << !isa<CXXMethodDecl>(FD)
8280             << ExpectedParmType2 << Param->getSourceRange();
8281       }
8282       return true;
8283     }
8284   }
8285   if (FD->getNumParams() == 2 &&
8286       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8287                            FD->getParamDecl(1)->getType())) {
8288     if (!FD->isImplicit()) {
8289       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8290           << (int)DCK
8291           << FD->getParamDecl(0)->getType()
8292           << FD->getParamDecl(0)->getSourceRange()
8293           << FD->getParamDecl(1)->getType()
8294           << FD->getParamDecl(1)->getSourceRange();
8295     }
8296     return true;
8297   }
8298 
8299   // ... non-static const member ...
8300   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8301     assert(!MD->isStatic() && "comparison function cannot be a static member");
8302     if (!MD->isConst()) {
8303       SourceLocation InsertLoc;
8304       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8305         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8306       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8307       // corresponding defaulted 'operator<=>' already.
8308       if (!MD->isImplicit()) {
8309         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8310           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8311       }
8312 
8313       // Add the 'const' to the type to recover.
8314       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8315       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8316       EPI.TypeQuals.addConst();
8317       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8318                                           FPT->getParamTypes(), EPI));
8319     }
8320   } else {
8321     // A non-member function declared in a class must be a friend.
8322     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8323   }
8324 
8325   // C++2a [class.eq]p1, [class.rel]p1:
8326   //   A [defaulted comparison other than <=>] shall have a declared return
8327   //   type bool.
8328   if (DCK != DefaultedComparisonKind::ThreeWay &&
8329       !FD->getDeclaredReturnType()->isDependentType() &&
8330       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8331     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8332         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8333         << FD->getReturnTypeSourceRange();
8334     return true;
8335   }
8336   // C++2a [class.spaceship]p2 [P2002R0]:
8337   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8338   //   R shall not contain a placeholder type.
8339   if (DCK == DefaultedComparisonKind::ThreeWay &&
8340       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8341       !Context.hasSameType(FD->getDeclaredReturnType(),
8342                            Context.getAutoDeductType())) {
8343     Diag(FD->getLocation(),
8344          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8345         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8346         << FD->getReturnTypeSourceRange();
8347     return true;
8348   }
8349 
8350   // For a defaulted function in a dependent class, defer all remaining checks
8351   // until instantiation.
8352   if (RD->isDependentType())
8353     return false;
8354 
8355   // Determine whether the function should be defined as deleted.
8356   DefaultedComparisonInfo Info =
8357       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8358 
8359   bool First = FD == FD->getCanonicalDecl();
8360 
8361   // If we want to delete the function, then do so; there's nothing else to
8362   // check in that case.
8363   if (Info.Deleted) {
8364     if (!First) {
8365       // C++11 [dcl.fct.def.default]p4:
8366       //   [For a] user-provided explicitly-defaulted function [...] if such a
8367       //   function is implicitly defined as deleted, the program is ill-formed.
8368       //
8369       // This is really just a consequence of the general rule that you can
8370       // only delete a function on its first declaration.
8371       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8372           << FD->isImplicit() << (int)DCK;
8373       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8374                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8375           .visit();
8376       return true;
8377     }
8378 
8379     SetDeclDeleted(FD, FD->getLocation());
8380     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8381       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8382           << (int)DCK;
8383       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8384                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8385           .visit();
8386     }
8387     return false;
8388   }
8389 
8390   // C++2a [class.spaceship]p2:
8391   //   The return type is deduced as the common comparison type of R0, R1, ...
8392   if (DCK == DefaultedComparisonKind::ThreeWay &&
8393       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8394     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8395     if (RetLoc.isInvalid())
8396       RetLoc = FD->getBeginLoc();
8397     // FIXME: Should we really care whether we have the complete type and the
8398     // 'enumerator' constants here? A forward declaration seems sufficient.
8399     QualType Cat = CheckComparisonCategoryType(
8400         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8401     if (Cat.isNull())
8402       return true;
8403     Context.adjustDeducedFunctionResultType(
8404         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8405   }
8406 
8407   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8408   //   An explicitly-defaulted function that is not defined as deleted may be
8409   //   declared constexpr or consteval only if it is constexpr-compatible.
8410   // C++2a [class.compare.default]p3 [P2002R0]:
8411   //   A defaulted comparison function is constexpr-compatible if it satisfies
8412   //   the requirements for a constexpr function [...]
8413   // The only relevant requirements are that the parameter and return types are
8414   // literal types. The remaining conditions are checked by the analyzer.
8415   if (FD->isConstexpr()) {
8416     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8417         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8418         !Info.Constexpr) {
8419       Diag(FD->getBeginLoc(),
8420            diag::err_incorrect_defaulted_comparison_constexpr)
8421           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8422       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8423                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8424           .visit();
8425     }
8426   }
8427 
8428   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8429   //   If a constexpr-compatible function is explicitly defaulted on its first
8430   //   declaration, it is implicitly considered to be constexpr.
8431   // FIXME: Only applying this to the first declaration seems problematic, as
8432   // simple reorderings can affect the meaning of the program.
8433   if (First && !FD->isConstexpr() && Info.Constexpr)
8434     FD->setConstexprKind(CSK_constexpr);
8435 
8436   // C++2a [except.spec]p3:
8437   //   If a declaration of a function does not have a noexcept-specifier
8438   //   [and] is defaulted on its first declaration, [...] the exception
8439   //   specification is as specified below
8440   if (FD->getExceptionSpecType() == EST_None) {
8441     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8442     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8443     EPI.ExceptionSpec.Type = EST_Unevaluated;
8444     EPI.ExceptionSpec.SourceDecl = FD;
8445     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8446                                         FPT->getParamTypes(), EPI));
8447   }
8448 
8449   return false;
8450 }
8451 
8452 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8453                                              FunctionDecl *Spaceship) {
8454   Sema::CodeSynthesisContext Ctx;
8455   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8456   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8457   Ctx.Entity = Spaceship;
8458   pushCodeSynthesisContext(Ctx);
8459 
8460   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8461     EqualEqual->setImplicit();
8462 
8463   popCodeSynthesisContext();
8464 }
8465 
8466 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8467                                      DefaultedComparisonKind DCK) {
8468   assert(FD->isDefaulted() && !FD->isDeleted() &&
8469          !FD->doesThisDeclarationHaveABody());
8470   if (FD->willHaveBody() || FD->isInvalidDecl())
8471     return;
8472 
8473   SynthesizedFunctionScope Scope(*this, FD);
8474 
8475   // Add a context note for diagnostics produced after this point.
8476   Scope.addContextNote(UseLoc);
8477 
8478   {
8479     // Build and set up the function body.
8480     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8481     SourceLocation BodyLoc =
8482         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8483     StmtResult Body =
8484         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8485     if (Body.isInvalid()) {
8486       FD->setInvalidDecl();
8487       return;
8488     }
8489     FD->setBody(Body.get());
8490     FD->markUsed(Context);
8491   }
8492 
8493   // The exception specification is needed because we are defining the
8494   // function. Note that this will reuse the body we just built.
8495   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8496 
8497   if (ASTMutationListener *L = getASTMutationListener())
8498     L->CompletedImplicitDefinition(FD);
8499 }
8500 
8501 static Sema::ImplicitExceptionSpecification
8502 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8503                                         FunctionDecl *FD,
8504                                         Sema::DefaultedComparisonKind DCK) {
8505   ComputingExceptionSpec CES(S, FD, Loc);
8506   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8507 
8508   if (FD->isInvalidDecl())
8509     return ExceptSpec;
8510 
8511   // The common case is that we just defined the comparison function. In that
8512   // case, just look at whether the body can throw.
8513   if (FD->hasBody()) {
8514     ExceptSpec.CalledStmt(FD->getBody());
8515   } else {
8516     // Otherwise, build a body so we can check it. This should ideally only
8517     // happen when we're not actually marking the function referenced. (This is
8518     // only really important for efficiency: we don't want to build and throw
8519     // away bodies for comparison functions more than we strictly need to.)
8520 
8521     // Pretend to synthesize the function body in an unevaluated context.
8522     // Note that we can't actually just go ahead and define the function here:
8523     // we are not permitted to mark its callees as referenced.
8524     Sema::SynthesizedFunctionScope Scope(S, FD);
8525     EnterExpressionEvaluationContext Context(
8526         S, Sema::ExpressionEvaluationContext::Unevaluated);
8527 
8528     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8529     SourceLocation BodyLoc =
8530         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8531     StmtResult Body =
8532         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8533     if (!Body.isInvalid())
8534       ExceptSpec.CalledStmt(Body.get());
8535 
8536     // FIXME: Can we hold onto this body and just transform it to potentially
8537     // evaluated when we're asked to define the function rather than rebuilding
8538     // it? Either that, or we should only build the bits of the body that we
8539     // need (the expressions, not the statements).
8540   }
8541 
8542   return ExceptSpec;
8543 }
8544 
8545 void Sema::CheckDelayedMemberExceptionSpecs() {
8546   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8547   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8548 
8549   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8550   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8551 
8552   // Perform any deferred checking of exception specifications for virtual
8553   // destructors.
8554   for (auto &Check : Overriding)
8555     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8556 
8557   // Perform any deferred checking of exception specifications for befriended
8558   // special members.
8559   for (auto &Check : Equivalent)
8560     CheckEquivalentExceptionSpec(Check.second, Check.first);
8561 }
8562 
8563 namespace {
8564 /// CRTP base class for visiting operations performed by a special member
8565 /// function (or inherited constructor).
8566 template<typename Derived>
8567 struct SpecialMemberVisitor {
8568   Sema &S;
8569   CXXMethodDecl *MD;
8570   Sema::CXXSpecialMember CSM;
8571   Sema::InheritedConstructorInfo *ICI;
8572 
8573   // Properties of the special member, computed for convenience.
8574   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8575 
8576   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8577                        Sema::InheritedConstructorInfo *ICI)
8578       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8579     switch (CSM) {
8580     case Sema::CXXDefaultConstructor:
8581     case Sema::CXXCopyConstructor:
8582     case Sema::CXXMoveConstructor:
8583       IsConstructor = true;
8584       break;
8585     case Sema::CXXCopyAssignment:
8586     case Sema::CXXMoveAssignment:
8587       IsAssignment = true;
8588       break;
8589     case Sema::CXXDestructor:
8590       break;
8591     case Sema::CXXInvalid:
8592       llvm_unreachable("invalid special member kind");
8593     }
8594 
8595     if (MD->getNumParams()) {
8596       if (const ReferenceType *RT =
8597               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8598         ConstArg = RT->getPointeeType().isConstQualified();
8599     }
8600   }
8601 
8602   Derived &getDerived() { return static_cast<Derived&>(*this); }
8603 
8604   /// Is this a "move" special member?
8605   bool isMove() const {
8606     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8607   }
8608 
8609   /// Look up the corresponding special member in the given class.
8610   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8611                                              unsigned Quals, bool IsMutable) {
8612     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8613                                        ConstArg && !IsMutable);
8614   }
8615 
8616   /// Look up the constructor for the specified base class to see if it's
8617   /// overridden due to this being an inherited constructor.
8618   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8619     if (!ICI)
8620       return {};
8621     assert(CSM == Sema::CXXDefaultConstructor);
8622     auto *BaseCtor =
8623       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8624     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8625       return MD;
8626     return {};
8627   }
8628 
8629   /// A base or member subobject.
8630   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8631 
8632   /// Get the location to use for a subobject in diagnostics.
8633   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8634     // FIXME: For an indirect virtual base, the direct base leading to
8635     // the indirect virtual base would be a more useful choice.
8636     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8637       return B->getBaseTypeLoc();
8638     else
8639       return Subobj.get<FieldDecl*>()->getLocation();
8640   }
8641 
8642   enum BasesToVisit {
8643     /// Visit all non-virtual (direct) bases.
8644     VisitNonVirtualBases,
8645     /// Visit all direct bases, virtual or not.
8646     VisitDirectBases,
8647     /// Visit all non-virtual bases, and all virtual bases if the class
8648     /// is not abstract.
8649     VisitPotentiallyConstructedBases,
8650     /// Visit all direct or virtual bases.
8651     VisitAllBases
8652   };
8653 
8654   // Visit the bases and members of the class.
8655   bool visit(BasesToVisit Bases) {
8656     CXXRecordDecl *RD = MD->getParent();
8657 
8658     if (Bases == VisitPotentiallyConstructedBases)
8659       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8660 
8661     for (auto &B : RD->bases())
8662       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8663           getDerived().visitBase(&B))
8664         return true;
8665 
8666     if (Bases == VisitAllBases)
8667       for (auto &B : RD->vbases())
8668         if (getDerived().visitBase(&B))
8669           return true;
8670 
8671     for (auto *F : RD->fields())
8672       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8673           getDerived().visitField(F))
8674         return true;
8675 
8676     return false;
8677   }
8678 };
8679 }
8680 
8681 namespace {
8682 struct SpecialMemberDeletionInfo
8683     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8684   bool Diagnose;
8685 
8686   SourceLocation Loc;
8687 
8688   bool AllFieldsAreConst;
8689 
8690   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8691                             Sema::CXXSpecialMember CSM,
8692                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8693       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8694         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8695 
8696   bool inUnion() const { return MD->getParent()->isUnion(); }
8697 
8698   Sema::CXXSpecialMember getEffectiveCSM() {
8699     return ICI ? Sema::CXXInvalid : CSM;
8700   }
8701 
8702   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8703 
8704   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8705   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8706 
8707   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8708   bool shouldDeleteForField(FieldDecl *FD);
8709   bool shouldDeleteForAllConstMembers();
8710 
8711   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8712                                      unsigned Quals);
8713   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8714                                     Sema::SpecialMemberOverloadResult SMOR,
8715                                     bool IsDtorCallInCtor);
8716 
8717   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8718 };
8719 }
8720 
8721 /// Is the given special member inaccessible when used on the given
8722 /// sub-object.
8723 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8724                                              CXXMethodDecl *target) {
8725   /// If we're operating on a base class, the object type is the
8726   /// type of this special member.
8727   QualType objectTy;
8728   AccessSpecifier access = target->getAccess();
8729   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8730     objectTy = S.Context.getTypeDeclType(MD->getParent());
8731     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8732 
8733   // If we're operating on a field, the object type is the type of the field.
8734   } else {
8735     objectTy = S.Context.getTypeDeclType(target->getParent());
8736   }
8737 
8738   return S.isMemberAccessibleForDeletion(
8739       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8740 }
8741 
8742 /// Check whether we should delete a special member due to the implicit
8743 /// definition containing a call to a special member of a subobject.
8744 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8745     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8746     bool IsDtorCallInCtor) {
8747   CXXMethodDecl *Decl = SMOR.getMethod();
8748   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8749 
8750   int DiagKind = -1;
8751 
8752   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8753     DiagKind = !Decl ? 0 : 1;
8754   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8755     DiagKind = 2;
8756   else if (!isAccessible(Subobj, Decl))
8757     DiagKind = 3;
8758   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8759            !Decl->isTrivial()) {
8760     // A member of a union must have a trivial corresponding special member.
8761     // As a weird special case, a destructor call from a union's constructor
8762     // must be accessible and non-deleted, but need not be trivial. Such a
8763     // destructor is never actually called, but is semantically checked as
8764     // if it were.
8765     DiagKind = 4;
8766   }
8767 
8768   if (DiagKind == -1)
8769     return false;
8770 
8771   if (Diagnose) {
8772     if (Field) {
8773       S.Diag(Field->getLocation(),
8774              diag::note_deleted_special_member_class_subobject)
8775         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8776         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8777     } else {
8778       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8779       S.Diag(Base->getBeginLoc(),
8780              diag::note_deleted_special_member_class_subobject)
8781           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8782           << Base->getType() << DiagKind << IsDtorCallInCtor
8783           << /*IsObjCPtr*/false;
8784     }
8785 
8786     if (DiagKind == 1)
8787       S.NoteDeletedFunction(Decl);
8788     // FIXME: Explain inaccessibility if DiagKind == 3.
8789   }
8790 
8791   return true;
8792 }
8793 
8794 /// Check whether we should delete a special member function due to having a
8795 /// direct or virtual base class or non-static data member of class type M.
8796 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8797     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8798   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8799   bool IsMutable = Field && Field->isMutable();
8800 
8801   // C++11 [class.ctor]p5:
8802   // -- any direct or virtual base class, or non-static data member with no
8803   //    brace-or-equal-initializer, has class type M (or array thereof) and
8804   //    either M has no default constructor or overload resolution as applied
8805   //    to M's default constructor results in an ambiguity or in a function
8806   //    that is deleted or inaccessible
8807   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8808   // -- a direct or virtual base class B that cannot be copied/moved because
8809   //    overload resolution, as applied to B's corresponding special member,
8810   //    results in an ambiguity or a function that is deleted or inaccessible
8811   //    from the defaulted special member
8812   // C++11 [class.dtor]p5:
8813   // -- any direct or virtual base class [...] has a type with a destructor
8814   //    that is deleted or inaccessible
8815   if (!(CSM == Sema::CXXDefaultConstructor &&
8816         Field && Field->hasInClassInitializer()) &&
8817       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8818                                    false))
8819     return true;
8820 
8821   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8822   // -- any direct or virtual base class or non-static data member has a
8823   //    type with a destructor that is deleted or inaccessible
8824   if (IsConstructor) {
8825     Sema::SpecialMemberOverloadResult SMOR =
8826         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8827                               false, false, false, false, false);
8828     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8829       return true;
8830   }
8831 
8832   return false;
8833 }
8834 
8835 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8836     FieldDecl *FD, QualType FieldType) {
8837   // The defaulted special functions are defined as deleted if this is a variant
8838   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8839   // type under ARC.
8840   if (!FieldType.hasNonTrivialObjCLifetime())
8841     return false;
8842 
8843   // Don't make the defaulted default constructor defined as deleted if the
8844   // member has an in-class initializer.
8845   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8846     return false;
8847 
8848   if (Diagnose) {
8849     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8850     S.Diag(FD->getLocation(),
8851            diag::note_deleted_special_member_class_subobject)
8852         << getEffectiveCSM() << ParentClass << /*IsField*/true
8853         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8854   }
8855 
8856   return true;
8857 }
8858 
8859 /// Check whether we should delete a special member function due to the class
8860 /// having a particular direct or virtual base class.
8861 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8862   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8863   // If program is correct, BaseClass cannot be null, but if it is, the error
8864   // must be reported elsewhere.
8865   if (!BaseClass)
8866     return false;
8867   // If we have an inheriting constructor, check whether we're calling an
8868   // inherited constructor instead of a default constructor.
8869   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8870   if (auto *BaseCtor = SMOR.getMethod()) {
8871     // Note that we do not check access along this path; other than that,
8872     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8873     // FIXME: Check that the base has a usable destructor! Sink this into
8874     // shouldDeleteForClassSubobject.
8875     if (BaseCtor->isDeleted() && Diagnose) {
8876       S.Diag(Base->getBeginLoc(),
8877              diag::note_deleted_special_member_class_subobject)
8878           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8879           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8880           << /*IsObjCPtr*/false;
8881       S.NoteDeletedFunction(BaseCtor);
8882     }
8883     return BaseCtor->isDeleted();
8884   }
8885   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8886 }
8887 
8888 /// Check whether we should delete a special member function due to the class
8889 /// having a particular non-static data member.
8890 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8891   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8892   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8893 
8894   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8895     return true;
8896 
8897   if (CSM == Sema::CXXDefaultConstructor) {
8898     // For a default constructor, all references must be initialized in-class
8899     // and, if a union, it must have a non-const member.
8900     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8901       if (Diagnose)
8902         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8903           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8904       return true;
8905     }
8906     // C++11 [class.ctor]p5: any non-variant non-static data member of
8907     // const-qualified type (or array thereof) with no
8908     // brace-or-equal-initializer does not have a user-provided default
8909     // constructor.
8910     if (!inUnion() && FieldType.isConstQualified() &&
8911         !FD->hasInClassInitializer() &&
8912         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8913       if (Diagnose)
8914         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8915           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8916       return true;
8917     }
8918 
8919     if (inUnion() && !FieldType.isConstQualified())
8920       AllFieldsAreConst = false;
8921   } else if (CSM == Sema::CXXCopyConstructor) {
8922     // For a copy constructor, data members must not be of rvalue reference
8923     // type.
8924     if (FieldType->isRValueReferenceType()) {
8925       if (Diagnose)
8926         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8927           << MD->getParent() << FD << FieldType;
8928       return true;
8929     }
8930   } else if (IsAssignment) {
8931     // For an assignment operator, data members must not be of reference type.
8932     if (FieldType->isReferenceType()) {
8933       if (Diagnose)
8934         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8935           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8936       return true;
8937     }
8938     if (!FieldRecord && FieldType.isConstQualified()) {
8939       // C++11 [class.copy]p23:
8940       // -- a non-static data member of const non-class type (or array thereof)
8941       if (Diagnose)
8942         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8943           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8944       return true;
8945     }
8946   }
8947 
8948   if (FieldRecord) {
8949     // Some additional restrictions exist on the variant members.
8950     if (!inUnion() && FieldRecord->isUnion() &&
8951         FieldRecord->isAnonymousStructOrUnion()) {
8952       bool AllVariantFieldsAreConst = true;
8953 
8954       // FIXME: Handle anonymous unions declared within anonymous unions.
8955       for (auto *UI : FieldRecord->fields()) {
8956         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8957 
8958         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8959           return true;
8960 
8961         if (!UnionFieldType.isConstQualified())
8962           AllVariantFieldsAreConst = false;
8963 
8964         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8965         if (UnionFieldRecord &&
8966             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8967                                           UnionFieldType.getCVRQualifiers()))
8968           return true;
8969       }
8970 
8971       // At least one member in each anonymous union must be non-const
8972       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8973           !FieldRecord->field_empty()) {
8974         if (Diagnose)
8975           S.Diag(FieldRecord->getLocation(),
8976                  diag::note_deleted_default_ctor_all_const)
8977             << !!ICI << MD->getParent() << /*anonymous union*/1;
8978         return true;
8979       }
8980 
8981       // Don't check the implicit member of the anonymous union type.
8982       // This is technically non-conformant, but sanity demands it.
8983       return false;
8984     }
8985 
8986     if (shouldDeleteForClassSubobject(FieldRecord, FD,
8987                                       FieldType.getCVRQualifiers()))
8988       return true;
8989   }
8990 
8991   return false;
8992 }
8993 
8994 /// C++11 [class.ctor] p5:
8995 ///   A defaulted default constructor for a class X is defined as deleted if
8996 /// X is a union and all of its variant members are of const-qualified type.
8997 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8998   // This is a silly definition, because it gives an empty union a deleted
8999   // default constructor. Don't do that.
9000   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9001     bool AnyFields = false;
9002     for (auto *F : MD->getParent()->fields())
9003       if ((AnyFields = !F->isUnnamedBitfield()))
9004         break;
9005     if (!AnyFields)
9006       return false;
9007     if (Diagnose)
9008       S.Diag(MD->getParent()->getLocation(),
9009              diag::note_deleted_default_ctor_all_const)
9010         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9011     return true;
9012   }
9013   return false;
9014 }
9015 
9016 /// Determine whether a defaulted special member function should be defined as
9017 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9018 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9019 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9020                                      InheritedConstructorInfo *ICI,
9021                                      bool Diagnose) {
9022   if (MD->isInvalidDecl())
9023     return false;
9024   CXXRecordDecl *RD = MD->getParent();
9025   assert(!RD->isDependentType() && "do deletion after instantiation");
9026   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9027     return false;
9028 
9029   // C++11 [expr.lambda.prim]p19:
9030   //   The closure type associated with a lambda-expression has a
9031   //   deleted (8.4.3) default constructor and a deleted copy
9032   //   assignment operator.
9033   // C++2a adds back these operators if the lambda has no lambda-capture.
9034   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9035       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9036     if (Diagnose)
9037       Diag(RD->getLocation(), diag::note_lambda_decl);
9038     return true;
9039   }
9040 
9041   // For an anonymous struct or union, the copy and assignment special members
9042   // will never be used, so skip the check. For an anonymous union declared at
9043   // namespace scope, the constructor and destructor are used.
9044   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9045       RD->isAnonymousStructOrUnion())
9046     return false;
9047 
9048   // C++11 [class.copy]p7, p18:
9049   //   If the class definition declares a move constructor or move assignment
9050   //   operator, an implicitly declared copy constructor or copy assignment
9051   //   operator is defined as deleted.
9052   if (MD->isImplicit() &&
9053       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9054     CXXMethodDecl *UserDeclaredMove = nullptr;
9055 
9056     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9057     // deletion of the corresponding copy operation, not both copy operations.
9058     // MSVC 2015 has adopted the standards conforming behavior.
9059     bool DeletesOnlyMatchingCopy =
9060         getLangOpts().MSVCCompat &&
9061         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9062 
9063     if (RD->hasUserDeclaredMoveConstructor() &&
9064         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9065       if (!Diagnose) return true;
9066 
9067       // Find any user-declared move constructor.
9068       for (auto *I : RD->ctors()) {
9069         if (I->isMoveConstructor()) {
9070           UserDeclaredMove = I;
9071           break;
9072         }
9073       }
9074       assert(UserDeclaredMove);
9075     } else if (RD->hasUserDeclaredMoveAssignment() &&
9076                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9077       if (!Diagnose) return true;
9078 
9079       // Find any user-declared move assignment operator.
9080       for (auto *I : RD->methods()) {
9081         if (I->isMoveAssignmentOperator()) {
9082           UserDeclaredMove = I;
9083           break;
9084         }
9085       }
9086       assert(UserDeclaredMove);
9087     }
9088 
9089     if (UserDeclaredMove) {
9090       Diag(UserDeclaredMove->getLocation(),
9091            diag::note_deleted_copy_user_declared_move)
9092         << (CSM == CXXCopyAssignment) << RD
9093         << UserDeclaredMove->isMoveAssignmentOperator();
9094       return true;
9095     }
9096   }
9097 
9098   // Do access control from the special member function
9099   ContextRAII MethodContext(*this, MD);
9100 
9101   // C++11 [class.dtor]p5:
9102   // -- for a virtual destructor, lookup of the non-array deallocation function
9103   //    results in an ambiguity or in a function that is deleted or inaccessible
9104   if (CSM == CXXDestructor && MD->isVirtual()) {
9105     FunctionDecl *OperatorDelete = nullptr;
9106     DeclarationName Name =
9107       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9108     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9109                                  OperatorDelete, /*Diagnose*/false)) {
9110       if (Diagnose)
9111         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9112       return true;
9113     }
9114   }
9115 
9116   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9117 
9118   // Per DR1611, do not consider virtual bases of constructors of abstract
9119   // classes, since we are not going to construct them.
9120   // Per DR1658, do not consider virtual bases of destructors of abstract
9121   // classes either.
9122   // Per DR2180, for assignment operators we only assign (and thus only
9123   // consider) direct bases.
9124   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9125                                  : SMI.VisitPotentiallyConstructedBases))
9126     return true;
9127 
9128   if (SMI.shouldDeleteForAllConstMembers())
9129     return true;
9130 
9131   if (getLangOpts().CUDA) {
9132     // We should delete the special member in CUDA mode if target inference
9133     // failed.
9134     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9135     // is treated as certain special member, which may not reflect what special
9136     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9137     // expects CSM to match MD, therefore recalculate CSM.
9138     assert(ICI || CSM == getSpecialMember(MD));
9139     auto RealCSM = CSM;
9140     if (ICI)
9141       RealCSM = getSpecialMember(MD);
9142 
9143     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9144                                                    SMI.ConstArg, Diagnose);
9145   }
9146 
9147   return false;
9148 }
9149 
9150 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9151   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9152   assert(DFK && "not a defaultable function");
9153   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9154 
9155   if (DFK.isSpecialMember()) {
9156     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9157                               nullptr, /*Diagnose=*/true);
9158   } else {
9159     DefaultedComparisonAnalyzer(
9160         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9161         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9162         .visit();
9163   }
9164 }
9165 
9166 /// Perform lookup for a special member of the specified kind, and determine
9167 /// whether it is trivial. If the triviality can be determined without the
9168 /// lookup, skip it. This is intended for use when determining whether a
9169 /// special member of a containing object is trivial, and thus does not ever
9170 /// perform overload resolution for default constructors.
9171 ///
9172 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9173 /// member that was most likely to be intended to be trivial, if any.
9174 ///
9175 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9176 /// determine whether the special member is trivial.
9177 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9178                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9179                                      bool ConstRHS,
9180                                      Sema::TrivialABIHandling TAH,
9181                                      CXXMethodDecl **Selected) {
9182   if (Selected)
9183     *Selected = nullptr;
9184 
9185   switch (CSM) {
9186   case Sema::CXXInvalid:
9187     llvm_unreachable("not a special member");
9188 
9189   case Sema::CXXDefaultConstructor:
9190     // C++11 [class.ctor]p5:
9191     //   A default constructor is trivial if:
9192     //    - all the [direct subobjects] have trivial default constructors
9193     //
9194     // Note, no overload resolution is performed in this case.
9195     if (RD->hasTrivialDefaultConstructor())
9196       return true;
9197 
9198     if (Selected) {
9199       // If there's a default constructor which could have been trivial, dig it
9200       // out. Otherwise, if there's any user-provided default constructor, point
9201       // to that as an example of why there's not a trivial one.
9202       CXXConstructorDecl *DefCtor = nullptr;
9203       if (RD->needsImplicitDefaultConstructor())
9204         S.DeclareImplicitDefaultConstructor(RD);
9205       for (auto *CI : RD->ctors()) {
9206         if (!CI->isDefaultConstructor())
9207           continue;
9208         DefCtor = CI;
9209         if (!DefCtor->isUserProvided())
9210           break;
9211       }
9212 
9213       *Selected = DefCtor;
9214     }
9215 
9216     return false;
9217 
9218   case Sema::CXXDestructor:
9219     // C++11 [class.dtor]p5:
9220     //   A destructor is trivial if:
9221     //    - all the direct [subobjects] have trivial destructors
9222     if (RD->hasTrivialDestructor() ||
9223         (TAH == Sema::TAH_ConsiderTrivialABI &&
9224          RD->hasTrivialDestructorForCall()))
9225       return true;
9226 
9227     if (Selected) {
9228       if (RD->needsImplicitDestructor())
9229         S.DeclareImplicitDestructor(RD);
9230       *Selected = RD->getDestructor();
9231     }
9232 
9233     return false;
9234 
9235   case Sema::CXXCopyConstructor:
9236     // C++11 [class.copy]p12:
9237     //   A copy constructor is trivial if:
9238     //    - the constructor selected to copy each direct [subobject] is trivial
9239     if (RD->hasTrivialCopyConstructor() ||
9240         (TAH == Sema::TAH_ConsiderTrivialABI &&
9241          RD->hasTrivialCopyConstructorForCall())) {
9242       if (Quals == Qualifiers::Const)
9243         // We must either select the trivial copy constructor or reach an
9244         // ambiguity; no need to actually perform overload resolution.
9245         return true;
9246     } else if (!Selected) {
9247       return false;
9248     }
9249     // In C++98, we are not supposed to perform overload resolution here, but we
9250     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9251     // cases like B as having a non-trivial copy constructor:
9252     //   struct A { template<typename T> A(T&); };
9253     //   struct B { mutable A a; };
9254     goto NeedOverloadResolution;
9255 
9256   case Sema::CXXCopyAssignment:
9257     // C++11 [class.copy]p25:
9258     //   A copy assignment operator is trivial if:
9259     //    - the assignment operator selected to copy each direct [subobject] is
9260     //      trivial
9261     if (RD->hasTrivialCopyAssignment()) {
9262       if (Quals == Qualifiers::Const)
9263         return true;
9264     } else if (!Selected) {
9265       return false;
9266     }
9267     // In C++98, we are not supposed to perform overload resolution here, but we
9268     // treat that as a language defect.
9269     goto NeedOverloadResolution;
9270 
9271   case Sema::CXXMoveConstructor:
9272   case Sema::CXXMoveAssignment:
9273   NeedOverloadResolution:
9274     Sema::SpecialMemberOverloadResult SMOR =
9275         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9276 
9277     // The standard doesn't describe how to behave if the lookup is ambiguous.
9278     // We treat it as not making the member non-trivial, just like the standard
9279     // mandates for the default constructor. This should rarely matter, because
9280     // the member will also be deleted.
9281     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9282       return true;
9283 
9284     if (!SMOR.getMethod()) {
9285       assert(SMOR.getKind() ==
9286              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9287       return false;
9288     }
9289 
9290     // We deliberately don't check if we found a deleted special member. We're
9291     // not supposed to!
9292     if (Selected)
9293       *Selected = SMOR.getMethod();
9294 
9295     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9296         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9297       return SMOR.getMethod()->isTrivialForCall();
9298     return SMOR.getMethod()->isTrivial();
9299   }
9300 
9301   llvm_unreachable("unknown special method kind");
9302 }
9303 
9304 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9305   for (auto *CI : RD->ctors())
9306     if (!CI->isImplicit())
9307       return CI;
9308 
9309   // Look for constructor templates.
9310   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9311   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9312     if (CXXConstructorDecl *CD =
9313           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9314       return CD;
9315   }
9316 
9317   return nullptr;
9318 }
9319 
9320 /// The kind of subobject we are checking for triviality. The values of this
9321 /// enumeration are used in diagnostics.
9322 enum TrivialSubobjectKind {
9323   /// The subobject is a base class.
9324   TSK_BaseClass,
9325   /// The subobject is a non-static data member.
9326   TSK_Field,
9327   /// The object is actually the complete object.
9328   TSK_CompleteObject
9329 };
9330 
9331 /// Check whether the special member selected for a given type would be trivial.
9332 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9333                                       QualType SubType, bool ConstRHS,
9334                                       Sema::CXXSpecialMember CSM,
9335                                       TrivialSubobjectKind Kind,
9336                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9337   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9338   if (!SubRD)
9339     return true;
9340 
9341   CXXMethodDecl *Selected;
9342   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9343                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9344     return true;
9345 
9346   if (Diagnose) {
9347     if (ConstRHS)
9348       SubType.addConst();
9349 
9350     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9351       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9352         << Kind << SubType.getUnqualifiedType();
9353       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9354         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9355     } else if (!Selected)
9356       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9357         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9358     else if (Selected->isUserProvided()) {
9359       if (Kind == TSK_CompleteObject)
9360         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9361           << Kind << SubType.getUnqualifiedType() << CSM;
9362       else {
9363         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9364           << Kind << SubType.getUnqualifiedType() << CSM;
9365         S.Diag(Selected->getLocation(), diag::note_declared_at);
9366       }
9367     } else {
9368       if (Kind != TSK_CompleteObject)
9369         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9370           << Kind << SubType.getUnqualifiedType() << CSM;
9371 
9372       // Explain why the defaulted or deleted special member isn't trivial.
9373       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9374                                Diagnose);
9375     }
9376   }
9377 
9378   return false;
9379 }
9380 
9381 /// Check whether the members of a class type allow a special member to be
9382 /// trivial.
9383 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9384                                      Sema::CXXSpecialMember CSM,
9385                                      bool ConstArg,
9386                                      Sema::TrivialABIHandling TAH,
9387                                      bool Diagnose) {
9388   for (const auto *FI : RD->fields()) {
9389     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9390       continue;
9391 
9392     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9393 
9394     // Pretend anonymous struct or union members are members of this class.
9395     if (FI->isAnonymousStructOrUnion()) {
9396       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9397                                     CSM, ConstArg, TAH, Diagnose))
9398         return false;
9399       continue;
9400     }
9401 
9402     // C++11 [class.ctor]p5:
9403     //   A default constructor is trivial if [...]
9404     //    -- no non-static data member of its class has a
9405     //       brace-or-equal-initializer
9406     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9407       if (Diagnose)
9408         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9409             << FI;
9410       return false;
9411     }
9412 
9413     // Objective C ARC 4.3.5:
9414     //   [...] nontrivally ownership-qualified types are [...] not trivially
9415     //   default constructible, copy constructible, move constructible, copy
9416     //   assignable, move assignable, or destructible [...]
9417     if (FieldType.hasNonTrivialObjCLifetime()) {
9418       if (Diagnose)
9419         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9420           << RD << FieldType.getObjCLifetime();
9421       return false;
9422     }
9423 
9424     bool ConstRHS = ConstArg && !FI->isMutable();
9425     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9426                                    CSM, TSK_Field, TAH, Diagnose))
9427       return false;
9428   }
9429 
9430   return true;
9431 }
9432 
9433 /// Diagnose why the specified class does not have a trivial special member of
9434 /// the given kind.
9435 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9436   QualType Ty = Context.getRecordType(RD);
9437 
9438   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9439   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9440                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9441                             /*Diagnose*/true);
9442 }
9443 
9444 /// Determine whether a defaulted or deleted special member function is trivial,
9445 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9446 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9447 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9448                                   TrivialABIHandling TAH, bool Diagnose) {
9449   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9450 
9451   CXXRecordDecl *RD = MD->getParent();
9452 
9453   bool ConstArg = false;
9454 
9455   // C++11 [class.copy]p12, p25: [DR1593]
9456   //   A [special member] is trivial if [...] its parameter-type-list is
9457   //   equivalent to the parameter-type-list of an implicit declaration [...]
9458   switch (CSM) {
9459   case CXXDefaultConstructor:
9460   case CXXDestructor:
9461     // Trivial default constructors and destructors cannot have parameters.
9462     break;
9463 
9464   case CXXCopyConstructor:
9465   case CXXCopyAssignment: {
9466     // Trivial copy operations always have const, non-volatile parameter types.
9467     ConstArg = true;
9468     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9469     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9470     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9471       if (Diagnose)
9472         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9473           << Param0->getSourceRange() << Param0->getType()
9474           << Context.getLValueReferenceType(
9475                Context.getRecordType(RD).withConst());
9476       return false;
9477     }
9478     break;
9479   }
9480 
9481   case CXXMoveConstructor:
9482   case CXXMoveAssignment: {
9483     // Trivial move operations always have non-cv-qualified parameters.
9484     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9485     const RValueReferenceType *RT =
9486       Param0->getType()->getAs<RValueReferenceType>();
9487     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9488       if (Diagnose)
9489         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9490           << Param0->getSourceRange() << Param0->getType()
9491           << Context.getRValueReferenceType(Context.getRecordType(RD));
9492       return false;
9493     }
9494     break;
9495   }
9496 
9497   case CXXInvalid:
9498     llvm_unreachable("not a special member");
9499   }
9500 
9501   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9502     if (Diagnose)
9503       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9504            diag::note_nontrivial_default_arg)
9505         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9506     return false;
9507   }
9508   if (MD->isVariadic()) {
9509     if (Diagnose)
9510       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9511     return false;
9512   }
9513 
9514   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9515   //   A copy/move [constructor or assignment operator] is trivial if
9516   //    -- the [member] selected to copy/move each direct base class subobject
9517   //       is trivial
9518   //
9519   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9520   //   A [default constructor or destructor] is trivial if
9521   //    -- all the direct base classes have trivial [default constructors or
9522   //       destructors]
9523   for (const auto &BI : RD->bases())
9524     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9525                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9526       return false;
9527 
9528   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9529   //   A copy/move [constructor or assignment operator] for a class X is
9530   //   trivial if
9531   //    -- for each non-static data member of X that is of class type (or array
9532   //       thereof), the constructor selected to copy/move that member is
9533   //       trivial
9534   //
9535   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9536   //   A [default constructor or destructor] is trivial if
9537   //    -- for all of the non-static data members of its class that are of class
9538   //       type (or array thereof), each such class has a trivial [default
9539   //       constructor or destructor]
9540   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9541     return false;
9542 
9543   // C++11 [class.dtor]p5:
9544   //   A destructor is trivial if [...]
9545   //    -- the destructor is not virtual
9546   if (CSM == CXXDestructor && MD->isVirtual()) {
9547     if (Diagnose)
9548       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9549     return false;
9550   }
9551 
9552   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9553   //   A [special member] for class X is trivial if [...]
9554   //    -- class X has no virtual functions and no virtual base classes
9555   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9556     if (!Diagnose)
9557       return false;
9558 
9559     if (RD->getNumVBases()) {
9560       // Check for virtual bases. We already know that the corresponding
9561       // member in all bases is trivial, so vbases must all be direct.
9562       CXXBaseSpecifier &BS = *RD->vbases_begin();
9563       assert(BS.isVirtual());
9564       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9565       return false;
9566     }
9567 
9568     // Must have a virtual method.
9569     for (const auto *MI : RD->methods()) {
9570       if (MI->isVirtual()) {
9571         SourceLocation MLoc = MI->getBeginLoc();
9572         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9573         return false;
9574       }
9575     }
9576 
9577     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9578   }
9579 
9580   // Looks like it's trivial!
9581   return true;
9582 }
9583 
9584 namespace {
9585 struct FindHiddenVirtualMethod {
9586   Sema *S;
9587   CXXMethodDecl *Method;
9588   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9589   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9590 
9591 private:
9592   /// Check whether any most overridden method from MD in Methods
9593   static bool CheckMostOverridenMethods(
9594       const CXXMethodDecl *MD,
9595       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9596     if (MD->size_overridden_methods() == 0)
9597       return Methods.count(MD->getCanonicalDecl());
9598     for (const CXXMethodDecl *O : MD->overridden_methods())
9599       if (CheckMostOverridenMethods(O, Methods))
9600         return true;
9601     return false;
9602   }
9603 
9604 public:
9605   /// Member lookup function that determines whether a given C++
9606   /// method overloads virtual methods in a base class without overriding any,
9607   /// to be used with CXXRecordDecl::lookupInBases().
9608   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9609     RecordDecl *BaseRecord =
9610         Specifier->getType()->castAs<RecordType>()->getDecl();
9611 
9612     DeclarationName Name = Method->getDeclName();
9613     assert(Name.getNameKind() == DeclarationName::Identifier);
9614 
9615     bool foundSameNameMethod = false;
9616     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9617     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9618          Path.Decls = Path.Decls.slice(1)) {
9619       NamedDecl *D = Path.Decls.front();
9620       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9621         MD = MD->getCanonicalDecl();
9622         foundSameNameMethod = true;
9623         // Interested only in hidden virtual methods.
9624         if (!MD->isVirtual())
9625           continue;
9626         // If the method we are checking overrides a method from its base
9627         // don't warn about the other overloaded methods. Clang deviates from
9628         // GCC by only diagnosing overloads of inherited virtual functions that
9629         // do not override any other virtual functions in the base. GCC's
9630         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9631         // function from a base class. These cases may be better served by a
9632         // warning (not specific to virtual functions) on call sites when the
9633         // call would select a different function from the base class, were it
9634         // visible.
9635         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9636         if (!S->IsOverload(Method, MD, false))
9637           return true;
9638         // Collect the overload only if its hidden.
9639         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9640           overloadedMethods.push_back(MD);
9641       }
9642     }
9643 
9644     if (foundSameNameMethod)
9645       OverloadedMethods.append(overloadedMethods.begin(),
9646                                overloadedMethods.end());
9647     return foundSameNameMethod;
9648   }
9649 };
9650 } // end anonymous namespace
9651 
9652 /// Add the most overriden methods from MD to Methods
9653 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9654                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9655   if (MD->size_overridden_methods() == 0)
9656     Methods.insert(MD->getCanonicalDecl());
9657   else
9658     for (const CXXMethodDecl *O : MD->overridden_methods())
9659       AddMostOverridenMethods(O, Methods);
9660 }
9661 
9662 /// Check if a method overloads virtual methods in a base class without
9663 /// overriding any.
9664 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9665                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9666   if (!MD->getDeclName().isIdentifier())
9667     return;
9668 
9669   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9670                      /*bool RecordPaths=*/false,
9671                      /*bool DetectVirtual=*/false);
9672   FindHiddenVirtualMethod FHVM;
9673   FHVM.Method = MD;
9674   FHVM.S = this;
9675 
9676   // Keep the base methods that were overridden or introduced in the subclass
9677   // by 'using' in a set. A base method not in this set is hidden.
9678   CXXRecordDecl *DC = MD->getParent();
9679   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9680   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9681     NamedDecl *ND = *I;
9682     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9683       ND = shad->getTargetDecl();
9684     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9685       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9686   }
9687 
9688   if (DC->lookupInBases(FHVM, Paths))
9689     OverloadedMethods = FHVM.OverloadedMethods;
9690 }
9691 
9692 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9693                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9694   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9695     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9696     PartialDiagnostic PD = PDiag(
9697          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9698     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9699     Diag(overloadedMD->getLocation(), PD);
9700   }
9701 }
9702 
9703 /// Diagnose methods which overload virtual methods in a base class
9704 /// without overriding any.
9705 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9706   if (MD->isInvalidDecl())
9707     return;
9708 
9709   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9710     return;
9711 
9712   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9713   FindHiddenVirtualMethods(MD, OverloadedMethods);
9714   if (!OverloadedMethods.empty()) {
9715     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9716       << MD << (OverloadedMethods.size() > 1);
9717 
9718     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9719   }
9720 }
9721 
9722 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9723   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9724     // No diagnostics if this is a template instantiation.
9725     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9726       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9727            diag::ext_cannot_use_trivial_abi) << &RD;
9728       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9729            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9730     }
9731     RD.dropAttr<TrivialABIAttr>();
9732   };
9733 
9734   // Ill-formed if the copy and move constructors are deleted.
9735   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9736     // If the type is dependent, then assume it might have
9737     // implicit copy or move ctor because we won't know yet at this point.
9738     if (RD.isDependentType())
9739       return true;
9740     if (RD.needsImplicitCopyConstructor() &&
9741         !RD.defaultedCopyConstructorIsDeleted())
9742       return true;
9743     if (RD.needsImplicitMoveConstructor() &&
9744         !RD.defaultedMoveConstructorIsDeleted())
9745       return true;
9746     for (const CXXConstructorDecl *CD : RD.ctors())
9747       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9748         return true;
9749     return false;
9750   };
9751 
9752   if (!HasNonDeletedCopyOrMoveConstructor()) {
9753     PrintDiagAndRemoveAttr(0);
9754     return;
9755   }
9756 
9757   // Ill-formed if the struct has virtual functions.
9758   if (RD.isPolymorphic()) {
9759     PrintDiagAndRemoveAttr(1);
9760     return;
9761   }
9762 
9763   for (const auto &B : RD.bases()) {
9764     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9765     // virtual base.
9766     if (!B.getType()->isDependentType() &&
9767         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9768       PrintDiagAndRemoveAttr(2);
9769       return;
9770     }
9771 
9772     if (B.isVirtual()) {
9773       PrintDiagAndRemoveAttr(3);
9774       return;
9775     }
9776   }
9777 
9778   for (const auto *FD : RD.fields()) {
9779     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9780     // non-trivial for the purpose of calls.
9781     QualType FT = FD->getType();
9782     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9783       PrintDiagAndRemoveAttr(4);
9784       return;
9785     }
9786 
9787     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9788       if (!RT->isDependentType() &&
9789           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9790         PrintDiagAndRemoveAttr(5);
9791         return;
9792       }
9793   }
9794 }
9795 
9796 void Sema::ActOnFinishCXXMemberSpecification(
9797     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9798     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9799   if (!TagDecl)
9800     return;
9801 
9802   AdjustDeclIfTemplate(TagDecl);
9803 
9804   for (const ParsedAttr &AL : AttrList) {
9805     if (AL.getKind() != ParsedAttr::AT_Visibility)
9806       continue;
9807     AL.setInvalid();
9808     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9809   }
9810 
9811   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9812               // strict aliasing violation!
9813               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9814               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9815 
9816   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9817 }
9818 
9819 /// Find the equality comparison functions that should be implicitly declared
9820 /// in a given class definition, per C++2a [class.compare.default]p3.
9821 static void findImplicitlyDeclaredEqualityComparisons(
9822     ASTContext &Ctx, CXXRecordDecl *RD,
9823     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9824   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9825   if (!RD->lookup(EqEq).empty())
9826     // Member operator== explicitly declared: no implicit operator==s.
9827     return;
9828 
9829   // Traverse friends looking for an '==' or a '<=>'.
9830   for (FriendDecl *Friend : RD->friends()) {
9831     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9832     if (!FD) continue;
9833 
9834     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9835       // Friend operator== explicitly declared: no implicit operator==s.
9836       Spaceships.clear();
9837       return;
9838     }
9839 
9840     if (FD->getOverloadedOperator() == OO_Spaceship &&
9841         FD->isExplicitlyDefaulted())
9842       Spaceships.push_back(FD);
9843   }
9844 
9845   // Look for members named 'operator<=>'.
9846   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9847   for (NamedDecl *ND : RD->lookup(Cmp)) {
9848     // Note that we could find a non-function here (either a function template
9849     // or a using-declaration). Neither case results in an implicit
9850     // 'operator=='.
9851     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9852       if (FD->isExplicitlyDefaulted())
9853         Spaceships.push_back(FD);
9854   }
9855 }
9856 
9857 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9858 /// special functions, such as the default constructor, copy
9859 /// constructor, or destructor, to the given C++ class (C++
9860 /// [special]p1).  This routine can only be executed just before the
9861 /// definition of the class is complete.
9862 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9863   // Don't add implicit special members to templated classes.
9864   // FIXME: This means unqualified lookups for 'operator=' within a class
9865   // template don't work properly.
9866   if (!ClassDecl->isDependentType()) {
9867     if (ClassDecl->needsImplicitDefaultConstructor()) {
9868       ++getASTContext().NumImplicitDefaultConstructors;
9869 
9870       if (ClassDecl->hasInheritedConstructor())
9871         DeclareImplicitDefaultConstructor(ClassDecl);
9872     }
9873 
9874     if (ClassDecl->needsImplicitCopyConstructor()) {
9875       ++getASTContext().NumImplicitCopyConstructors;
9876 
9877       // If the properties or semantics of the copy constructor couldn't be
9878       // determined while the class was being declared, force a declaration
9879       // of it now.
9880       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9881           ClassDecl->hasInheritedConstructor())
9882         DeclareImplicitCopyConstructor(ClassDecl);
9883       // For the MS ABI we need to know whether the copy ctor is deleted. A
9884       // prerequisite for deleting the implicit copy ctor is that the class has
9885       // a move ctor or move assignment that is either user-declared or whose
9886       // semantics are inherited from a subobject. FIXME: We should provide a
9887       // more direct way for CodeGen to ask whether the constructor was deleted.
9888       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9889                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9890                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9891                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9892                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9893         DeclareImplicitCopyConstructor(ClassDecl);
9894     }
9895 
9896     if (getLangOpts().CPlusPlus11 &&
9897         ClassDecl->needsImplicitMoveConstructor()) {
9898       ++getASTContext().NumImplicitMoveConstructors;
9899 
9900       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9901           ClassDecl->hasInheritedConstructor())
9902         DeclareImplicitMoveConstructor(ClassDecl);
9903     }
9904 
9905     if (ClassDecl->needsImplicitCopyAssignment()) {
9906       ++getASTContext().NumImplicitCopyAssignmentOperators;
9907 
9908       // If we have a dynamic class, then the copy assignment operator may be
9909       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9910       // it shows up in the right place in the vtable and that we diagnose
9911       // problems with the implicit exception specification.
9912       if (ClassDecl->isDynamicClass() ||
9913           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9914           ClassDecl->hasInheritedAssignment())
9915         DeclareImplicitCopyAssignment(ClassDecl);
9916     }
9917 
9918     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9919       ++getASTContext().NumImplicitMoveAssignmentOperators;
9920 
9921       // Likewise for the move assignment operator.
9922       if (ClassDecl->isDynamicClass() ||
9923           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9924           ClassDecl->hasInheritedAssignment())
9925         DeclareImplicitMoveAssignment(ClassDecl);
9926     }
9927 
9928     if (ClassDecl->needsImplicitDestructor()) {
9929       ++getASTContext().NumImplicitDestructors;
9930 
9931       // If we have a dynamic class, then the destructor may be virtual, so we
9932       // have to declare the destructor immediately. This ensures that, e.g., it
9933       // shows up in the right place in the vtable and that we diagnose problems
9934       // with the implicit exception specification.
9935       if (ClassDecl->isDynamicClass() ||
9936           ClassDecl->needsOverloadResolutionForDestructor())
9937         DeclareImplicitDestructor(ClassDecl);
9938     }
9939   }
9940 
9941   // C++2a [class.compare.default]p3:
9942   //   If the member-specification does not explicitly declare any member or
9943   //   friend named operator==, an == operator function is declared implicitly
9944   //   for each defaulted three-way comparison operator function defined in
9945   //   the member-specification
9946   // FIXME: Consider doing this lazily.
9947   // We do this during the initial parse for a class template, not during
9948   // instantiation, so that we can handle unqualified lookups for 'operator=='
9949   // when parsing the template.
9950   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9951     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9952     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9953                                               DefaultedSpaceships);
9954     for (auto *FD : DefaultedSpaceships)
9955       DeclareImplicitEqualityComparison(ClassDecl, FD);
9956   }
9957 }
9958 
9959 unsigned
9960 Sema::ActOnReenterTemplateScope(Decl *D,
9961                                 llvm::function_ref<Scope *()> EnterScope) {
9962   if (!D)
9963     return 0;
9964   AdjustDeclIfTemplate(D);
9965 
9966   // In order to get name lookup right, reenter template scopes in order from
9967   // outermost to innermost.
9968   SmallVector<TemplateParameterList *, 4> ParameterLists;
9969   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9970 
9971   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9972     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9973       ParameterLists.push_back(DD->getTemplateParameterList(i));
9974 
9975     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9976       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9977         ParameterLists.push_back(FTD->getTemplateParameters());
9978     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
9979       LookupDC = VD->getDeclContext();
9980 
9981       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
9982         ParameterLists.push_back(VTD->getTemplateParameters());
9983       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
9984         ParameterLists.push_back(PSD->getTemplateParameters());
9985     }
9986   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9987     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9988       ParameterLists.push_back(TD->getTemplateParameterList(i));
9989 
9990     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9991       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9992         ParameterLists.push_back(CTD->getTemplateParameters());
9993       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9994         ParameterLists.push_back(PSD->getTemplateParameters());
9995     }
9996   }
9997   // FIXME: Alias declarations and concepts.
9998 
9999   unsigned Count = 0;
10000   Scope *InnermostTemplateScope = nullptr;
10001   for (TemplateParameterList *Params : ParameterLists) {
10002     // Ignore explicit specializations; they don't contribute to the template
10003     // depth.
10004     if (Params->size() == 0)
10005       continue;
10006 
10007     InnermostTemplateScope = EnterScope();
10008     for (NamedDecl *Param : *Params) {
10009       if (Param->getDeclName()) {
10010         InnermostTemplateScope->AddDecl(Param);
10011         IdResolver.AddDecl(Param);
10012       }
10013     }
10014     ++Count;
10015   }
10016 
10017   // Associate the new template scopes with the corresponding entities.
10018   if (InnermostTemplateScope) {
10019     assert(LookupDC && "no enclosing DeclContext for template lookup");
10020     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10021   }
10022 
10023   return Count;
10024 }
10025 
10026 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10027   if (!RecordD) return;
10028   AdjustDeclIfTemplate(RecordD);
10029   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10030   PushDeclContext(S, Record);
10031 }
10032 
10033 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10034   if (!RecordD) return;
10035   PopDeclContext();
10036 }
10037 
10038 /// This is used to implement the constant expression evaluation part of the
10039 /// attribute enable_if extension. There is nothing in standard C++ which would
10040 /// require reentering parameters.
10041 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10042   if (!Param)
10043     return;
10044 
10045   S->AddDecl(Param);
10046   if (Param->getDeclName())
10047     IdResolver.AddDecl(Param);
10048 }
10049 
10050 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10051 /// parsing a top-level (non-nested) C++ class, and we are now
10052 /// parsing those parts of the given Method declaration that could
10053 /// not be parsed earlier (C++ [class.mem]p2), such as default
10054 /// arguments. This action should enter the scope of the given
10055 /// Method declaration as if we had just parsed the qualified method
10056 /// name. However, it should not bring the parameters into scope;
10057 /// that will be performed by ActOnDelayedCXXMethodParameter.
10058 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10059 }
10060 
10061 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10062 /// C++ method declaration. We're (re-)introducing the given
10063 /// function parameter into scope for use in parsing later parts of
10064 /// the method declaration. For example, we could see an
10065 /// ActOnParamDefaultArgument event for this parameter.
10066 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10067   if (!ParamD)
10068     return;
10069 
10070   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10071 
10072   S->AddDecl(Param);
10073   if (Param->getDeclName())
10074     IdResolver.AddDecl(Param);
10075 }
10076 
10077 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10078 /// processing the delayed method declaration for Method. The method
10079 /// declaration is now considered finished. There may be a separate
10080 /// ActOnStartOfFunctionDef action later (not necessarily
10081 /// immediately!) for this method, if it was also defined inside the
10082 /// class body.
10083 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10084   if (!MethodD)
10085     return;
10086 
10087   AdjustDeclIfTemplate(MethodD);
10088 
10089   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10090 
10091   // Now that we have our default arguments, check the constructor
10092   // again. It could produce additional diagnostics or affect whether
10093   // the class has implicitly-declared destructors, among other
10094   // things.
10095   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10096     CheckConstructor(Constructor);
10097 
10098   // Check the default arguments, which we may have added.
10099   if (!Method->isInvalidDecl())
10100     CheckCXXDefaultArguments(Method);
10101 }
10102 
10103 // Emit the given diagnostic for each non-address-space qualifier.
10104 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10105 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10106   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10107   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10108     bool DiagOccured = false;
10109     FTI.MethodQualifiers->forEachQualifier(
10110         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10111                                    SourceLocation SL) {
10112           // This diagnostic should be emitted on any qualifier except an addr
10113           // space qualifier. However, forEachQualifier currently doesn't visit
10114           // addr space qualifiers, so there's no way to write this condition
10115           // right now; we just diagnose on everything.
10116           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10117           DiagOccured = true;
10118         });
10119     if (DiagOccured)
10120       D.setInvalidType();
10121   }
10122 }
10123 
10124 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10125 /// the well-formedness of the constructor declarator @p D with type @p
10126 /// R. If there are any errors in the declarator, this routine will
10127 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10128 /// will be updated to reflect a well-formed type for the constructor and
10129 /// returned.
10130 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10131                                           StorageClass &SC) {
10132   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10133 
10134   // C++ [class.ctor]p3:
10135   //   A constructor shall not be virtual (10.3) or static (9.4). A
10136   //   constructor can be invoked for a const, volatile or const
10137   //   volatile object. A constructor shall not be declared const,
10138   //   volatile, or const volatile (9.3.2).
10139   if (isVirtual) {
10140     if (!D.isInvalidType())
10141       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10142         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10143         << SourceRange(D.getIdentifierLoc());
10144     D.setInvalidType();
10145   }
10146   if (SC == SC_Static) {
10147     if (!D.isInvalidType())
10148       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10149         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10150         << SourceRange(D.getIdentifierLoc());
10151     D.setInvalidType();
10152     SC = SC_None;
10153   }
10154 
10155   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10156     diagnoseIgnoredQualifiers(
10157         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10158         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10159         D.getDeclSpec().getRestrictSpecLoc(),
10160         D.getDeclSpec().getAtomicSpecLoc());
10161     D.setInvalidType();
10162   }
10163 
10164   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10165 
10166   // C++0x [class.ctor]p4:
10167   //   A constructor shall not be declared with a ref-qualifier.
10168   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10169   if (FTI.hasRefQualifier()) {
10170     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10171       << FTI.RefQualifierIsLValueRef
10172       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10173     D.setInvalidType();
10174   }
10175 
10176   // Rebuild the function type "R" without any type qualifiers (in
10177   // case any of the errors above fired) and with "void" as the
10178   // return type, since constructors don't have return types.
10179   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10180   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10181     return R;
10182 
10183   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10184   EPI.TypeQuals = Qualifiers();
10185   EPI.RefQualifier = RQ_None;
10186 
10187   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10188 }
10189 
10190 /// CheckConstructor - Checks a fully-formed constructor for
10191 /// well-formedness, issuing any diagnostics required. Returns true if
10192 /// the constructor declarator is invalid.
10193 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10194   CXXRecordDecl *ClassDecl
10195     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10196   if (!ClassDecl)
10197     return Constructor->setInvalidDecl();
10198 
10199   // C++ [class.copy]p3:
10200   //   A declaration of a constructor for a class X is ill-formed if
10201   //   its first parameter is of type (optionally cv-qualified) X and
10202   //   either there are no other parameters or else all other
10203   //   parameters have default arguments.
10204   if (!Constructor->isInvalidDecl() &&
10205       Constructor->hasOneParamOrDefaultArgs() &&
10206       Constructor->getTemplateSpecializationKind() !=
10207           TSK_ImplicitInstantiation) {
10208     QualType ParamType = Constructor->getParamDecl(0)->getType();
10209     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10210     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10211       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10212       const char *ConstRef
10213         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10214                                                         : " const &";
10215       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10216         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10217 
10218       // FIXME: Rather that making the constructor invalid, we should endeavor
10219       // to fix the type.
10220       Constructor->setInvalidDecl();
10221     }
10222   }
10223 }
10224 
10225 /// CheckDestructor - Checks a fully-formed destructor definition for
10226 /// well-formedness, issuing any diagnostics required.  Returns true
10227 /// on error.
10228 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10229   CXXRecordDecl *RD = Destructor->getParent();
10230 
10231   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10232     SourceLocation Loc;
10233 
10234     if (!Destructor->isImplicit())
10235       Loc = Destructor->getLocation();
10236     else
10237       Loc = RD->getLocation();
10238 
10239     // If we have a virtual destructor, look up the deallocation function
10240     if (FunctionDecl *OperatorDelete =
10241             FindDeallocationFunctionForDestructor(Loc, RD)) {
10242       Expr *ThisArg = nullptr;
10243 
10244       // If the notional 'delete this' expression requires a non-trivial
10245       // conversion from 'this' to the type of a destroying operator delete's
10246       // first parameter, perform that conversion now.
10247       if (OperatorDelete->isDestroyingOperatorDelete()) {
10248         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10249         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10250           // C++ [class.dtor]p13:
10251           //   ... as if for the expression 'delete this' appearing in a
10252           //   non-virtual destructor of the destructor's class.
10253           ContextRAII SwitchContext(*this, Destructor);
10254           ExprResult This =
10255               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10256           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10257           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10258           if (This.isInvalid()) {
10259             // FIXME: Register this as a context note so that it comes out
10260             // in the right order.
10261             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10262             return true;
10263           }
10264           ThisArg = This.get();
10265         }
10266       }
10267 
10268       DiagnoseUseOfDecl(OperatorDelete, Loc);
10269       MarkFunctionReferenced(Loc, OperatorDelete);
10270       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10271     }
10272   }
10273 
10274   return false;
10275 }
10276 
10277 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10278 /// the well-formednes of the destructor declarator @p D with type @p
10279 /// R. If there are any errors in the declarator, this routine will
10280 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10281 /// will be updated to reflect a well-formed type for the destructor and
10282 /// returned.
10283 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10284                                          StorageClass& SC) {
10285   // C++ [class.dtor]p1:
10286   //   [...] A typedef-name that names a class is a class-name
10287   //   (7.1.3); however, a typedef-name that names a class shall not
10288   //   be used as the identifier in the declarator for a destructor
10289   //   declaration.
10290   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10291   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10292     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10293       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10294   else if (const TemplateSpecializationType *TST =
10295              DeclaratorType->getAs<TemplateSpecializationType>())
10296     if (TST->isTypeAlias())
10297       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10298         << DeclaratorType << 1;
10299 
10300   // C++ [class.dtor]p2:
10301   //   A destructor is used to destroy objects of its class type. A
10302   //   destructor takes no parameters, and no return type can be
10303   //   specified for it (not even void). The address of a destructor
10304   //   shall not be taken. A destructor shall not be static. A
10305   //   destructor can be invoked for a const, volatile or const
10306   //   volatile object. A destructor shall not be declared const,
10307   //   volatile or const volatile (9.3.2).
10308   if (SC == SC_Static) {
10309     if (!D.isInvalidType())
10310       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10311         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10312         << SourceRange(D.getIdentifierLoc())
10313         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10314 
10315     SC = SC_None;
10316   }
10317   if (!D.isInvalidType()) {
10318     // Destructors don't have return types, but the parser will
10319     // happily parse something like:
10320     //
10321     //   class X {
10322     //     float ~X();
10323     //   };
10324     //
10325     // The return type will be eliminated later.
10326     if (D.getDeclSpec().hasTypeSpecifier())
10327       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10328         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10329         << SourceRange(D.getIdentifierLoc());
10330     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10331       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10332                                 SourceLocation(),
10333                                 D.getDeclSpec().getConstSpecLoc(),
10334                                 D.getDeclSpec().getVolatileSpecLoc(),
10335                                 D.getDeclSpec().getRestrictSpecLoc(),
10336                                 D.getDeclSpec().getAtomicSpecLoc());
10337       D.setInvalidType();
10338     }
10339   }
10340 
10341   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10342 
10343   // C++0x [class.dtor]p2:
10344   //   A destructor shall not be declared with a ref-qualifier.
10345   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10346   if (FTI.hasRefQualifier()) {
10347     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10348       << FTI.RefQualifierIsLValueRef
10349       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10350     D.setInvalidType();
10351   }
10352 
10353   // Make sure we don't have any parameters.
10354   if (FTIHasNonVoidParameters(FTI)) {
10355     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10356 
10357     // Delete the parameters.
10358     FTI.freeParams();
10359     D.setInvalidType();
10360   }
10361 
10362   // Make sure the destructor isn't variadic.
10363   if (FTI.isVariadic) {
10364     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10365     D.setInvalidType();
10366   }
10367 
10368   // Rebuild the function type "R" without any type qualifiers or
10369   // parameters (in case any of the errors above fired) and with
10370   // "void" as the return type, since destructors don't have return
10371   // types.
10372   if (!D.isInvalidType())
10373     return R;
10374 
10375   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10376   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10377   EPI.Variadic = false;
10378   EPI.TypeQuals = Qualifiers();
10379   EPI.RefQualifier = RQ_None;
10380   return Context.getFunctionType(Context.VoidTy, None, EPI);
10381 }
10382 
10383 static void extendLeft(SourceRange &R, SourceRange Before) {
10384   if (Before.isInvalid())
10385     return;
10386   R.setBegin(Before.getBegin());
10387   if (R.getEnd().isInvalid())
10388     R.setEnd(Before.getEnd());
10389 }
10390 
10391 static void extendRight(SourceRange &R, SourceRange After) {
10392   if (After.isInvalid())
10393     return;
10394   if (R.getBegin().isInvalid())
10395     R.setBegin(After.getBegin());
10396   R.setEnd(After.getEnd());
10397 }
10398 
10399 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10400 /// well-formednes of the conversion function declarator @p D with
10401 /// type @p R. If there are any errors in the declarator, this routine
10402 /// will emit diagnostics and return true. Otherwise, it will return
10403 /// false. Either way, the type @p R will be updated to reflect a
10404 /// well-formed type for the conversion operator.
10405 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10406                                      StorageClass& SC) {
10407   // C++ [class.conv.fct]p1:
10408   //   Neither parameter types nor return type can be specified. The
10409   //   type of a conversion function (8.3.5) is "function taking no
10410   //   parameter returning conversion-type-id."
10411   if (SC == SC_Static) {
10412     if (!D.isInvalidType())
10413       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10414         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10415         << D.getName().getSourceRange();
10416     D.setInvalidType();
10417     SC = SC_None;
10418   }
10419 
10420   TypeSourceInfo *ConvTSI = nullptr;
10421   QualType ConvType =
10422       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10423 
10424   const DeclSpec &DS = D.getDeclSpec();
10425   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10426     // Conversion functions don't have return types, but the parser will
10427     // happily parse something like:
10428     //
10429     //   class X {
10430     //     float operator bool();
10431     //   };
10432     //
10433     // The return type will be changed later anyway.
10434     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10435       << SourceRange(DS.getTypeSpecTypeLoc())
10436       << SourceRange(D.getIdentifierLoc());
10437     D.setInvalidType();
10438   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10439     // It's also plausible that the user writes type qualifiers in the wrong
10440     // place, such as:
10441     //   struct S { const operator int(); };
10442     // FIXME: we could provide a fixit to move the qualifiers onto the
10443     // conversion type.
10444     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10445         << SourceRange(D.getIdentifierLoc()) << 0;
10446     D.setInvalidType();
10447   }
10448 
10449   const auto *Proto = R->castAs<FunctionProtoType>();
10450 
10451   // Make sure we don't have any parameters.
10452   if (Proto->getNumParams() > 0) {
10453     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10454 
10455     // Delete the parameters.
10456     D.getFunctionTypeInfo().freeParams();
10457     D.setInvalidType();
10458   } else if (Proto->isVariadic()) {
10459     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10460     D.setInvalidType();
10461   }
10462 
10463   // Diagnose "&operator bool()" and other such nonsense.  This
10464   // is actually a gcc extension which we don't support.
10465   if (Proto->getReturnType() != ConvType) {
10466     bool NeedsTypedef = false;
10467     SourceRange Before, After;
10468 
10469     // Walk the chunks and extract information on them for our diagnostic.
10470     bool PastFunctionChunk = false;
10471     for (auto &Chunk : D.type_objects()) {
10472       switch (Chunk.Kind) {
10473       case DeclaratorChunk::Function:
10474         if (!PastFunctionChunk) {
10475           if (Chunk.Fun.HasTrailingReturnType) {
10476             TypeSourceInfo *TRT = nullptr;
10477             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10478             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10479           }
10480           PastFunctionChunk = true;
10481           break;
10482         }
10483         LLVM_FALLTHROUGH;
10484       case DeclaratorChunk::Array:
10485         NeedsTypedef = true;
10486         extendRight(After, Chunk.getSourceRange());
10487         break;
10488 
10489       case DeclaratorChunk::Pointer:
10490       case DeclaratorChunk::BlockPointer:
10491       case DeclaratorChunk::Reference:
10492       case DeclaratorChunk::MemberPointer:
10493       case DeclaratorChunk::Pipe:
10494         extendLeft(Before, Chunk.getSourceRange());
10495         break;
10496 
10497       case DeclaratorChunk::Paren:
10498         extendLeft(Before, Chunk.Loc);
10499         extendRight(After, Chunk.EndLoc);
10500         break;
10501       }
10502     }
10503 
10504     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10505                          After.isValid()  ? After.getBegin() :
10506                                             D.getIdentifierLoc();
10507     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10508     DB << Before << After;
10509 
10510     if (!NeedsTypedef) {
10511       DB << /*don't need a typedef*/0;
10512 
10513       // If we can provide a correct fix-it hint, do so.
10514       if (After.isInvalid() && ConvTSI) {
10515         SourceLocation InsertLoc =
10516             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10517         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10518            << FixItHint::CreateInsertionFromRange(
10519                   InsertLoc, CharSourceRange::getTokenRange(Before))
10520            << FixItHint::CreateRemoval(Before);
10521       }
10522     } else if (!Proto->getReturnType()->isDependentType()) {
10523       DB << /*typedef*/1 << Proto->getReturnType();
10524     } else if (getLangOpts().CPlusPlus11) {
10525       DB << /*alias template*/2 << Proto->getReturnType();
10526     } else {
10527       DB << /*might not be fixable*/3;
10528     }
10529 
10530     // Recover by incorporating the other type chunks into the result type.
10531     // Note, this does *not* change the name of the function. This is compatible
10532     // with the GCC extension:
10533     //   struct S { &operator int(); } s;
10534     //   int &r = s.operator int(); // ok in GCC
10535     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10536     ConvType = Proto->getReturnType();
10537   }
10538 
10539   // C++ [class.conv.fct]p4:
10540   //   The conversion-type-id shall not represent a function type nor
10541   //   an array type.
10542   if (ConvType->isArrayType()) {
10543     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10544     ConvType = Context.getPointerType(ConvType);
10545     D.setInvalidType();
10546   } else if (ConvType->isFunctionType()) {
10547     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10548     ConvType = Context.getPointerType(ConvType);
10549     D.setInvalidType();
10550   }
10551 
10552   // Rebuild the function type "R" without any parameters (in case any
10553   // of the errors above fired) and with the conversion type as the
10554   // return type.
10555   if (D.isInvalidType())
10556     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10557 
10558   // C++0x explicit conversion operators.
10559   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10560     Diag(DS.getExplicitSpecLoc(),
10561          getLangOpts().CPlusPlus11
10562              ? diag::warn_cxx98_compat_explicit_conversion_functions
10563              : diag::ext_explicit_conversion_functions)
10564         << SourceRange(DS.getExplicitSpecRange());
10565 }
10566 
10567 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10568 /// the declaration of the given C++ conversion function. This routine
10569 /// is responsible for recording the conversion function in the C++
10570 /// class, if possible.
10571 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10572   assert(Conversion && "Expected to receive a conversion function declaration");
10573 
10574   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10575 
10576   // Make sure we aren't redeclaring the conversion function.
10577   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10578   // C++ [class.conv.fct]p1:
10579   //   [...] A conversion function is never used to convert a
10580   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10581   //   same object type (or a reference to it), to a (possibly
10582   //   cv-qualified) base class of that type (or a reference to it),
10583   //   or to (possibly cv-qualified) void.
10584   QualType ClassType
10585     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10586   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10587     ConvType = ConvTypeRef->getPointeeType();
10588   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10589       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10590     /* Suppress diagnostics for instantiations. */;
10591   else if (Conversion->size_overridden_methods() != 0)
10592     /* Suppress diagnostics for overriding virtual function in a base class. */;
10593   else if (ConvType->isRecordType()) {
10594     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10595     if (ConvType == ClassType)
10596       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10597         << ClassType;
10598     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10599       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10600         <<  ClassType << ConvType;
10601   } else if (ConvType->isVoidType()) {
10602     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10603       << ClassType << ConvType;
10604   }
10605 
10606   if (FunctionTemplateDecl *ConversionTemplate
10607                                 = Conversion->getDescribedFunctionTemplate())
10608     return ConversionTemplate;
10609 
10610   return Conversion;
10611 }
10612 
10613 namespace {
10614 /// Utility class to accumulate and print a diagnostic listing the invalid
10615 /// specifier(s) on a declaration.
10616 struct BadSpecifierDiagnoser {
10617   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10618       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10619   ~BadSpecifierDiagnoser() {
10620     Diagnostic << Specifiers;
10621   }
10622 
10623   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10624     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10625   }
10626   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10627     return check(SpecLoc,
10628                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10629   }
10630   void check(SourceLocation SpecLoc, const char *Spec) {
10631     if (SpecLoc.isInvalid()) return;
10632     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10633     if (!Specifiers.empty()) Specifiers += " ";
10634     Specifiers += Spec;
10635   }
10636 
10637   Sema &S;
10638   Sema::SemaDiagnosticBuilder Diagnostic;
10639   std::string Specifiers;
10640 };
10641 }
10642 
10643 /// Check the validity of a declarator that we parsed for a deduction-guide.
10644 /// These aren't actually declarators in the grammar, so we need to check that
10645 /// the user didn't specify any pieces that are not part of the deduction-guide
10646 /// grammar.
10647 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10648                                          StorageClass &SC) {
10649   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10650   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10651   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10652 
10653   // C++ [temp.deduct.guide]p3:
10654   //   A deduction-gide shall be declared in the same scope as the
10655   //   corresponding class template.
10656   if (!CurContext->getRedeclContext()->Equals(
10657           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10658     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10659       << GuidedTemplateDecl;
10660     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10661   }
10662 
10663   auto &DS = D.getMutableDeclSpec();
10664   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10665   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10666       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10667       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10668     BadSpecifierDiagnoser Diagnoser(
10669         *this, D.getIdentifierLoc(),
10670         diag::err_deduction_guide_invalid_specifier);
10671 
10672     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10673     DS.ClearStorageClassSpecs();
10674     SC = SC_None;
10675 
10676     // 'explicit' is permitted.
10677     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10678     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10679     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10680     DS.ClearConstexprSpec();
10681 
10682     Diagnoser.check(DS.getConstSpecLoc(), "const");
10683     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10684     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10685     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10686     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10687     DS.ClearTypeQualifiers();
10688 
10689     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10690     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10691     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10692     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10693     DS.ClearTypeSpecType();
10694   }
10695 
10696   if (D.isInvalidType())
10697     return;
10698 
10699   // Check the declarator is simple enough.
10700   bool FoundFunction = false;
10701   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10702     if (Chunk.Kind == DeclaratorChunk::Paren)
10703       continue;
10704     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10705       Diag(D.getDeclSpec().getBeginLoc(),
10706            diag::err_deduction_guide_with_complex_decl)
10707           << D.getSourceRange();
10708       break;
10709     }
10710     if (!Chunk.Fun.hasTrailingReturnType()) {
10711       Diag(D.getName().getBeginLoc(),
10712            diag::err_deduction_guide_no_trailing_return_type);
10713       break;
10714     }
10715 
10716     // Check that the return type is written as a specialization of
10717     // the template specified as the deduction-guide's name.
10718     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10719     TypeSourceInfo *TSI = nullptr;
10720     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10721     assert(TSI && "deduction guide has valid type but invalid return type?");
10722     bool AcceptableReturnType = false;
10723     bool MightInstantiateToSpecialization = false;
10724     if (auto RetTST =
10725             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10726       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10727       bool TemplateMatches =
10728           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10729       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10730         AcceptableReturnType = true;
10731       else {
10732         // This could still instantiate to the right type, unless we know it
10733         // names the wrong class template.
10734         auto *TD = SpecifiedName.getAsTemplateDecl();
10735         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10736                                              !TemplateMatches);
10737       }
10738     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10739       MightInstantiateToSpecialization = true;
10740     }
10741 
10742     if (!AcceptableReturnType) {
10743       Diag(TSI->getTypeLoc().getBeginLoc(),
10744            diag::err_deduction_guide_bad_trailing_return_type)
10745           << GuidedTemplate << TSI->getType()
10746           << MightInstantiateToSpecialization
10747           << TSI->getTypeLoc().getSourceRange();
10748     }
10749 
10750     // Keep going to check that we don't have any inner declarator pieces (we
10751     // could still have a function returning a pointer to a function).
10752     FoundFunction = true;
10753   }
10754 
10755   if (D.isFunctionDefinition())
10756     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10757 }
10758 
10759 //===----------------------------------------------------------------------===//
10760 // Namespace Handling
10761 //===----------------------------------------------------------------------===//
10762 
10763 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10764 /// reopened.
10765 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10766                                             SourceLocation Loc,
10767                                             IdentifierInfo *II, bool *IsInline,
10768                                             NamespaceDecl *PrevNS) {
10769   assert(*IsInline != PrevNS->isInline());
10770 
10771   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10772   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10773   // inline namespaces, with the intention of bringing names into namespace std.
10774   //
10775   // We support this just well enough to get that case working; this is not
10776   // sufficient to support reopening namespaces as inline in general.
10777   if (*IsInline && II && II->getName().startswith("__atomic") &&
10778       S.getSourceManager().isInSystemHeader(Loc)) {
10779     // Mark all prior declarations of the namespace as inline.
10780     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10781          NS = NS->getPreviousDecl())
10782       NS->setInline(*IsInline);
10783     // Patch up the lookup table for the containing namespace. This isn't really
10784     // correct, but it's good enough for this particular case.
10785     for (auto *I : PrevNS->decls())
10786       if (auto *ND = dyn_cast<NamedDecl>(I))
10787         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10788     return;
10789   }
10790 
10791   if (PrevNS->isInline())
10792     // The user probably just forgot the 'inline', so suggest that it
10793     // be added back.
10794     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10795       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10796   else
10797     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10798 
10799   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10800   *IsInline = PrevNS->isInline();
10801 }
10802 
10803 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10804 /// definition.
10805 Decl *Sema::ActOnStartNamespaceDef(
10806     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10807     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10808     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10809   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10810   // For anonymous namespace, take the location of the left brace.
10811   SourceLocation Loc = II ? IdentLoc : LBrace;
10812   bool IsInline = InlineLoc.isValid();
10813   bool IsInvalid = false;
10814   bool IsStd = false;
10815   bool AddToKnown = false;
10816   Scope *DeclRegionScope = NamespcScope->getParent();
10817 
10818   NamespaceDecl *PrevNS = nullptr;
10819   if (II) {
10820     // C++ [namespace.def]p2:
10821     //   The identifier in an original-namespace-definition shall not
10822     //   have been previously defined in the declarative region in
10823     //   which the original-namespace-definition appears. The
10824     //   identifier in an original-namespace-definition is the name of
10825     //   the namespace. Subsequently in that declarative region, it is
10826     //   treated as an original-namespace-name.
10827     //
10828     // Since namespace names are unique in their scope, and we don't
10829     // look through using directives, just look for any ordinary names
10830     // as if by qualified name lookup.
10831     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10832                    ForExternalRedeclaration);
10833     LookupQualifiedName(R, CurContext->getRedeclContext());
10834     NamedDecl *PrevDecl =
10835         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10836     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10837 
10838     if (PrevNS) {
10839       // This is an extended namespace definition.
10840       if (IsInline != PrevNS->isInline())
10841         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10842                                         &IsInline, PrevNS);
10843     } else if (PrevDecl) {
10844       // This is an invalid name redefinition.
10845       Diag(Loc, diag::err_redefinition_different_kind)
10846         << II;
10847       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10848       IsInvalid = true;
10849       // Continue on to push Namespc as current DeclContext and return it.
10850     } else if (II->isStr("std") &&
10851                CurContext->getRedeclContext()->isTranslationUnit()) {
10852       // This is the first "real" definition of the namespace "std", so update
10853       // our cache of the "std" namespace to point at this definition.
10854       PrevNS = getStdNamespace();
10855       IsStd = true;
10856       AddToKnown = !IsInline;
10857     } else {
10858       // We've seen this namespace for the first time.
10859       AddToKnown = !IsInline;
10860     }
10861   } else {
10862     // Anonymous namespaces.
10863 
10864     // Determine whether the parent already has an anonymous namespace.
10865     DeclContext *Parent = CurContext->getRedeclContext();
10866     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10867       PrevNS = TU->getAnonymousNamespace();
10868     } else {
10869       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10870       PrevNS = ND->getAnonymousNamespace();
10871     }
10872 
10873     if (PrevNS && IsInline != PrevNS->isInline())
10874       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10875                                       &IsInline, PrevNS);
10876   }
10877 
10878   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10879                                                  StartLoc, Loc, II, PrevNS);
10880   if (IsInvalid)
10881     Namespc->setInvalidDecl();
10882 
10883   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10884   AddPragmaAttributes(DeclRegionScope, Namespc);
10885 
10886   // FIXME: Should we be merging attributes?
10887   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10888     PushNamespaceVisibilityAttr(Attr, Loc);
10889 
10890   if (IsStd)
10891     StdNamespace = Namespc;
10892   if (AddToKnown)
10893     KnownNamespaces[Namespc] = false;
10894 
10895   if (II) {
10896     PushOnScopeChains(Namespc, DeclRegionScope);
10897   } else {
10898     // Link the anonymous namespace into its parent.
10899     DeclContext *Parent = CurContext->getRedeclContext();
10900     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10901       TU->setAnonymousNamespace(Namespc);
10902     } else {
10903       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10904     }
10905 
10906     CurContext->addDecl(Namespc);
10907 
10908     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10909     //   behaves as if it were replaced by
10910     //     namespace unique { /* empty body */ }
10911     //     using namespace unique;
10912     //     namespace unique { namespace-body }
10913     //   where all occurrences of 'unique' in a translation unit are
10914     //   replaced by the same identifier and this identifier differs
10915     //   from all other identifiers in the entire program.
10916 
10917     // We just create the namespace with an empty name and then add an
10918     // implicit using declaration, just like the standard suggests.
10919     //
10920     // CodeGen enforces the "universally unique" aspect by giving all
10921     // declarations semantically contained within an anonymous
10922     // namespace internal linkage.
10923 
10924     if (!PrevNS) {
10925       UD = UsingDirectiveDecl::Create(Context, Parent,
10926                                       /* 'using' */ LBrace,
10927                                       /* 'namespace' */ SourceLocation(),
10928                                       /* qualifier */ NestedNameSpecifierLoc(),
10929                                       /* identifier */ SourceLocation(),
10930                                       Namespc,
10931                                       /* Ancestor */ Parent);
10932       UD->setImplicit();
10933       Parent->addDecl(UD);
10934     }
10935   }
10936 
10937   ActOnDocumentableDecl(Namespc);
10938 
10939   // Although we could have an invalid decl (i.e. the namespace name is a
10940   // redefinition), push it as current DeclContext and try to continue parsing.
10941   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10942   // for the namespace has the declarations that showed up in that particular
10943   // namespace definition.
10944   PushDeclContext(NamespcScope, Namespc);
10945   return Namespc;
10946 }
10947 
10948 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10949 /// is a namespace alias, returns the namespace it points to.
10950 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10951   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10952     return AD->getNamespace();
10953   return dyn_cast_or_null<NamespaceDecl>(D);
10954 }
10955 
10956 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10957 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10958 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10959   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10960   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10961   Namespc->setRBraceLoc(RBrace);
10962   PopDeclContext();
10963   if (Namespc->hasAttr<VisibilityAttr>())
10964     PopPragmaVisibility(true, RBrace);
10965   // If this namespace contains an export-declaration, export it now.
10966   if (DeferredExportedNamespaces.erase(Namespc))
10967     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10968 }
10969 
10970 CXXRecordDecl *Sema::getStdBadAlloc() const {
10971   return cast_or_null<CXXRecordDecl>(
10972                                   StdBadAlloc.get(Context.getExternalSource()));
10973 }
10974 
10975 EnumDecl *Sema::getStdAlignValT() const {
10976   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10977 }
10978 
10979 NamespaceDecl *Sema::getStdNamespace() const {
10980   return cast_or_null<NamespaceDecl>(
10981                                  StdNamespace.get(Context.getExternalSource()));
10982 }
10983 
10984 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10985   if (!StdExperimentalNamespaceCache) {
10986     if (auto Std = getStdNamespace()) {
10987       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10988                           SourceLocation(), LookupNamespaceName);
10989       if (!LookupQualifiedName(Result, Std) ||
10990           !(StdExperimentalNamespaceCache =
10991                 Result.getAsSingle<NamespaceDecl>()))
10992         Result.suppressDiagnostics();
10993     }
10994   }
10995   return StdExperimentalNamespaceCache;
10996 }
10997 
10998 namespace {
10999 
11000 enum UnsupportedSTLSelect {
11001   USS_InvalidMember,
11002   USS_MissingMember,
11003   USS_NonTrivial,
11004   USS_Other
11005 };
11006 
11007 struct InvalidSTLDiagnoser {
11008   Sema &S;
11009   SourceLocation Loc;
11010   QualType TyForDiags;
11011 
11012   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11013                       const VarDecl *VD = nullptr) {
11014     {
11015       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11016                << TyForDiags << ((int)Sel);
11017       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11018         assert(!Name.empty());
11019         D << Name;
11020       }
11021     }
11022     if (Sel == USS_InvalidMember) {
11023       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11024           << VD << VD->getSourceRange();
11025     }
11026     return QualType();
11027   }
11028 };
11029 } // namespace
11030 
11031 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11032                                            SourceLocation Loc,
11033                                            ComparisonCategoryUsage Usage) {
11034   assert(getLangOpts().CPlusPlus &&
11035          "Looking for comparison category type outside of C++.");
11036 
11037   // Use an elaborated type for diagnostics which has a name containing the
11038   // prepended 'std' namespace but not any inline namespace names.
11039   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11040     auto *NNS =
11041         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11042     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11043   };
11044 
11045   // Check if we've already successfully checked the comparison category type
11046   // before. If so, skip checking it again.
11047   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11048   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11049     // The only thing we need to check is that the type has a reachable
11050     // definition in the current context.
11051     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11052       return QualType();
11053 
11054     return Info->getType();
11055   }
11056 
11057   // If lookup failed
11058   if (!Info) {
11059     std::string NameForDiags = "std::";
11060     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11061     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11062         << NameForDiags << (int)Usage;
11063     return QualType();
11064   }
11065 
11066   assert(Info->Kind == Kind);
11067   assert(Info->Record);
11068 
11069   // Update the Record decl in case we encountered a forward declaration on our
11070   // first pass. FIXME: This is a bit of a hack.
11071   if (Info->Record->hasDefinition())
11072     Info->Record = Info->Record->getDefinition();
11073 
11074   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11075     return QualType();
11076 
11077   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11078 
11079   if (!Info->Record->isTriviallyCopyable())
11080     return UnsupportedSTLError(USS_NonTrivial);
11081 
11082   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11083     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11084     // Tolerate empty base classes.
11085     if (Base->isEmpty())
11086       continue;
11087     // Reject STL implementations which have at least one non-empty base.
11088     return UnsupportedSTLError();
11089   }
11090 
11091   // Check that the STL has implemented the types using a single integer field.
11092   // This expectation allows better codegen for builtin operators. We require:
11093   //   (1) The class has exactly one field.
11094   //   (2) The field is an integral or enumeration type.
11095   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11096   if (std::distance(FIt, FEnd) != 1 ||
11097       !FIt->getType()->isIntegralOrEnumerationType()) {
11098     return UnsupportedSTLError();
11099   }
11100 
11101   // Build each of the require values and store them in Info.
11102   for (ComparisonCategoryResult CCR :
11103        ComparisonCategories::getPossibleResultsForType(Kind)) {
11104     StringRef MemName = ComparisonCategories::getResultString(CCR);
11105     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11106 
11107     if (!ValInfo)
11108       return UnsupportedSTLError(USS_MissingMember, MemName);
11109 
11110     VarDecl *VD = ValInfo->VD;
11111     assert(VD && "should not be null!");
11112 
11113     // Attempt to diagnose reasons why the STL definition of this type
11114     // might be foobar, including it failing to be a constant expression.
11115     // TODO Handle more ways the lookup or result can be invalid.
11116     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11117         VD->isWeak() || !VD->checkInitIsICE())
11118       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11119 
11120     // Attempt to evaluate the var decl as a constant expression and extract
11121     // the value of its first field as a ICE. If this fails, the STL
11122     // implementation is not supported.
11123     if (!ValInfo->hasValidIntValue())
11124       return UnsupportedSTLError();
11125 
11126     MarkVariableReferenced(Loc, VD);
11127   }
11128 
11129   // We've successfully built the required types and expressions. Update
11130   // the cache and return the newly cached value.
11131   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11132   return Info->getType();
11133 }
11134 
11135 /// Retrieve the special "std" namespace, which may require us to
11136 /// implicitly define the namespace.
11137 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11138   if (!StdNamespace) {
11139     // The "std" namespace has not yet been defined, so build one implicitly.
11140     StdNamespace = NamespaceDecl::Create(Context,
11141                                          Context.getTranslationUnitDecl(),
11142                                          /*Inline=*/false,
11143                                          SourceLocation(), SourceLocation(),
11144                                          &PP.getIdentifierTable().get("std"),
11145                                          /*PrevDecl=*/nullptr);
11146     getStdNamespace()->setImplicit(true);
11147   }
11148 
11149   return getStdNamespace();
11150 }
11151 
11152 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11153   assert(getLangOpts().CPlusPlus &&
11154          "Looking for std::initializer_list outside of C++.");
11155 
11156   // We're looking for implicit instantiations of
11157   // template <typename E> class std::initializer_list.
11158 
11159   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11160     return false;
11161 
11162   ClassTemplateDecl *Template = nullptr;
11163   const TemplateArgument *Arguments = nullptr;
11164 
11165   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11166 
11167     ClassTemplateSpecializationDecl *Specialization =
11168         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11169     if (!Specialization)
11170       return false;
11171 
11172     Template = Specialization->getSpecializedTemplate();
11173     Arguments = Specialization->getTemplateArgs().data();
11174   } else if (const TemplateSpecializationType *TST =
11175                  Ty->getAs<TemplateSpecializationType>()) {
11176     Template = dyn_cast_or_null<ClassTemplateDecl>(
11177         TST->getTemplateName().getAsTemplateDecl());
11178     Arguments = TST->getArgs();
11179   }
11180   if (!Template)
11181     return false;
11182 
11183   if (!StdInitializerList) {
11184     // Haven't recognized std::initializer_list yet, maybe this is it.
11185     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11186     if (TemplateClass->getIdentifier() !=
11187             &PP.getIdentifierTable().get("initializer_list") ||
11188         !getStdNamespace()->InEnclosingNamespaceSetOf(
11189             TemplateClass->getDeclContext()))
11190       return false;
11191     // This is a template called std::initializer_list, but is it the right
11192     // template?
11193     TemplateParameterList *Params = Template->getTemplateParameters();
11194     if (Params->getMinRequiredArguments() != 1)
11195       return false;
11196     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11197       return false;
11198 
11199     // It's the right template.
11200     StdInitializerList = Template;
11201   }
11202 
11203   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11204     return false;
11205 
11206   // This is an instance of std::initializer_list. Find the argument type.
11207   if (Element)
11208     *Element = Arguments[0].getAsType();
11209   return true;
11210 }
11211 
11212 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11213   NamespaceDecl *Std = S.getStdNamespace();
11214   if (!Std) {
11215     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11216     return nullptr;
11217   }
11218 
11219   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11220                       Loc, Sema::LookupOrdinaryName);
11221   if (!S.LookupQualifiedName(Result, Std)) {
11222     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11223     return nullptr;
11224   }
11225   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11226   if (!Template) {
11227     Result.suppressDiagnostics();
11228     // We found something weird. Complain about the first thing we found.
11229     NamedDecl *Found = *Result.begin();
11230     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11231     return nullptr;
11232   }
11233 
11234   // We found some template called std::initializer_list. Now verify that it's
11235   // correct.
11236   TemplateParameterList *Params = Template->getTemplateParameters();
11237   if (Params->getMinRequiredArguments() != 1 ||
11238       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11239     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11240     return nullptr;
11241   }
11242 
11243   return Template;
11244 }
11245 
11246 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11247   if (!StdInitializerList) {
11248     StdInitializerList = LookupStdInitializerList(*this, Loc);
11249     if (!StdInitializerList)
11250       return QualType();
11251   }
11252 
11253   TemplateArgumentListInfo Args(Loc, Loc);
11254   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11255                                        Context.getTrivialTypeSourceInfo(Element,
11256                                                                         Loc)));
11257   return Context.getCanonicalType(
11258       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11259 }
11260 
11261 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11262   // C++ [dcl.init.list]p2:
11263   //   A constructor is an initializer-list constructor if its first parameter
11264   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11265   //   std::initializer_list<E> for some type E, and either there are no other
11266   //   parameters or else all other parameters have default arguments.
11267   if (!Ctor->hasOneParamOrDefaultArgs())
11268     return false;
11269 
11270   QualType ArgType = Ctor->getParamDecl(0)->getType();
11271   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11272     ArgType = RT->getPointeeType().getUnqualifiedType();
11273 
11274   return isStdInitializerList(ArgType, nullptr);
11275 }
11276 
11277 /// Determine whether a using statement is in a context where it will be
11278 /// apply in all contexts.
11279 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11280   switch (CurContext->getDeclKind()) {
11281     case Decl::TranslationUnit:
11282       return true;
11283     case Decl::LinkageSpec:
11284       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11285     default:
11286       return false;
11287   }
11288 }
11289 
11290 namespace {
11291 
11292 // Callback to only accept typo corrections that are namespaces.
11293 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11294 public:
11295   bool ValidateCandidate(const TypoCorrection &candidate) override {
11296     if (NamedDecl *ND = candidate.getCorrectionDecl())
11297       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11298     return false;
11299   }
11300 
11301   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11302     return std::make_unique<NamespaceValidatorCCC>(*this);
11303   }
11304 };
11305 
11306 }
11307 
11308 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11309                                        CXXScopeSpec &SS,
11310                                        SourceLocation IdentLoc,
11311                                        IdentifierInfo *Ident) {
11312   R.clear();
11313   NamespaceValidatorCCC CCC{};
11314   if (TypoCorrection Corrected =
11315           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11316                         Sema::CTK_ErrorRecovery)) {
11317     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11318       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11319       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11320                               Ident->getName().equals(CorrectedStr);
11321       S.diagnoseTypo(Corrected,
11322                      S.PDiag(diag::err_using_directive_member_suggest)
11323                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11324                      S.PDiag(diag::note_namespace_defined_here));
11325     } else {
11326       S.diagnoseTypo(Corrected,
11327                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11328                      S.PDiag(diag::note_namespace_defined_here));
11329     }
11330     R.addDecl(Corrected.getFoundDecl());
11331     return true;
11332   }
11333   return false;
11334 }
11335 
11336 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11337                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11338                                 SourceLocation IdentLoc,
11339                                 IdentifierInfo *NamespcName,
11340                                 const ParsedAttributesView &AttrList) {
11341   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11342   assert(NamespcName && "Invalid NamespcName.");
11343   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11344 
11345   // This can only happen along a recovery path.
11346   while (S->isTemplateParamScope())
11347     S = S->getParent();
11348   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11349 
11350   UsingDirectiveDecl *UDir = nullptr;
11351   NestedNameSpecifier *Qualifier = nullptr;
11352   if (SS.isSet())
11353     Qualifier = SS.getScopeRep();
11354 
11355   // Lookup namespace name.
11356   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11357   LookupParsedName(R, S, &SS);
11358   if (R.isAmbiguous())
11359     return nullptr;
11360 
11361   if (R.empty()) {
11362     R.clear();
11363     // Allow "using namespace std;" or "using namespace ::std;" even if
11364     // "std" hasn't been defined yet, for GCC compatibility.
11365     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11366         NamespcName->isStr("std")) {
11367       Diag(IdentLoc, diag::ext_using_undefined_std);
11368       R.addDecl(getOrCreateStdNamespace());
11369       R.resolveKind();
11370     }
11371     // Otherwise, attempt typo correction.
11372     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11373   }
11374 
11375   if (!R.empty()) {
11376     NamedDecl *Named = R.getRepresentativeDecl();
11377     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11378     assert(NS && "expected namespace decl");
11379 
11380     // The use of a nested name specifier may trigger deprecation warnings.
11381     DiagnoseUseOfDecl(Named, IdentLoc);
11382 
11383     // C++ [namespace.udir]p1:
11384     //   A using-directive specifies that the names in the nominated
11385     //   namespace can be used in the scope in which the
11386     //   using-directive appears after the using-directive. During
11387     //   unqualified name lookup (3.4.1), the names appear as if they
11388     //   were declared in the nearest enclosing namespace which
11389     //   contains both the using-directive and the nominated
11390     //   namespace. [Note: in this context, "contains" means "contains
11391     //   directly or indirectly". ]
11392 
11393     // Find enclosing context containing both using-directive and
11394     // nominated namespace.
11395     DeclContext *CommonAncestor = NS;
11396     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11397       CommonAncestor = CommonAncestor->getParent();
11398 
11399     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11400                                       SS.getWithLocInContext(Context),
11401                                       IdentLoc, Named, CommonAncestor);
11402 
11403     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11404         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11405       Diag(IdentLoc, diag::warn_using_directive_in_header);
11406     }
11407 
11408     PushUsingDirective(S, UDir);
11409   } else {
11410     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11411   }
11412 
11413   if (UDir)
11414     ProcessDeclAttributeList(S, UDir, AttrList);
11415 
11416   return UDir;
11417 }
11418 
11419 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11420   // If the scope has an associated entity and the using directive is at
11421   // namespace or translation unit scope, add the UsingDirectiveDecl into
11422   // its lookup structure so qualified name lookup can find it.
11423   DeclContext *Ctx = S->getEntity();
11424   if (Ctx && !Ctx->isFunctionOrMethod())
11425     Ctx->addDecl(UDir);
11426   else
11427     // Otherwise, it is at block scope. The using-directives will affect lookup
11428     // only to the end of the scope.
11429     S->PushUsingDirective(UDir);
11430 }
11431 
11432 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11433                                   SourceLocation UsingLoc,
11434                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11435                                   UnqualifiedId &Name,
11436                                   SourceLocation EllipsisLoc,
11437                                   const ParsedAttributesView &AttrList) {
11438   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11439 
11440   if (SS.isEmpty()) {
11441     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11442     return nullptr;
11443   }
11444 
11445   switch (Name.getKind()) {
11446   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11447   case UnqualifiedIdKind::IK_Identifier:
11448   case UnqualifiedIdKind::IK_OperatorFunctionId:
11449   case UnqualifiedIdKind::IK_LiteralOperatorId:
11450   case UnqualifiedIdKind::IK_ConversionFunctionId:
11451     break;
11452 
11453   case UnqualifiedIdKind::IK_ConstructorName:
11454   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11455     // C++11 inheriting constructors.
11456     Diag(Name.getBeginLoc(),
11457          getLangOpts().CPlusPlus11
11458              ? diag::warn_cxx98_compat_using_decl_constructor
11459              : diag::err_using_decl_constructor)
11460         << SS.getRange();
11461 
11462     if (getLangOpts().CPlusPlus11) break;
11463 
11464     return nullptr;
11465 
11466   case UnqualifiedIdKind::IK_DestructorName:
11467     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11468     return nullptr;
11469 
11470   case UnqualifiedIdKind::IK_TemplateId:
11471     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11472         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11473     return nullptr;
11474 
11475   case UnqualifiedIdKind::IK_DeductionGuideName:
11476     llvm_unreachable("cannot parse qualified deduction guide name");
11477   }
11478 
11479   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11480   DeclarationName TargetName = TargetNameInfo.getName();
11481   if (!TargetName)
11482     return nullptr;
11483 
11484   // Warn about access declarations.
11485   if (UsingLoc.isInvalid()) {
11486     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11487                                  ? diag::err_access_decl
11488                                  : diag::warn_access_decl_deprecated)
11489         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11490   }
11491 
11492   if (EllipsisLoc.isInvalid()) {
11493     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11494         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11495       return nullptr;
11496   } else {
11497     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11498         !TargetNameInfo.containsUnexpandedParameterPack()) {
11499       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11500         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11501       EllipsisLoc = SourceLocation();
11502     }
11503   }
11504 
11505   NamedDecl *UD =
11506       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11507                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11508                             /*IsInstantiation*/false);
11509   if (UD)
11510     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11511 
11512   return UD;
11513 }
11514 
11515 /// Determine whether a using declaration considers the given
11516 /// declarations as "equivalent", e.g., if they are redeclarations of
11517 /// the same entity or are both typedefs of the same type.
11518 static bool
11519 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11520   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11521     return true;
11522 
11523   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11524     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11525       return Context.hasSameType(TD1->getUnderlyingType(),
11526                                  TD2->getUnderlyingType());
11527 
11528   return false;
11529 }
11530 
11531 
11532 /// Determines whether to create a using shadow decl for a particular
11533 /// decl, given the set of decls existing prior to this using lookup.
11534 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11535                                 const LookupResult &Previous,
11536                                 UsingShadowDecl *&PrevShadow) {
11537   // Diagnose finding a decl which is not from a base class of the
11538   // current class.  We do this now because there are cases where this
11539   // function will silently decide not to build a shadow decl, which
11540   // will pre-empt further diagnostics.
11541   //
11542   // We don't need to do this in C++11 because we do the check once on
11543   // the qualifier.
11544   //
11545   // FIXME: diagnose the following if we care enough:
11546   //   struct A { int foo; };
11547   //   struct B : A { using A::foo; };
11548   //   template <class T> struct C : A {};
11549   //   template <class T> struct D : C<T> { using B::foo; } // <---
11550   // This is invalid (during instantiation) in C++03 because B::foo
11551   // resolves to the using decl in B, which is not a base class of D<T>.
11552   // We can't diagnose it immediately because C<T> is an unknown
11553   // specialization.  The UsingShadowDecl in D<T> then points directly
11554   // to A::foo, which will look well-formed when we instantiate.
11555   // The right solution is to not collapse the shadow-decl chain.
11556   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11557     DeclContext *OrigDC = Orig->getDeclContext();
11558 
11559     // Handle enums and anonymous structs.
11560     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11561     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11562     while (OrigRec->isAnonymousStructOrUnion())
11563       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11564 
11565     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11566       if (OrigDC == CurContext) {
11567         Diag(Using->getLocation(),
11568              diag::err_using_decl_nested_name_specifier_is_current_class)
11569           << Using->getQualifierLoc().getSourceRange();
11570         Diag(Orig->getLocation(), diag::note_using_decl_target);
11571         Using->setInvalidDecl();
11572         return true;
11573       }
11574 
11575       Diag(Using->getQualifierLoc().getBeginLoc(),
11576            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11577         << Using->getQualifier()
11578         << cast<CXXRecordDecl>(CurContext)
11579         << Using->getQualifierLoc().getSourceRange();
11580       Diag(Orig->getLocation(), diag::note_using_decl_target);
11581       Using->setInvalidDecl();
11582       return true;
11583     }
11584   }
11585 
11586   if (Previous.empty()) return false;
11587 
11588   NamedDecl *Target = Orig;
11589   if (isa<UsingShadowDecl>(Target))
11590     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11591 
11592   // If the target happens to be one of the previous declarations, we
11593   // don't have a conflict.
11594   //
11595   // FIXME: but we might be increasing its access, in which case we
11596   // should redeclare it.
11597   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11598   bool FoundEquivalentDecl = false;
11599   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11600          I != E; ++I) {
11601     NamedDecl *D = (*I)->getUnderlyingDecl();
11602     // We can have UsingDecls in our Previous results because we use the same
11603     // LookupResult for checking whether the UsingDecl itself is a valid
11604     // redeclaration.
11605     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11606       continue;
11607 
11608     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11609       // C++ [class.mem]p19:
11610       //   If T is the name of a class, then [every named member other than
11611       //   a non-static data member] shall have a name different from T
11612       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11613           !isa<IndirectFieldDecl>(Target) &&
11614           !isa<UnresolvedUsingValueDecl>(Target) &&
11615           DiagnoseClassNameShadow(
11616               CurContext,
11617               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11618         return true;
11619     }
11620 
11621     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11622       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11623         PrevShadow = Shadow;
11624       FoundEquivalentDecl = true;
11625     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11626       // We don't conflict with an existing using shadow decl of an equivalent
11627       // declaration, but we're not a redeclaration of it.
11628       FoundEquivalentDecl = true;
11629     }
11630 
11631     if (isVisible(D))
11632       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11633   }
11634 
11635   if (FoundEquivalentDecl)
11636     return false;
11637 
11638   if (FunctionDecl *FD = Target->getAsFunction()) {
11639     NamedDecl *OldDecl = nullptr;
11640     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11641                           /*IsForUsingDecl*/ true)) {
11642     case Ovl_Overload:
11643       return false;
11644 
11645     case Ovl_NonFunction:
11646       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11647       break;
11648 
11649     // We found a decl with the exact signature.
11650     case Ovl_Match:
11651       // If we're in a record, we want to hide the target, so we
11652       // return true (without a diagnostic) to tell the caller not to
11653       // build a shadow decl.
11654       if (CurContext->isRecord())
11655         return true;
11656 
11657       // If we're not in a record, this is an error.
11658       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11659       break;
11660     }
11661 
11662     Diag(Target->getLocation(), diag::note_using_decl_target);
11663     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11664     Using->setInvalidDecl();
11665     return true;
11666   }
11667 
11668   // Target is not a function.
11669 
11670   if (isa<TagDecl>(Target)) {
11671     // No conflict between a tag and a non-tag.
11672     if (!Tag) return false;
11673 
11674     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11675     Diag(Target->getLocation(), diag::note_using_decl_target);
11676     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11677     Using->setInvalidDecl();
11678     return true;
11679   }
11680 
11681   // No conflict between a tag and a non-tag.
11682   if (!NonTag) return false;
11683 
11684   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11685   Diag(Target->getLocation(), diag::note_using_decl_target);
11686   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11687   Using->setInvalidDecl();
11688   return true;
11689 }
11690 
11691 /// Determine whether a direct base class is a virtual base class.
11692 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11693   if (!Derived->getNumVBases())
11694     return false;
11695   for (auto &B : Derived->bases())
11696     if (B.getType()->getAsCXXRecordDecl() == Base)
11697       return B.isVirtual();
11698   llvm_unreachable("not a direct base class");
11699 }
11700 
11701 /// Builds a shadow declaration corresponding to a 'using' declaration.
11702 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11703                                             UsingDecl *UD,
11704                                             NamedDecl *Orig,
11705                                             UsingShadowDecl *PrevDecl) {
11706   // If we resolved to another shadow declaration, just coalesce them.
11707   NamedDecl *Target = Orig;
11708   if (isa<UsingShadowDecl>(Target)) {
11709     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11710     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11711   }
11712 
11713   NamedDecl *NonTemplateTarget = Target;
11714   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11715     NonTemplateTarget = TargetTD->getTemplatedDecl();
11716 
11717   UsingShadowDecl *Shadow;
11718   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11719     bool IsVirtualBase =
11720         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11721                             UD->getQualifier()->getAsRecordDecl());
11722     Shadow = ConstructorUsingShadowDecl::Create(
11723         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11724   } else {
11725     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11726                                      Target);
11727   }
11728   UD->addShadowDecl(Shadow);
11729 
11730   Shadow->setAccess(UD->getAccess());
11731   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11732     Shadow->setInvalidDecl();
11733 
11734   Shadow->setPreviousDecl(PrevDecl);
11735 
11736   if (S)
11737     PushOnScopeChains(Shadow, S);
11738   else
11739     CurContext->addDecl(Shadow);
11740 
11741 
11742   return Shadow;
11743 }
11744 
11745 /// Hides a using shadow declaration.  This is required by the current
11746 /// using-decl implementation when a resolvable using declaration in a
11747 /// class is followed by a declaration which would hide or override
11748 /// one or more of the using decl's targets; for example:
11749 ///
11750 ///   struct Base { void foo(int); };
11751 ///   struct Derived : Base {
11752 ///     using Base::foo;
11753 ///     void foo(int);
11754 ///   };
11755 ///
11756 /// The governing language is C++03 [namespace.udecl]p12:
11757 ///
11758 ///   When a using-declaration brings names from a base class into a
11759 ///   derived class scope, member functions in the derived class
11760 ///   override and/or hide member functions with the same name and
11761 ///   parameter types in a base class (rather than conflicting).
11762 ///
11763 /// There are two ways to implement this:
11764 ///   (1) optimistically create shadow decls when they're not hidden
11765 ///       by existing declarations, or
11766 ///   (2) don't create any shadow decls (or at least don't make them
11767 ///       visible) until we've fully parsed/instantiated the class.
11768 /// The problem with (1) is that we might have to retroactively remove
11769 /// a shadow decl, which requires several O(n) operations because the
11770 /// decl structures are (very reasonably) not designed for removal.
11771 /// (2) avoids this but is very fiddly and phase-dependent.
11772 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11773   if (Shadow->getDeclName().getNameKind() ==
11774         DeclarationName::CXXConversionFunctionName)
11775     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11776 
11777   // Remove it from the DeclContext...
11778   Shadow->getDeclContext()->removeDecl(Shadow);
11779 
11780   // ...and the scope, if applicable...
11781   if (S) {
11782     S->RemoveDecl(Shadow);
11783     IdResolver.RemoveDecl(Shadow);
11784   }
11785 
11786   // ...and the using decl.
11787   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11788 
11789   // TODO: complain somehow if Shadow was used.  It shouldn't
11790   // be possible for this to happen, because...?
11791 }
11792 
11793 /// Find the base specifier for a base class with the given type.
11794 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11795                                                 QualType DesiredBase,
11796                                                 bool &AnyDependentBases) {
11797   // Check whether the named type is a direct base class.
11798   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11799     .getUnqualifiedType();
11800   for (auto &Base : Derived->bases()) {
11801     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11802     if (CanonicalDesiredBase == BaseType)
11803       return &Base;
11804     if (BaseType->isDependentType())
11805       AnyDependentBases = true;
11806   }
11807   return nullptr;
11808 }
11809 
11810 namespace {
11811 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11812 public:
11813   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11814                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11815       : HasTypenameKeyword(HasTypenameKeyword),
11816         IsInstantiation(IsInstantiation), OldNNS(NNS),
11817         RequireMemberOf(RequireMemberOf) {}
11818 
11819   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11820     NamedDecl *ND = Candidate.getCorrectionDecl();
11821 
11822     // Keywords are not valid here.
11823     if (!ND || isa<NamespaceDecl>(ND))
11824       return false;
11825 
11826     // Completely unqualified names are invalid for a 'using' declaration.
11827     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11828       return false;
11829 
11830     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11831     // reject.
11832 
11833     if (RequireMemberOf) {
11834       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11835       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11836         // No-one ever wants a using-declaration to name an injected-class-name
11837         // of a base class, unless they're declaring an inheriting constructor.
11838         ASTContext &Ctx = ND->getASTContext();
11839         if (!Ctx.getLangOpts().CPlusPlus11)
11840           return false;
11841         QualType FoundType = Ctx.getRecordType(FoundRecord);
11842 
11843         // Check that the injected-class-name is named as a member of its own
11844         // type; we don't want to suggest 'using Derived::Base;', since that
11845         // means something else.
11846         NestedNameSpecifier *Specifier =
11847             Candidate.WillReplaceSpecifier()
11848                 ? Candidate.getCorrectionSpecifier()
11849                 : OldNNS;
11850         if (!Specifier->getAsType() ||
11851             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11852           return false;
11853 
11854         // Check that this inheriting constructor declaration actually names a
11855         // direct base class of the current class.
11856         bool AnyDependentBases = false;
11857         if (!findDirectBaseWithType(RequireMemberOf,
11858                                     Ctx.getRecordType(FoundRecord),
11859                                     AnyDependentBases) &&
11860             !AnyDependentBases)
11861           return false;
11862       } else {
11863         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11864         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11865           return false;
11866 
11867         // FIXME: Check that the base class member is accessible?
11868       }
11869     } else {
11870       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11871       if (FoundRecord && FoundRecord->isInjectedClassName())
11872         return false;
11873     }
11874 
11875     if (isa<TypeDecl>(ND))
11876       return HasTypenameKeyword || !IsInstantiation;
11877 
11878     return !HasTypenameKeyword;
11879   }
11880 
11881   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11882     return std::make_unique<UsingValidatorCCC>(*this);
11883   }
11884 
11885 private:
11886   bool HasTypenameKeyword;
11887   bool IsInstantiation;
11888   NestedNameSpecifier *OldNNS;
11889   CXXRecordDecl *RequireMemberOf;
11890 };
11891 } // end anonymous namespace
11892 
11893 /// Builds a using declaration.
11894 ///
11895 /// \param IsInstantiation - Whether this call arises from an
11896 ///   instantiation of an unresolved using declaration.  We treat
11897 ///   the lookup differently for these declarations.
11898 NamedDecl *Sema::BuildUsingDeclaration(
11899     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11900     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11901     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11902     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11903   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11904   SourceLocation IdentLoc = NameInfo.getLoc();
11905   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11906 
11907   // FIXME: We ignore attributes for now.
11908 
11909   // For an inheriting constructor declaration, the name of the using
11910   // declaration is the name of a constructor in this class, not in the
11911   // base class.
11912   DeclarationNameInfo UsingName = NameInfo;
11913   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11914     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11915       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11916           Context.getCanonicalType(Context.getRecordType(RD))));
11917 
11918   // Do the redeclaration lookup in the current scope.
11919   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11920                         ForVisibleRedeclaration);
11921   Previous.setHideTags(false);
11922   if (S) {
11923     LookupName(Previous, S);
11924 
11925     // It is really dumb that we have to do this.
11926     LookupResult::Filter F = Previous.makeFilter();
11927     while (F.hasNext()) {
11928       NamedDecl *D = F.next();
11929       if (!isDeclInScope(D, CurContext, S))
11930         F.erase();
11931       // If we found a local extern declaration that's not ordinarily visible,
11932       // and this declaration is being added to a non-block scope, ignore it.
11933       // We're only checking for scope conflicts here, not also for violations
11934       // of the linkage rules.
11935       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11936                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11937         F.erase();
11938     }
11939     F.done();
11940   } else {
11941     assert(IsInstantiation && "no scope in non-instantiation");
11942     if (CurContext->isRecord())
11943       LookupQualifiedName(Previous, CurContext);
11944     else {
11945       // No redeclaration check is needed here; in non-member contexts we
11946       // diagnosed all possible conflicts with other using-declarations when
11947       // building the template:
11948       //
11949       // For a dependent non-type using declaration, the only valid case is
11950       // if we instantiate to a single enumerator. We check for conflicts
11951       // between shadow declarations we introduce, and we check in the template
11952       // definition for conflicts between a non-type using declaration and any
11953       // other declaration, which together covers all cases.
11954       //
11955       // A dependent typename using declaration will never successfully
11956       // instantiate, since it will always name a class member, so we reject
11957       // that in the template definition.
11958     }
11959   }
11960 
11961   // Check for invalid redeclarations.
11962   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11963                                   SS, IdentLoc, Previous))
11964     return nullptr;
11965 
11966   // Check for bad qualifiers.
11967   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11968                               IdentLoc))
11969     return nullptr;
11970 
11971   DeclContext *LookupContext = computeDeclContext(SS);
11972   NamedDecl *D;
11973   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11974   if (!LookupContext || EllipsisLoc.isValid()) {
11975     if (HasTypenameKeyword) {
11976       // FIXME: not all declaration name kinds are legal here
11977       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11978                                               UsingLoc, TypenameLoc,
11979                                               QualifierLoc,
11980                                               IdentLoc, NameInfo.getName(),
11981                                               EllipsisLoc);
11982     } else {
11983       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11984                                            QualifierLoc, NameInfo, EllipsisLoc);
11985     }
11986     D->setAccess(AS);
11987     CurContext->addDecl(D);
11988     return D;
11989   }
11990 
11991   auto Build = [&](bool Invalid) {
11992     UsingDecl *UD =
11993         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11994                           UsingName, HasTypenameKeyword);
11995     UD->setAccess(AS);
11996     CurContext->addDecl(UD);
11997     UD->setInvalidDecl(Invalid);
11998     return UD;
11999   };
12000   auto BuildInvalid = [&]{ return Build(true); };
12001   auto BuildValid = [&]{ return Build(false); };
12002 
12003   if (RequireCompleteDeclContext(SS, LookupContext))
12004     return BuildInvalid();
12005 
12006   // Look up the target name.
12007   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12008 
12009   // Unlike most lookups, we don't always want to hide tag
12010   // declarations: tag names are visible through the using declaration
12011   // even if hidden by ordinary names, *except* in a dependent context
12012   // where it's important for the sanity of two-phase lookup.
12013   if (!IsInstantiation)
12014     R.setHideTags(false);
12015 
12016   // For the purposes of this lookup, we have a base object type
12017   // equal to that of the current context.
12018   if (CurContext->isRecord()) {
12019     R.setBaseObjectType(
12020                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12021   }
12022 
12023   LookupQualifiedName(R, LookupContext);
12024 
12025   // Try to correct typos if possible. If constructor name lookup finds no
12026   // results, that means the named class has no explicit constructors, and we
12027   // suppressed declaring implicit ones (probably because it's dependent or
12028   // invalid).
12029   if (R.empty() &&
12030       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12031     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12032     // it will believe that glibc provides a ::gets in cases where it does not,
12033     // and will try to pull it into namespace std with a using-declaration.
12034     // Just ignore the using-declaration in that case.
12035     auto *II = NameInfo.getName().getAsIdentifierInfo();
12036     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12037         CurContext->isStdNamespace() &&
12038         isa<TranslationUnitDecl>(LookupContext) &&
12039         getSourceManager().isInSystemHeader(UsingLoc))
12040       return nullptr;
12041     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12042                           dyn_cast<CXXRecordDecl>(CurContext));
12043     if (TypoCorrection Corrected =
12044             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12045                         CTK_ErrorRecovery)) {
12046       // We reject candidates where DroppedSpecifier == true, hence the
12047       // literal '0' below.
12048       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12049                                 << NameInfo.getName() << LookupContext << 0
12050                                 << SS.getRange());
12051 
12052       // If we picked a correction with no attached Decl we can't do anything
12053       // useful with it, bail out.
12054       NamedDecl *ND = Corrected.getCorrectionDecl();
12055       if (!ND)
12056         return BuildInvalid();
12057 
12058       // If we corrected to an inheriting constructor, handle it as one.
12059       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12060       if (RD && RD->isInjectedClassName()) {
12061         // The parent of the injected class name is the class itself.
12062         RD = cast<CXXRecordDecl>(RD->getParent());
12063 
12064         // Fix up the information we'll use to build the using declaration.
12065         if (Corrected.WillReplaceSpecifier()) {
12066           NestedNameSpecifierLocBuilder Builder;
12067           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12068                               QualifierLoc.getSourceRange());
12069           QualifierLoc = Builder.getWithLocInContext(Context);
12070         }
12071 
12072         // In this case, the name we introduce is the name of a derived class
12073         // constructor.
12074         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12075         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12076             Context.getCanonicalType(Context.getRecordType(CurClass))));
12077         UsingName.setNamedTypeInfo(nullptr);
12078         for (auto *Ctor : LookupConstructors(RD))
12079           R.addDecl(Ctor);
12080         R.resolveKind();
12081       } else {
12082         // FIXME: Pick up all the declarations if we found an overloaded
12083         // function.
12084         UsingName.setName(ND->getDeclName());
12085         R.addDecl(ND);
12086       }
12087     } else {
12088       Diag(IdentLoc, diag::err_no_member)
12089         << NameInfo.getName() << LookupContext << SS.getRange();
12090       return BuildInvalid();
12091     }
12092   }
12093 
12094   if (R.isAmbiguous())
12095     return BuildInvalid();
12096 
12097   if (HasTypenameKeyword) {
12098     // If we asked for a typename and got a non-type decl, error out.
12099     if (!R.getAsSingle<TypeDecl>()) {
12100       Diag(IdentLoc, diag::err_using_typename_non_type);
12101       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12102         Diag((*I)->getUnderlyingDecl()->getLocation(),
12103              diag::note_using_decl_target);
12104       return BuildInvalid();
12105     }
12106   } else {
12107     // If we asked for a non-typename and we got a type, error out,
12108     // but only if this is an instantiation of an unresolved using
12109     // decl.  Otherwise just silently find the type name.
12110     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12111       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12112       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12113       return BuildInvalid();
12114     }
12115   }
12116 
12117   // C++14 [namespace.udecl]p6:
12118   // A using-declaration shall not name a namespace.
12119   if (R.getAsSingle<NamespaceDecl>()) {
12120     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12121       << SS.getRange();
12122     return BuildInvalid();
12123   }
12124 
12125   // C++14 [namespace.udecl]p7:
12126   // A using-declaration shall not name a scoped enumerator.
12127   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12128     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12129       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12130         << SS.getRange();
12131       return BuildInvalid();
12132     }
12133   }
12134 
12135   UsingDecl *UD = BuildValid();
12136 
12137   // Some additional rules apply to inheriting constructors.
12138   if (UsingName.getName().getNameKind() ==
12139         DeclarationName::CXXConstructorName) {
12140     // Suppress access diagnostics; the access check is instead performed at the
12141     // point of use for an inheriting constructor.
12142     R.suppressDiagnostics();
12143     if (CheckInheritingConstructorUsingDecl(UD))
12144       return UD;
12145   }
12146 
12147   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12148     UsingShadowDecl *PrevDecl = nullptr;
12149     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12150       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12151   }
12152 
12153   return UD;
12154 }
12155 
12156 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12157                                     ArrayRef<NamedDecl *> Expansions) {
12158   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12159          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12160          isa<UsingPackDecl>(InstantiatedFrom));
12161 
12162   auto *UPD =
12163       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12164   UPD->setAccess(InstantiatedFrom->getAccess());
12165   CurContext->addDecl(UPD);
12166   return UPD;
12167 }
12168 
12169 /// Additional checks for a using declaration referring to a constructor name.
12170 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12171   assert(!UD->hasTypename() && "expecting a constructor name");
12172 
12173   const Type *SourceType = UD->getQualifier()->getAsType();
12174   assert(SourceType &&
12175          "Using decl naming constructor doesn't have type in scope spec.");
12176   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12177 
12178   // Check whether the named type is a direct base class.
12179   bool AnyDependentBases = false;
12180   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12181                                       AnyDependentBases);
12182   if (!Base && !AnyDependentBases) {
12183     Diag(UD->getUsingLoc(),
12184          diag::err_using_decl_constructor_not_in_direct_base)
12185       << UD->getNameInfo().getSourceRange()
12186       << QualType(SourceType, 0) << TargetClass;
12187     UD->setInvalidDecl();
12188     return true;
12189   }
12190 
12191   if (Base)
12192     Base->setInheritConstructors();
12193 
12194   return false;
12195 }
12196 
12197 /// Checks that the given using declaration is not an invalid
12198 /// redeclaration.  Note that this is checking only for the using decl
12199 /// itself, not for any ill-formedness among the UsingShadowDecls.
12200 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12201                                        bool HasTypenameKeyword,
12202                                        const CXXScopeSpec &SS,
12203                                        SourceLocation NameLoc,
12204                                        const LookupResult &Prev) {
12205   NestedNameSpecifier *Qual = SS.getScopeRep();
12206 
12207   // C++03 [namespace.udecl]p8:
12208   // C++0x [namespace.udecl]p10:
12209   //   A using-declaration is a declaration and can therefore be used
12210   //   repeatedly where (and only where) multiple declarations are
12211   //   allowed.
12212   //
12213   // That's in non-member contexts.
12214   if (!CurContext->getRedeclContext()->isRecord()) {
12215     // A dependent qualifier outside a class can only ever resolve to an
12216     // enumeration type. Therefore it conflicts with any other non-type
12217     // declaration in the same scope.
12218     // FIXME: How should we check for dependent type-type conflicts at block
12219     // scope?
12220     if (Qual->isDependent() && !HasTypenameKeyword) {
12221       for (auto *D : Prev) {
12222         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12223           bool OldCouldBeEnumerator =
12224               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12225           Diag(NameLoc,
12226                OldCouldBeEnumerator ? diag::err_redefinition
12227                                     : diag::err_redefinition_different_kind)
12228               << Prev.getLookupName();
12229           Diag(D->getLocation(), diag::note_previous_definition);
12230           return true;
12231         }
12232       }
12233     }
12234     return false;
12235   }
12236 
12237   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12238     NamedDecl *D = *I;
12239 
12240     bool DTypename;
12241     NestedNameSpecifier *DQual;
12242     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12243       DTypename = UD->hasTypename();
12244       DQual = UD->getQualifier();
12245     } else if (UnresolvedUsingValueDecl *UD
12246                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12247       DTypename = false;
12248       DQual = UD->getQualifier();
12249     } else if (UnresolvedUsingTypenameDecl *UD
12250                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12251       DTypename = true;
12252       DQual = UD->getQualifier();
12253     } else continue;
12254 
12255     // using decls differ if one says 'typename' and the other doesn't.
12256     // FIXME: non-dependent using decls?
12257     if (HasTypenameKeyword != DTypename) continue;
12258 
12259     // using decls differ if they name different scopes (but note that
12260     // template instantiation can cause this check to trigger when it
12261     // didn't before instantiation).
12262     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12263         Context.getCanonicalNestedNameSpecifier(DQual))
12264       continue;
12265 
12266     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12267     Diag(D->getLocation(), diag::note_using_decl) << 1;
12268     return true;
12269   }
12270 
12271   return false;
12272 }
12273 
12274 
12275 /// Checks that the given nested-name qualifier used in a using decl
12276 /// in the current context is appropriately related to the current
12277 /// scope.  If an error is found, diagnoses it and returns true.
12278 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12279                                    bool HasTypename,
12280                                    const CXXScopeSpec &SS,
12281                                    const DeclarationNameInfo &NameInfo,
12282                                    SourceLocation NameLoc) {
12283   DeclContext *NamedContext = computeDeclContext(SS);
12284 
12285   if (!CurContext->isRecord()) {
12286     // C++03 [namespace.udecl]p3:
12287     // C++0x [namespace.udecl]p8:
12288     //   A using-declaration for a class member shall be a member-declaration.
12289 
12290     // If we weren't able to compute a valid scope, it might validly be a
12291     // dependent class scope or a dependent enumeration unscoped scope. If
12292     // we have a 'typename' keyword, the scope must resolve to a class type.
12293     if ((HasTypename && !NamedContext) ||
12294         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12295       auto *RD = NamedContext
12296                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12297                      : nullptr;
12298       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12299         RD = nullptr;
12300 
12301       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12302         << SS.getRange();
12303 
12304       // If we have a complete, non-dependent source type, try to suggest a
12305       // way to get the same effect.
12306       if (!RD)
12307         return true;
12308 
12309       // Find what this using-declaration was referring to.
12310       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12311       R.setHideTags(false);
12312       R.suppressDiagnostics();
12313       LookupQualifiedName(R, RD);
12314 
12315       if (R.getAsSingle<TypeDecl>()) {
12316         if (getLangOpts().CPlusPlus11) {
12317           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12318           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12319             << 0 // alias declaration
12320             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12321                                           NameInfo.getName().getAsString() +
12322                                               " = ");
12323         } else {
12324           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12325           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12326           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12327             << 1 // typedef declaration
12328             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12329             << FixItHint::CreateInsertion(
12330                    InsertLoc, " " + NameInfo.getName().getAsString());
12331         }
12332       } else if (R.getAsSingle<VarDecl>()) {
12333         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12334         // repeating the type of the static data member here.
12335         FixItHint FixIt;
12336         if (getLangOpts().CPlusPlus11) {
12337           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12338           FixIt = FixItHint::CreateReplacement(
12339               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12340         }
12341 
12342         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12343           << 2 // reference declaration
12344           << FixIt;
12345       } else if (R.getAsSingle<EnumConstantDecl>()) {
12346         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12347         // repeating the type of the enumeration here, and we can't do so if
12348         // the type is anonymous.
12349         FixItHint FixIt;
12350         if (getLangOpts().CPlusPlus11) {
12351           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12352           FixIt = FixItHint::CreateReplacement(
12353               UsingLoc,
12354               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12355         }
12356 
12357         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12358           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12359           << FixIt;
12360       }
12361       return true;
12362     }
12363 
12364     // Otherwise, this might be valid.
12365     return false;
12366   }
12367 
12368   // The current scope is a record.
12369 
12370   // If the named context is dependent, we can't decide much.
12371   if (!NamedContext) {
12372     // FIXME: in C++0x, we can diagnose if we can prove that the
12373     // nested-name-specifier does not refer to a base class, which is
12374     // still possible in some cases.
12375 
12376     // Otherwise we have to conservatively report that things might be
12377     // okay.
12378     return false;
12379   }
12380 
12381   if (!NamedContext->isRecord()) {
12382     // Ideally this would point at the last name in the specifier,
12383     // but we don't have that level of source info.
12384     Diag(SS.getRange().getBegin(),
12385          diag::err_using_decl_nested_name_specifier_is_not_class)
12386       << SS.getScopeRep() << SS.getRange();
12387     return true;
12388   }
12389 
12390   if (!NamedContext->isDependentContext() &&
12391       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12392     return true;
12393 
12394   if (getLangOpts().CPlusPlus11) {
12395     // C++11 [namespace.udecl]p3:
12396     //   In a using-declaration used as a member-declaration, the
12397     //   nested-name-specifier shall name a base class of the class
12398     //   being defined.
12399 
12400     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12401                                  cast<CXXRecordDecl>(NamedContext))) {
12402       if (CurContext == NamedContext) {
12403         Diag(NameLoc,
12404              diag::err_using_decl_nested_name_specifier_is_current_class)
12405           << SS.getRange();
12406         return true;
12407       }
12408 
12409       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12410         Diag(SS.getRange().getBegin(),
12411              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12412           << SS.getScopeRep()
12413           << cast<CXXRecordDecl>(CurContext)
12414           << SS.getRange();
12415       }
12416       return true;
12417     }
12418 
12419     return false;
12420   }
12421 
12422   // C++03 [namespace.udecl]p4:
12423   //   A using-declaration used as a member-declaration shall refer
12424   //   to a member of a base class of the class being defined [etc.].
12425 
12426   // Salient point: SS doesn't have to name a base class as long as
12427   // lookup only finds members from base classes.  Therefore we can
12428   // diagnose here only if we can prove that that can't happen,
12429   // i.e. if the class hierarchies provably don't intersect.
12430 
12431   // TODO: it would be nice if "definitely valid" results were cached
12432   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12433   // need to be repeated.
12434 
12435   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12436   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12437     Bases.insert(Base);
12438     return true;
12439   };
12440 
12441   // Collect all bases. Return false if we find a dependent base.
12442   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12443     return false;
12444 
12445   // Returns true if the base is dependent or is one of the accumulated base
12446   // classes.
12447   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12448     return !Bases.count(Base);
12449   };
12450 
12451   // Return false if the class has a dependent base or if it or one
12452   // of its bases is present in the base set of the current context.
12453   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12454       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12455     return false;
12456 
12457   Diag(SS.getRange().getBegin(),
12458        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12459     << SS.getScopeRep()
12460     << cast<CXXRecordDecl>(CurContext)
12461     << SS.getRange();
12462 
12463   return true;
12464 }
12465 
12466 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12467                                   MultiTemplateParamsArg TemplateParamLists,
12468                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12469                                   const ParsedAttributesView &AttrList,
12470                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12471   // Skip up to the relevant declaration scope.
12472   while (S->isTemplateParamScope())
12473     S = S->getParent();
12474   assert((S->getFlags() & Scope::DeclScope) &&
12475          "got alias-declaration outside of declaration scope");
12476 
12477   if (Type.isInvalid())
12478     return nullptr;
12479 
12480   bool Invalid = false;
12481   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12482   TypeSourceInfo *TInfo = nullptr;
12483   GetTypeFromParser(Type.get(), &TInfo);
12484 
12485   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12486     return nullptr;
12487 
12488   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12489                                       UPPC_DeclarationType)) {
12490     Invalid = true;
12491     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12492                                              TInfo->getTypeLoc().getBeginLoc());
12493   }
12494 
12495   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12496                         TemplateParamLists.size()
12497                             ? forRedeclarationInCurContext()
12498                             : ForVisibleRedeclaration);
12499   LookupName(Previous, S);
12500 
12501   // Warn about shadowing the name of a template parameter.
12502   if (Previous.isSingleResult() &&
12503       Previous.getFoundDecl()->isTemplateParameter()) {
12504     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12505     Previous.clear();
12506   }
12507 
12508   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12509          "name in alias declaration must be an identifier");
12510   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12511                                                Name.StartLocation,
12512                                                Name.Identifier, TInfo);
12513 
12514   NewTD->setAccess(AS);
12515 
12516   if (Invalid)
12517     NewTD->setInvalidDecl();
12518 
12519   ProcessDeclAttributeList(S, NewTD, AttrList);
12520   AddPragmaAttributes(S, NewTD);
12521 
12522   CheckTypedefForVariablyModifiedType(S, NewTD);
12523   Invalid |= NewTD->isInvalidDecl();
12524 
12525   bool Redeclaration = false;
12526 
12527   NamedDecl *NewND;
12528   if (TemplateParamLists.size()) {
12529     TypeAliasTemplateDecl *OldDecl = nullptr;
12530     TemplateParameterList *OldTemplateParams = nullptr;
12531 
12532     if (TemplateParamLists.size() != 1) {
12533       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12534         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12535          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12536     }
12537     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12538 
12539     // Check that we can declare a template here.
12540     if (CheckTemplateDeclScope(S, TemplateParams))
12541       return nullptr;
12542 
12543     // Only consider previous declarations in the same scope.
12544     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12545                          /*ExplicitInstantiationOrSpecialization*/false);
12546     if (!Previous.empty()) {
12547       Redeclaration = true;
12548 
12549       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12550       if (!OldDecl && !Invalid) {
12551         Diag(UsingLoc, diag::err_redefinition_different_kind)
12552           << Name.Identifier;
12553 
12554         NamedDecl *OldD = Previous.getRepresentativeDecl();
12555         if (OldD->getLocation().isValid())
12556           Diag(OldD->getLocation(), diag::note_previous_definition);
12557 
12558         Invalid = true;
12559       }
12560 
12561       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12562         if (TemplateParameterListsAreEqual(TemplateParams,
12563                                            OldDecl->getTemplateParameters(),
12564                                            /*Complain=*/true,
12565                                            TPL_TemplateMatch))
12566           OldTemplateParams =
12567               OldDecl->getMostRecentDecl()->getTemplateParameters();
12568         else
12569           Invalid = true;
12570 
12571         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12572         if (!Invalid &&
12573             !Context.hasSameType(OldTD->getUnderlyingType(),
12574                                  NewTD->getUnderlyingType())) {
12575           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12576           // but we can't reasonably accept it.
12577           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12578             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12579           if (OldTD->getLocation().isValid())
12580             Diag(OldTD->getLocation(), diag::note_previous_definition);
12581           Invalid = true;
12582         }
12583       }
12584     }
12585 
12586     // Merge any previous default template arguments into our parameters,
12587     // and check the parameter list.
12588     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12589                                    TPC_TypeAliasTemplate))
12590       return nullptr;
12591 
12592     TypeAliasTemplateDecl *NewDecl =
12593       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12594                                     Name.Identifier, TemplateParams,
12595                                     NewTD);
12596     NewTD->setDescribedAliasTemplate(NewDecl);
12597 
12598     NewDecl->setAccess(AS);
12599 
12600     if (Invalid)
12601       NewDecl->setInvalidDecl();
12602     else if (OldDecl) {
12603       NewDecl->setPreviousDecl(OldDecl);
12604       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12605     }
12606 
12607     NewND = NewDecl;
12608   } else {
12609     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12610       setTagNameForLinkagePurposes(TD, NewTD);
12611       handleTagNumbering(TD, S);
12612     }
12613     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12614     NewND = NewTD;
12615   }
12616 
12617   PushOnScopeChains(NewND, S);
12618   ActOnDocumentableDecl(NewND);
12619   return NewND;
12620 }
12621 
12622 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12623                                    SourceLocation AliasLoc,
12624                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12625                                    SourceLocation IdentLoc,
12626                                    IdentifierInfo *Ident) {
12627 
12628   // Lookup the namespace name.
12629   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12630   LookupParsedName(R, S, &SS);
12631 
12632   if (R.isAmbiguous())
12633     return nullptr;
12634 
12635   if (R.empty()) {
12636     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12637       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12638       return nullptr;
12639     }
12640   }
12641   assert(!R.isAmbiguous() && !R.empty());
12642   NamedDecl *ND = R.getRepresentativeDecl();
12643 
12644   // Check if we have a previous declaration with the same name.
12645   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12646                      ForVisibleRedeclaration);
12647   LookupName(PrevR, S);
12648 
12649   // Check we're not shadowing a template parameter.
12650   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12651     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12652     PrevR.clear();
12653   }
12654 
12655   // Filter out any other lookup result from an enclosing scope.
12656   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12657                        /*AllowInlineNamespace*/false);
12658 
12659   // Find the previous declaration and check that we can redeclare it.
12660   NamespaceAliasDecl *Prev = nullptr;
12661   if (PrevR.isSingleResult()) {
12662     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12663     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12664       // We already have an alias with the same name that points to the same
12665       // namespace; check that it matches.
12666       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12667         Prev = AD;
12668       } else if (isVisible(PrevDecl)) {
12669         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12670           << Alias;
12671         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12672           << AD->getNamespace();
12673         return nullptr;
12674       }
12675     } else if (isVisible(PrevDecl)) {
12676       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12677                             ? diag::err_redefinition
12678                             : diag::err_redefinition_different_kind;
12679       Diag(AliasLoc, DiagID) << Alias;
12680       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12681       return nullptr;
12682     }
12683   }
12684 
12685   // The use of a nested name specifier may trigger deprecation warnings.
12686   DiagnoseUseOfDecl(ND, IdentLoc);
12687 
12688   NamespaceAliasDecl *AliasDecl =
12689     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12690                                Alias, SS.getWithLocInContext(Context),
12691                                IdentLoc, ND);
12692   if (Prev)
12693     AliasDecl->setPreviousDecl(Prev);
12694 
12695   PushOnScopeChains(AliasDecl, S);
12696   return AliasDecl;
12697 }
12698 
12699 namespace {
12700 struct SpecialMemberExceptionSpecInfo
12701     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12702   SourceLocation Loc;
12703   Sema::ImplicitExceptionSpecification ExceptSpec;
12704 
12705   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12706                                  Sema::CXXSpecialMember CSM,
12707                                  Sema::InheritedConstructorInfo *ICI,
12708                                  SourceLocation Loc)
12709       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12710 
12711   bool visitBase(CXXBaseSpecifier *Base);
12712   bool visitField(FieldDecl *FD);
12713 
12714   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12715                            unsigned Quals);
12716 
12717   void visitSubobjectCall(Subobject Subobj,
12718                           Sema::SpecialMemberOverloadResult SMOR);
12719 };
12720 }
12721 
12722 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12723   auto *RT = Base->getType()->getAs<RecordType>();
12724   if (!RT)
12725     return false;
12726 
12727   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12728   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12729   if (auto *BaseCtor = SMOR.getMethod()) {
12730     visitSubobjectCall(Base, BaseCtor);
12731     return false;
12732   }
12733 
12734   visitClassSubobject(BaseClass, Base, 0);
12735   return false;
12736 }
12737 
12738 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12739   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12740     Expr *E = FD->getInClassInitializer();
12741     if (!E)
12742       // FIXME: It's a little wasteful to build and throw away a
12743       // CXXDefaultInitExpr here.
12744       // FIXME: We should have a single context note pointing at Loc, and
12745       // this location should be MD->getLocation() instead, since that's
12746       // the location where we actually use the default init expression.
12747       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12748     if (E)
12749       ExceptSpec.CalledExpr(E);
12750   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12751                             ->getAs<RecordType>()) {
12752     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12753                         FD->getType().getCVRQualifiers());
12754   }
12755   return false;
12756 }
12757 
12758 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12759                                                          Subobject Subobj,
12760                                                          unsigned Quals) {
12761   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12762   bool IsMutable = Field && Field->isMutable();
12763   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12764 }
12765 
12766 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12767     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12768   // Note, if lookup fails, it doesn't matter what exception specification we
12769   // choose because the special member will be deleted.
12770   if (CXXMethodDecl *MD = SMOR.getMethod())
12771     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12772 }
12773 
12774 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12775   llvm::APSInt Result;
12776   ExprResult Converted = CheckConvertedConstantExpression(
12777       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12778   ExplicitSpec.setExpr(Converted.get());
12779   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12780     ExplicitSpec.setKind(Result.getBoolValue()
12781                              ? ExplicitSpecKind::ResolvedTrue
12782                              : ExplicitSpecKind::ResolvedFalse);
12783     return true;
12784   }
12785   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12786   return false;
12787 }
12788 
12789 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12790   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12791   if (!ExplicitExpr->isTypeDependent())
12792     tryResolveExplicitSpecifier(ES);
12793   return ES;
12794 }
12795 
12796 static Sema::ImplicitExceptionSpecification
12797 ComputeDefaultedSpecialMemberExceptionSpec(
12798     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12799     Sema::InheritedConstructorInfo *ICI) {
12800   ComputingExceptionSpec CES(S, MD, Loc);
12801 
12802   CXXRecordDecl *ClassDecl = MD->getParent();
12803 
12804   // C++ [except.spec]p14:
12805   //   An implicitly declared special member function (Clause 12) shall have an
12806   //   exception-specification. [...]
12807   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12808   if (ClassDecl->isInvalidDecl())
12809     return Info.ExceptSpec;
12810 
12811   // FIXME: If this diagnostic fires, we're probably missing a check for
12812   // attempting to resolve an exception specification before it's known
12813   // at a higher level.
12814   if (S.RequireCompleteType(MD->getLocation(),
12815                             S.Context.getRecordType(ClassDecl),
12816                             diag::err_exception_spec_incomplete_type))
12817     return Info.ExceptSpec;
12818 
12819   // C++1z [except.spec]p7:
12820   //   [Look for exceptions thrown by] a constructor selected [...] to
12821   //   initialize a potentially constructed subobject,
12822   // C++1z [except.spec]p8:
12823   //   The exception specification for an implicitly-declared destructor, or a
12824   //   destructor without a noexcept-specifier, is potentially-throwing if and
12825   //   only if any of the destructors for any of its potentially constructed
12826   //   subojects is potentially throwing.
12827   // FIXME: We respect the first rule but ignore the "potentially constructed"
12828   // in the second rule to resolve a core issue (no number yet) that would have
12829   // us reject:
12830   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12831   //   struct B : A {};
12832   //   struct C : B { void f(); };
12833   // ... due to giving B::~B() a non-throwing exception specification.
12834   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12835                                 : Info.VisitAllBases);
12836 
12837   return Info.ExceptSpec;
12838 }
12839 
12840 namespace {
12841 /// RAII object to register a special member as being currently declared.
12842 struct DeclaringSpecialMember {
12843   Sema &S;
12844   Sema::SpecialMemberDecl D;
12845   Sema::ContextRAII SavedContext;
12846   bool WasAlreadyBeingDeclared;
12847 
12848   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12849       : S(S), D(RD, CSM), SavedContext(S, RD) {
12850     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12851     if (WasAlreadyBeingDeclared)
12852       // This almost never happens, but if it does, ensure that our cache
12853       // doesn't contain a stale result.
12854       S.SpecialMemberCache.clear();
12855     else {
12856       // Register a note to be produced if we encounter an error while
12857       // declaring the special member.
12858       Sema::CodeSynthesisContext Ctx;
12859       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12860       // FIXME: We don't have a location to use here. Using the class's
12861       // location maintains the fiction that we declare all special members
12862       // with the class, but (1) it's not clear that lying about that helps our
12863       // users understand what's going on, and (2) there may be outer contexts
12864       // on the stack (some of which are relevant) and printing them exposes
12865       // our lies.
12866       Ctx.PointOfInstantiation = RD->getLocation();
12867       Ctx.Entity = RD;
12868       Ctx.SpecialMember = CSM;
12869       S.pushCodeSynthesisContext(Ctx);
12870     }
12871   }
12872   ~DeclaringSpecialMember() {
12873     if (!WasAlreadyBeingDeclared) {
12874       S.SpecialMembersBeingDeclared.erase(D);
12875       S.popCodeSynthesisContext();
12876     }
12877   }
12878 
12879   /// Are we already trying to declare this special member?
12880   bool isAlreadyBeingDeclared() const {
12881     return WasAlreadyBeingDeclared;
12882   }
12883 };
12884 }
12885 
12886 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12887   // Look up any existing declarations, but don't trigger declaration of all
12888   // implicit special members with this name.
12889   DeclarationName Name = FD->getDeclName();
12890   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12891                  ForExternalRedeclaration);
12892   for (auto *D : FD->getParent()->lookup(Name))
12893     if (auto *Acceptable = R.getAcceptableDecl(D))
12894       R.addDecl(Acceptable);
12895   R.resolveKind();
12896   R.suppressDiagnostics();
12897 
12898   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12899 }
12900 
12901 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12902                                           QualType ResultTy,
12903                                           ArrayRef<QualType> Args) {
12904   // Build an exception specification pointing back at this constructor.
12905   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12906 
12907   LangAS AS = getDefaultCXXMethodAddrSpace();
12908   if (AS != LangAS::Default) {
12909     EPI.TypeQuals.addAddressSpace(AS);
12910   }
12911 
12912   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12913   SpecialMem->setType(QT);
12914 }
12915 
12916 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12917                                                      CXXRecordDecl *ClassDecl) {
12918   // C++ [class.ctor]p5:
12919   //   A default constructor for a class X is a constructor of class X
12920   //   that can be called without an argument. If there is no
12921   //   user-declared constructor for class X, a default constructor is
12922   //   implicitly declared. An implicitly-declared default constructor
12923   //   is an inline public member of its class.
12924   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12925          "Should not build implicit default constructor!");
12926 
12927   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12928   if (DSM.isAlreadyBeingDeclared())
12929     return nullptr;
12930 
12931   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12932                                                      CXXDefaultConstructor,
12933                                                      false);
12934 
12935   // Create the actual constructor declaration.
12936   CanQualType ClassType
12937     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12938   SourceLocation ClassLoc = ClassDecl->getLocation();
12939   DeclarationName Name
12940     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12941   DeclarationNameInfo NameInfo(Name, ClassLoc);
12942   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12943       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12944       /*TInfo=*/nullptr, ExplicitSpecifier(),
12945       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12946       Constexpr ? CSK_constexpr : CSK_unspecified);
12947   DefaultCon->setAccess(AS_public);
12948   DefaultCon->setDefaulted();
12949 
12950   if (getLangOpts().CUDA) {
12951     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12952                                             DefaultCon,
12953                                             /* ConstRHS */ false,
12954                                             /* Diagnose */ false);
12955   }
12956 
12957   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12958 
12959   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12960   // constructors is easy to compute.
12961   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12962 
12963   // Note that we have declared this constructor.
12964   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12965 
12966   Scope *S = getScopeForContext(ClassDecl);
12967   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12968 
12969   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12970     SetDeclDeleted(DefaultCon, ClassLoc);
12971 
12972   if (S)
12973     PushOnScopeChains(DefaultCon, S, false);
12974   ClassDecl->addDecl(DefaultCon);
12975 
12976   return DefaultCon;
12977 }
12978 
12979 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12980                                             CXXConstructorDecl *Constructor) {
12981   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12982           !Constructor->doesThisDeclarationHaveABody() &&
12983           !Constructor->isDeleted()) &&
12984     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12985   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12986     return;
12987 
12988   CXXRecordDecl *ClassDecl = Constructor->getParent();
12989   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12990 
12991   SynthesizedFunctionScope Scope(*this, Constructor);
12992 
12993   // The exception specification is needed because we are defining the
12994   // function.
12995   ResolveExceptionSpec(CurrentLocation,
12996                        Constructor->getType()->castAs<FunctionProtoType>());
12997   MarkVTableUsed(CurrentLocation, ClassDecl);
12998 
12999   // Add a context note for diagnostics produced after this point.
13000   Scope.addContextNote(CurrentLocation);
13001 
13002   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13003     Constructor->setInvalidDecl();
13004     return;
13005   }
13006 
13007   SourceLocation Loc = Constructor->getEndLoc().isValid()
13008                            ? Constructor->getEndLoc()
13009                            : Constructor->getLocation();
13010   Constructor->setBody(new (Context) CompoundStmt(Loc));
13011   Constructor->markUsed(Context);
13012 
13013   if (ASTMutationListener *L = getASTMutationListener()) {
13014     L->CompletedImplicitDefinition(Constructor);
13015   }
13016 
13017   DiagnoseUninitializedFields(*this, Constructor);
13018 }
13019 
13020 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13021   // Perform any delayed checks on exception specifications.
13022   CheckDelayedMemberExceptionSpecs();
13023 }
13024 
13025 /// Find or create the fake constructor we synthesize to model constructing an
13026 /// object of a derived class via a constructor of a base class.
13027 CXXConstructorDecl *
13028 Sema::findInheritingConstructor(SourceLocation Loc,
13029                                 CXXConstructorDecl *BaseCtor,
13030                                 ConstructorUsingShadowDecl *Shadow) {
13031   CXXRecordDecl *Derived = Shadow->getParent();
13032   SourceLocation UsingLoc = Shadow->getLocation();
13033 
13034   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13035   // For now we use the name of the base class constructor as a member of the
13036   // derived class to indicate a (fake) inherited constructor name.
13037   DeclarationName Name = BaseCtor->getDeclName();
13038 
13039   // Check to see if we already have a fake constructor for this inherited
13040   // constructor call.
13041   for (NamedDecl *Ctor : Derived->lookup(Name))
13042     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13043                                ->getInheritedConstructor()
13044                                .getConstructor(),
13045                            BaseCtor))
13046       return cast<CXXConstructorDecl>(Ctor);
13047 
13048   DeclarationNameInfo NameInfo(Name, UsingLoc);
13049   TypeSourceInfo *TInfo =
13050       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13051   FunctionProtoTypeLoc ProtoLoc =
13052       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13053 
13054   // Check the inherited constructor is valid and find the list of base classes
13055   // from which it was inherited.
13056   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13057 
13058   bool Constexpr =
13059       BaseCtor->isConstexpr() &&
13060       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13061                                         false, BaseCtor, &ICI);
13062 
13063   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13064       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13065       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13066       /*isImplicitlyDeclared=*/true,
13067       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13068       InheritedConstructor(Shadow, BaseCtor),
13069       BaseCtor->getTrailingRequiresClause());
13070   if (Shadow->isInvalidDecl())
13071     DerivedCtor->setInvalidDecl();
13072 
13073   // Build an unevaluated exception specification for this fake constructor.
13074   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13075   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13076   EPI.ExceptionSpec.Type = EST_Unevaluated;
13077   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13078   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13079                                                FPT->getParamTypes(), EPI));
13080 
13081   // Build the parameter declarations.
13082   SmallVector<ParmVarDecl *, 16> ParamDecls;
13083   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13084     TypeSourceInfo *TInfo =
13085         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13086     ParmVarDecl *PD = ParmVarDecl::Create(
13087         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13088         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13089     PD->setScopeInfo(0, I);
13090     PD->setImplicit();
13091     // Ensure attributes are propagated onto parameters (this matters for
13092     // format, pass_object_size, ...).
13093     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13094     ParamDecls.push_back(PD);
13095     ProtoLoc.setParam(I, PD);
13096   }
13097 
13098   // Set up the new constructor.
13099   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13100   DerivedCtor->setAccess(BaseCtor->getAccess());
13101   DerivedCtor->setParams(ParamDecls);
13102   Derived->addDecl(DerivedCtor);
13103 
13104   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13105     SetDeclDeleted(DerivedCtor, UsingLoc);
13106 
13107   return DerivedCtor;
13108 }
13109 
13110 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13111   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13112                                Ctor->getInheritedConstructor().getShadowDecl());
13113   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13114                             /*Diagnose*/true);
13115 }
13116 
13117 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13118                                        CXXConstructorDecl *Constructor) {
13119   CXXRecordDecl *ClassDecl = Constructor->getParent();
13120   assert(Constructor->getInheritedConstructor() &&
13121          !Constructor->doesThisDeclarationHaveABody() &&
13122          !Constructor->isDeleted());
13123   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13124     return;
13125 
13126   // Initializations are performed "as if by a defaulted default constructor",
13127   // so enter the appropriate scope.
13128   SynthesizedFunctionScope Scope(*this, Constructor);
13129 
13130   // The exception specification is needed because we are defining the
13131   // function.
13132   ResolveExceptionSpec(CurrentLocation,
13133                        Constructor->getType()->castAs<FunctionProtoType>());
13134   MarkVTableUsed(CurrentLocation, ClassDecl);
13135 
13136   // Add a context note for diagnostics produced after this point.
13137   Scope.addContextNote(CurrentLocation);
13138 
13139   ConstructorUsingShadowDecl *Shadow =
13140       Constructor->getInheritedConstructor().getShadowDecl();
13141   CXXConstructorDecl *InheritedCtor =
13142       Constructor->getInheritedConstructor().getConstructor();
13143 
13144   // [class.inhctor.init]p1:
13145   //   initialization proceeds as if a defaulted default constructor is used to
13146   //   initialize the D object and each base class subobject from which the
13147   //   constructor was inherited
13148 
13149   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13150   CXXRecordDecl *RD = Shadow->getParent();
13151   SourceLocation InitLoc = Shadow->getLocation();
13152 
13153   // Build explicit initializers for all base classes from which the
13154   // constructor was inherited.
13155   SmallVector<CXXCtorInitializer*, 8> Inits;
13156   for (bool VBase : {false, true}) {
13157     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13158       if (B.isVirtual() != VBase)
13159         continue;
13160 
13161       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13162       if (!BaseRD)
13163         continue;
13164 
13165       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13166       if (!BaseCtor.first)
13167         continue;
13168 
13169       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13170       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13171           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13172 
13173       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13174       Inits.push_back(new (Context) CXXCtorInitializer(
13175           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13176           SourceLocation()));
13177     }
13178   }
13179 
13180   // We now proceed as if for a defaulted default constructor, with the relevant
13181   // initializers replaced.
13182 
13183   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13184     Constructor->setInvalidDecl();
13185     return;
13186   }
13187 
13188   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13189   Constructor->markUsed(Context);
13190 
13191   if (ASTMutationListener *L = getASTMutationListener()) {
13192     L->CompletedImplicitDefinition(Constructor);
13193   }
13194 
13195   DiagnoseUninitializedFields(*this, Constructor);
13196 }
13197 
13198 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13199   // C++ [class.dtor]p2:
13200   //   If a class has no user-declared destructor, a destructor is
13201   //   declared implicitly. An implicitly-declared destructor is an
13202   //   inline public member of its class.
13203   assert(ClassDecl->needsImplicitDestructor());
13204 
13205   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13206   if (DSM.isAlreadyBeingDeclared())
13207     return nullptr;
13208 
13209   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13210                                                      CXXDestructor,
13211                                                      false);
13212 
13213   // Create the actual destructor declaration.
13214   CanQualType ClassType
13215     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13216   SourceLocation ClassLoc = ClassDecl->getLocation();
13217   DeclarationName Name
13218     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13219   DeclarationNameInfo NameInfo(Name, ClassLoc);
13220   CXXDestructorDecl *Destructor =
13221       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13222                                 QualType(), nullptr, /*isInline=*/true,
13223                                 /*isImplicitlyDeclared=*/true,
13224                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13225   Destructor->setAccess(AS_public);
13226   Destructor->setDefaulted();
13227 
13228   if (getLangOpts().CUDA) {
13229     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13230                                             Destructor,
13231                                             /* ConstRHS */ false,
13232                                             /* Diagnose */ false);
13233   }
13234 
13235   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13236 
13237   // We don't need to use SpecialMemberIsTrivial here; triviality for
13238   // destructors is easy to compute.
13239   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13240   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13241                                 ClassDecl->hasTrivialDestructorForCall());
13242 
13243   // Note that we have declared this destructor.
13244   ++getASTContext().NumImplicitDestructorsDeclared;
13245 
13246   Scope *S = getScopeForContext(ClassDecl);
13247   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13248 
13249   // We can't check whether an implicit destructor is deleted before we complete
13250   // the definition of the class, because its validity depends on the alignment
13251   // of the class. We'll check this from ActOnFields once the class is complete.
13252   if (ClassDecl->isCompleteDefinition() &&
13253       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13254     SetDeclDeleted(Destructor, ClassLoc);
13255 
13256   // Introduce this destructor into its scope.
13257   if (S)
13258     PushOnScopeChains(Destructor, S, false);
13259   ClassDecl->addDecl(Destructor);
13260 
13261   return Destructor;
13262 }
13263 
13264 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13265                                     CXXDestructorDecl *Destructor) {
13266   assert((Destructor->isDefaulted() &&
13267           !Destructor->doesThisDeclarationHaveABody() &&
13268           !Destructor->isDeleted()) &&
13269          "DefineImplicitDestructor - call it for implicit default dtor");
13270   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13271     return;
13272 
13273   CXXRecordDecl *ClassDecl = Destructor->getParent();
13274   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13275 
13276   SynthesizedFunctionScope Scope(*this, Destructor);
13277 
13278   // The exception specification is needed because we are defining the
13279   // function.
13280   ResolveExceptionSpec(CurrentLocation,
13281                        Destructor->getType()->castAs<FunctionProtoType>());
13282   MarkVTableUsed(CurrentLocation, ClassDecl);
13283 
13284   // Add a context note for diagnostics produced after this point.
13285   Scope.addContextNote(CurrentLocation);
13286 
13287   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13288                                          Destructor->getParent());
13289 
13290   if (CheckDestructor(Destructor)) {
13291     Destructor->setInvalidDecl();
13292     return;
13293   }
13294 
13295   SourceLocation Loc = Destructor->getEndLoc().isValid()
13296                            ? Destructor->getEndLoc()
13297                            : Destructor->getLocation();
13298   Destructor->setBody(new (Context) CompoundStmt(Loc));
13299   Destructor->markUsed(Context);
13300 
13301   if (ASTMutationListener *L = getASTMutationListener()) {
13302     L->CompletedImplicitDefinition(Destructor);
13303   }
13304 }
13305 
13306 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13307                                           CXXDestructorDecl *Destructor) {
13308   if (Destructor->isInvalidDecl())
13309     return;
13310 
13311   CXXRecordDecl *ClassDecl = Destructor->getParent();
13312   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13313          "implicit complete dtors unneeded outside MS ABI");
13314   assert(ClassDecl->getNumVBases() > 0 &&
13315          "complete dtor only exists for classes with vbases");
13316 
13317   SynthesizedFunctionScope Scope(*this, Destructor);
13318 
13319   // Add a context note for diagnostics produced after this point.
13320   Scope.addContextNote(CurrentLocation);
13321 
13322   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13323 }
13324 
13325 /// Perform any semantic analysis which needs to be delayed until all
13326 /// pending class member declarations have been parsed.
13327 void Sema::ActOnFinishCXXMemberDecls() {
13328   // If the context is an invalid C++ class, just suppress these checks.
13329   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13330     if (Record->isInvalidDecl()) {
13331       DelayedOverridingExceptionSpecChecks.clear();
13332       DelayedEquivalentExceptionSpecChecks.clear();
13333       return;
13334     }
13335     checkForMultipleExportedDefaultConstructors(*this, Record);
13336   }
13337 }
13338 
13339 void Sema::ActOnFinishCXXNonNestedClass() {
13340   referenceDLLExportedClassMethods();
13341 
13342   if (!DelayedDllExportMemberFunctions.empty()) {
13343     SmallVector<CXXMethodDecl*, 4> WorkList;
13344     std::swap(DelayedDllExportMemberFunctions, WorkList);
13345     for (CXXMethodDecl *M : WorkList) {
13346       DefineDefaultedFunction(*this, M, M->getLocation());
13347 
13348       // Pass the method to the consumer to get emitted. This is not necessary
13349       // for explicit instantiation definitions, as they will get emitted
13350       // anyway.
13351       if (M->getParent()->getTemplateSpecializationKind() !=
13352           TSK_ExplicitInstantiationDefinition)
13353         ActOnFinishInlineFunctionDef(M);
13354     }
13355   }
13356 }
13357 
13358 void Sema::referenceDLLExportedClassMethods() {
13359   if (!DelayedDllExportClasses.empty()) {
13360     // Calling ReferenceDllExportedMembers might cause the current function to
13361     // be called again, so use a local copy of DelayedDllExportClasses.
13362     SmallVector<CXXRecordDecl *, 4> WorkList;
13363     std::swap(DelayedDllExportClasses, WorkList);
13364     for (CXXRecordDecl *Class : WorkList)
13365       ReferenceDllExportedMembers(*this, Class);
13366   }
13367 }
13368 
13369 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13370   assert(getLangOpts().CPlusPlus11 &&
13371          "adjusting dtor exception specs was introduced in c++11");
13372 
13373   if (Destructor->isDependentContext())
13374     return;
13375 
13376   // C++11 [class.dtor]p3:
13377   //   A declaration of a destructor that does not have an exception-
13378   //   specification is implicitly considered to have the same exception-
13379   //   specification as an implicit declaration.
13380   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13381   if (DtorType->hasExceptionSpec())
13382     return;
13383 
13384   // Replace the destructor's type, building off the existing one. Fortunately,
13385   // the only thing of interest in the destructor type is its extended info.
13386   // The return and arguments are fixed.
13387   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13388   EPI.ExceptionSpec.Type = EST_Unevaluated;
13389   EPI.ExceptionSpec.SourceDecl = Destructor;
13390   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13391 
13392   // FIXME: If the destructor has a body that could throw, and the newly created
13393   // spec doesn't allow exceptions, we should emit a warning, because this
13394   // change in behavior can break conforming C++03 programs at runtime.
13395   // However, we don't have a body or an exception specification yet, so it
13396   // needs to be done somewhere else.
13397 }
13398 
13399 namespace {
13400 /// An abstract base class for all helper classes used in building the
13401 //  copy/move operators. These classes serve as factory functions and help us
13402 //  avoid using the same Expr* in the AST twice.
13403 class ExprBuilder {
13404   ExprBuilder(const ExprBuilder&) = delete;
13405   ExprBuilder &operator=(const ExprBuilder&) = delete;
13406 
13407 protected:
13408   static Expr *assertNotNull(Expr *E) {
13409     assert(E && "Expression construction must not fail.");
13410     return E;
13411   }
13412 
13413 public:
13414   ExprBuilder() {}
13415   virtual ~ExprBuilder() {}
13416 
13417   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13418 };
13419 
13420 class RefBuilder: public ExprBuilder {
13421   VarDecl *Var;
13422   QualType VarType;
13423 
13424 public:
13425   Expr *build(Sema &S, SourceLocation Loc) const override {
13426     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13427   }
13428 
13429   RefBuilder(VarDecl *Var, QualType VarType)
13430       : Var(Var), VarType(VarType) {}
13431 };
13432 
13433 class ThisBuilder: public ExprBuilder {
13434 public:
13435   Expr *build(Sema &S, SourceLocation Loc) const override {
13436     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13437   }
13438 };
13439 
13440 class CastBuilder: public ExprBuilder {
13441   const ExprBuilder &Builder;
13442   QualType Type;
13443   ExprValueKind Kind;
13444   const CXXCastPath &Path;
13445 
13446 public:
13447   Expr *build(Sema &S, SourceLocation Loc) const override {
13448     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13449                                              CK_UncheckedDerivedToBase, Kind,
13450                                              &Path).get());
13451   }
13452 
13453   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13454               const CXXCastPath &Path)
13455       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13456 };
13457 
13458 class DerefBuilder: public ExprBuilder {
13459   const ExprBuilder &Builder;
13460 
13461 public:
13462   Expr *build(Sema &S, SourceLocation Loc) const override {
13463     return assertNotNull(
13464         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13465   }
13466 
13467   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13468 };
13469 
13470 class MemberBuilder: public ExprBuilder {
13471   const ExprBuilder &Builder;
13472   QualType Type;
13473   CXXScopeSpec SS;
13474   bool IsArrow;
13475   LookupResult &MemberLookup;
13476 
13477 public:
13478   Expr *build(Sema &S, SourceLocation Loc) const override {
13479     return assertNotNull(S.BuildMemberReferenceExpr(
13480         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13481         nullptr, MemberLookup, nullptr, nullptr).get());
13482   }
13483 
13484   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13485                 LookupResult &MemberLookup)
13486       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13487         MemberLookup(MemberLookup) {}
13488 };
13489 
13490 class MoveCastBuilder: public ExprBuilder {
13491   const ExprBuilder &Builder;
13492 
13493 public:
13494   Expr *build(Sema &S, SourceLocation Loc) const override {
13495     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13496   }
13497 
13498   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13499 };
13500 
13501 class LvalueConvBuilder: public ExprBuilder {
13502   const ExprBuilder &Builder;
13503 
13504 public:
13505   Expr *build(Sema &S, SourceLocation Loc) const override {
13506     return assertNotNull(
13507         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13508   }
13509 
13510   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13511 };
13512 
13513 class SubscriptBuilder: public ExprBuilder {
13514   const ExprBuilder &Base;
13515   const ExprBuilder &Index;
13516 
13517 public:
13518   Expr *build(Sema &S, SourceLocation Loc) const override {
13519     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13520         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13521   }
13522 
13523   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13524       : Base(Base), Index(Index) {}
13525 };
13526 
13527 } // end anonymous namespace
13528 
13529 /// When generating a defaulted copy or move assignment operator, if a field
13530 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13531 /// do so. This optimization only applies for arrays of scalars, and for arrays
13532 /// of class type where the selected copy/move-assignment operator is trivial.
13533 static StmtResult
13534 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13535                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13536   // Compute the size of the memory buffer to be copied.
13537   QualType SizeType = S.Context.getSizeType();
13538   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13539                    S.Context.getTypeSizeInChars(T).getQuantity());
13540 
13541   // Take the address of the field references for "from" and "to". We
13542   // directly construct UnaryOperators here because semantic analysis
13543   // does not permit us to take the address of an xvalue.
13544   Expr *From = FromB.build(S, Loc);
13545   From = UnaryOperator::Create(
13546       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13547       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13548   Expr *To = ToB.build(S, Loc);
13549   To = UnaryOperator::Create(
13550       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13551       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13552 
13553   const Type *E = T->getBaseElementTypeUnsafe();
13554   bool NeedsCollectableMemCpy =
13555       E->isRecordType() &&
13556       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13557 
13558   // Create a reference to the __builtin_objc_memmove_collectable function
13559   StringRef MemCpyName = NeedsCollectableMemCpy ?
13560     "__builtin_objc_memmove_collectable" :
13561     "__builtin_memcpy";
13562   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13563                  Sema::LookupOrdinaryName);
13564   S.LookupName(R, S.TUScope, true);
13565 
13566   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13567   if (!MemCpy)
13568     // Something went horribly wrong earlier, and we will have complained
13569     // about it.
13570     return StmtError();
13571 
13572   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13573                                             VK_RValue, Loc, nullptr);
13574   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13575 
13576   Expr *CallArgs[] = {
13577     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13578   };
13579   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13580                                     Loc, CallArgs, Loc);
13581 
13582   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13583   return Call.getAs<Stmt>();
13584 }
13585 
13586 /// Builds a statement that copies/moves the given entity from \p From to
13587 /// \c To.
13588 ///
13589 /// This routine is used to copy/move the members of a class with an
13590 /// implicitly-declared copy/move assignment operator. When the entities being
13591 /// copied are arrays, this routine builds for loops to copy them.
13592 ///
13593 /// \param S The Sema object used for type-checking.
13594 ///
13595 /// \param Loc The location where the implicit copy/move is being generated.
13596 ///
13597 /// \param T The type of the expressions being copied/moved. Both expressions
13598 /// must have this type.
13599 ///
13600 /// \param To The expression we are copying/moving to.
13601 ///
13602 /// \param From The expression we are copying/moving from.
13603 ///
13604 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13605 /// Otherwise, it's a non-static member subobject.
13606 ///
13607 /// \param Copying Whether we're copying or moving.
13608 ///
13609 /// \param Depth Internal parameter recording the depth of the recursion.
13610 ///
13611 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13612 /// if a memcpy should be used instead.
13613 static StmtResult
13614 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13615                                  const ExprBuilder &To, const ExprBuilder &From,
13616                                  bool CopyingBaseSubobject, bool Copying,
13617                                  unsigned Depth = 0) {
13618   // C++11 [class.copy]p28:
13619   //   Each subobject is assigned in the manner appropriate to its type:
13620   //
13621   //     - if the subobject is of class type, as if by a call to operator= with
13622   //       the subobject as the object expression and the corresponding
13623   //       subobject of x as a single function argument (as if by explicit
13624   //       qualification; that is, ignoring any possible virtual overriding
13625   //       functions in more derived classes);
13626   //
13627   // C++03 [class.copy]p13:
13628   //     - if the subobject is of class type, the copy assignment operator for
13629   //       the class is used (as if by explicit qualification; that is,
13630   //       ignoring any possible virtual overriding functions in more derived
13631   //       classes);
13632   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13633     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13634 
13635     // Look for operator=.
13636     DeclarationName Name
13637       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13638     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13639     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13640 
13641     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13642     // operator.
13643     if (!S.getLangOpts().CPlusPlus11) {
13644       LookupResult::Filter F = OpLookup.makeFilter();
13645       while (F.hasNext()) {
13646         NamedDecl *D = F.next();
13647         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13648           if (Method->isCopyAssignmentOperator() ||
13649               (!Copying && Method->isMoveAssignmentOperator()))
13650             continue;
13651 
13652         F.erase();
13653       }
13654       F.done();
13655     }
13656 
13657     // Suppress the protected check (C++ [class.protected]) for each of the
13658     // assignment operators we found. This strange dance is required when
13659     // we're assigning via a base classes's copy-assignment operator. To
13660     // ensure that we're getting the right base class subobject (without
13661     // ambiguities), we need to cast "this" to that subobject type; to
13662     // ensure that we don't go through the virtual call mechanism, we need
13663     // to qualify the operator= name with the base class (see below). However,
13664     // this means that if the base class has a protected copy assignment
13665     // operator, the protected member access check will fail. So, we
13666     // rewrite "protected" access to "public" access in this case, since we
13667     // know by construction that we're calling from a derived class.
13668     if (CopyingBaseSubobject) {
13669       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13670            L != LEnd; ++L) {
13671         if (L.getAccess() == AS_protected)
13672           L.setAccess(AS_public);
13673       }
13674     }
13675 
13676     // Create the nested-name-specifier that will be used to qualify the
13677     // reference to operator=; this is required to suppress the virtual
13678     // call mechanism.
13679     CXXScopeSpec SS;
13680     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13681     SS.MakeTrivial(S.Context,
13682                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13683                                                CanonicalT),
13684                    Loc);
13685 
13686     // Create the reference to operator=.
13687     ExprResult OpEqualRef
13688       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13689                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13690                                    /*FirstQualifierInScope=*/nullptr,
13691                                    OpLookup,
13692                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13693                                    /*SuppressQualifierCheck=*/true);
13694     if (OpEqualRef.isInvalid())
13695       return StmtError();
13696 
13697     // Build the call to the assignment operator.
13698 
13699     Expr *FromInst = From.build(S, Loc);
13700     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13701                                                   OpEqualRef.getAs<Expr>(),
13702                                                   Loc, FromInst, Loc);
13703     if (Call.isInvalid())
13704       return StmtError();
13705 
13706     // If we built a call to a trivial 'operator=' while copying an array,
13707     // bail out. We'll replace the whole shebang with a memcpy.
13708     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13709     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13710       return StmtResult((Stmt*)nullptr);
13711 
13712     // Convert to an expression-statement, and clean up any produced
13713     // temporaries.
13714     return S.ActOnExprStmt(Call);
13715   }
13716 
13717   //     - if the subobject is of scalar type, the built-in assignment
13718   //       operator is used.
13719   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13720   if (!ArrayTy) {
13721     ExprResult Assignment = S.CreateBuiltinBinOp(
13722         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13723     if (Assignment.isInvalid())
13724       return StmtError();
13725     return S.ActOnExprStmt(Assignment);
13726   }
13727 
13728   //     - if the subobject is an array, each element is assigned, in the
13729   //       manner appropriate to the element type;
13730 
13731   // Construct a loop over the array bounds, e.g.,
13732   //
13733   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13734   //
13735   // that will copy each of the array elements.
13736   QualType SizeType = S.Context.getSizeType();
13737 
13738   // Create the iteration variable.
13739   IdentifierInfo *IterationVarName = nullptr;
13740   {
13741     SmallString<8> Str;
13742     llvm::raw_svector_ostream OS(Str);
13743     OS << "__i" << Depth;
13744     IterationVarName = &S.Context.Idents.get(OS.str());
13745   }
13746   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13747                                           IterationVarName, SizeType,
13748                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13749                                           SC_None);
13750 
13751   // Initialize the iteration variable to zero.
13752   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13753   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13754 
13755   // Creates a reference to the iteration variable.
13756   RefBuilder IterationVarRef(IterationVar, SizeType);
13757   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13758 
13759   // Create the DeclStmt that holds the iteration variable.
13760   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13761 
13762   // Subscript the "from" and "to" expressions with the iteration variable.
13763   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13764   MoveCastBuilder FromIndexMove(FromIndexCopy);
13765   const ExprBuilder *FromIndex;
13766   if (Copying)
13767     FromIndex = &FromIndexCopy;
13768   else
13769     FromIndex = &FromIndexMove;
13770 
13771   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13772 
13773   // Build the copy/move for an individual element of the array.
13774   StmtResult Copy =
13775     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13776                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13777                                      Copying, Depth + 1);
13778   // Bail out if copying fails or if we determined that we should use memcpy.
13779   if (Copy.isInvalid() || !Copy.get())
13780     return Copy;
13781 
13782   // Create the comparison against the array bound.
13783   llvm::APInt Upper
13784     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13785   Expr *Comparison = BinaryOperator::Create(
13786       S.Context, IterationVarRefRVal.build(S, Loc),
13787       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13788       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13789 
13790   // Create the pre-increment of the iteration variable. We can determine
13791   // whether the increment will overflow based on the value of the array
13792   // bound.
13793   Expr *Increment = UnaryOperator::Create(
13794       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13795       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13796 
13797   // Construct the loop that copies all elements of this array.
13798   return S.ActOnForStmt(
13799       Loc, Loc, InitStmt,
13800       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13801       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13802 }
13803 
13804 static StmtResult
13805 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13806                       const ExprBuilder &To, const ExprBuilder &From,
13807                       bool CopyingBaseSubobject, bool Copying) {
13808   // Maybe we should use a memcpy?
13809   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13810       T.isTriviallyCopyableType(S.Context))
13811     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13812 
13813   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13814                                                      CopyingBaseSubobject,
13815                                                      Copying, 0));
13816 
13817   // If we ended up picking a trivial assignment operator for an array of a
13818   // non-trivially-copyable class type, just emit a memcpy.
13819   if (!Result.isInvalid() && !Result.get())
13820     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13821 
13822   return Result;
13823 }
13824 
13825 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13826   // Note: The following rules are largely analoguous to the copy
13827   // constructor rules. Note that virtual bases are not taken into account
13828   // for determining the argument type of the operator. Note also that
13829   // operators taking an object instead of a reference are allowed.
13830   assert(ClassDecl->needsImplicitCopyAssignment());
13831 
13832   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13833   if (DSM.isAlreadyBeingDeclared())
13834     return nullptr;
13835 
13836   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13837   LangAS AS = getDefaultCXXMethodAddrSpace();
13838   if (AS != LangAS::Default)
13839     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13840   QualType RetType = Context.getLValueReferenceType(ArgType);
13841   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13842   if (Const)
13843     ArgType = ArgType.withConst();
13844 
13845   ArgType = Context.getLValueReferenceType(ArgType);
13846 
13847   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13848                                                      CXXCopyAssignment,
13849                                                      Const);
13850 
13851   //   An implicitly-declared copy assignment operator is an inline public
13852   //   member of its class.
13853   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13854   SourceLocation ClassLoc = ClassDecl->getLocation();
13855   DeclarationNameInfo NameInfo(Name, ClassLoc);
13856   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13857       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13858       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13859       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13860       SourceLocation());
13861   CopyAssignment->setAccess(AS_public);
13862   CopyAssignment->setDefaulted();
13863   CopyAssignment->setImplicit();
13864 
13865   if (getLangOpts().CUDA) {
13866     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13867                                             CopyAssignment,
13868                                             /* ConstRHS */ Const,
13869                                             /* Diagnose */ false);
13870   }
13871 
13872   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13873 
13874   // Add the parameter to the operator.
13875   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13876                                                ClassLoc, ClassLoc,
13877                                                /*Id=*/nullptr, ArgType,
13878                                                /*TInfo=*/nullptr, SC_None,
13879                                                nullptr);
13880   CopyAssignment->setParams(FromParam);
13881 
13882   CopyAssignment->setTrivial(
13883     ClassDecl->needsOverloadResolutionForCopyAssignment()
13884       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13885       : ClassDecl->hasTrivialCopyAssignment());
13886 
13887   // Note that we have added this copy-assignment operator.
13888   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13889 
13890   Scope *S = getScopeForContext(ClassDecl);
13891   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13892 
13893   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13894     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13895     SetDeclDeleted(CopyAssignment, ClassLoc);
13896   }
13897 
13898   if (S)
13899     PushOnScopeChains(CopyAssignment, S, false);
13900   ClassDecl->addDecl(CopyAssignment);
13901 
13902   return CopyAssignment;
13903 }
13904 
13905 /// Diagnose an implicit copy operation for a class which is odr-used, but
13906 /// which is deprecated because the class has a user-declared copy constructor,
13907 /// copy assignment operator, or destructor.
13908 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13909   assert(CopyOp->isImplicit());
13910 
13911   CXXRecordDecl *RD = CopyOp->getParent();
13912   CXXMethodDecl *UserDeclaredOperation = nullptr;
13913 
13914   // In Microsoft mode, assignment operations don't affect constructors and
13915   // vice versa.
13916   if (RD->hasUserDeclaredDestructor()) {
13917     UserDeclaredOperation = RD->getDestructor();
13918   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13919              RD->hasUserDeclaredCopyConstructor() &&
13920              !S.getLangOpts().MSVCCompat) {
13921     // Find any user-declared copy constructor.
13922     for (auto *I : RD->ctors()) {
13923       if (I->isCopyConstructor()) {
13924         UserDeclaredOperation = I;
13925         break;
13926       }
13927     }
13928     assert(UserDeclaredOperation);
13929   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13930              RD->hasUserDeclaredCopyAssignment() &&
13931              !S.getLangOpts().MSVCCompat) {
13932     // Find any user-declared move assignment operator.
13933     for (auto *I : RD->methods()) {
13934       if (I->isCopyAssignmentOperator()) {
13935         UserDeclaredOperation = I;
13936         break;
13937       }
13938     }
13939     assert(UserDeclaredOperation);
13940   }
13941 
13942   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13943     S.Diag(UserDeclaredOperation->getLocation(),
13944            isa<CXXDestructorDecl>(UserDeclaredOperation)
13945                ? diag::warn_deprecated_copy_dtor_operation
13946                : diag::warn_deprecated_copy_operation)
13947         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13948   }
13949 }
13950 
13951 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13952                                         CXXMethodDecl *CopyAssignOperator) {
13953   assert((CopyAssignOperator->isDefaulted() &&
13954           CopyAssignOperator->isOverloadedOperator() &&
13955           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13956           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13957           !CopyAssignOperator->isDeleted()) &&
13958          "DefineImplicitCopyAssignment called for wrong function");
13959   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13960     return;
13961 
13962   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13963   if (ClassDecl->isInvalidDecl()) {
13964     CopyAssignOperator->setInvalidDecl();
13965     return;
13966   }
13967 
13968   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13969 
13970   // The exception specification is needed because we are defining the
13971   // function.
13972   ResolveExceptionSpec(CurrentLocation,
13973                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13974 
13975   // Add a context note for diagnostics produced after this point.
13976   Scope.addContextNote(CurrentLocation);
13977 
13978   // C++11 [class.copy]p18:
13979   //   The [definition of an implicitly declared copy assignment operator] is
13980   //   deprecated if the class has a user-declared copy constructor or a
13981   //   user-declared destructor.
13982   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13983     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13984 
13985   // C++0x [class.copy]p30:
13986   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13987   //   for a non-union class X performs memberwise copy assignment of its
13988   //   subobjects. The direct base classes of X are assigned first, in the
13989   //   order of their declaration in the base-specifier-list, and then the
13990   //   immediate non-static data members of X are assigned, in the order in
13991   //   which they were declared in the class definition.
13992 
13993   // The statements that form the synthesized function body.
13994   SmallVector<Stmt*, 8> Statements;
13995 
13996   // The parameter for the "other" object, which we are copying from.
13997   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13998   Qualifiers OtherQuals = Other->getType().getQualifiers();
13999   QualType OtherRefType = Other->getType();
14000   if (const LValueReferenceType *OtherRef
14001                                 = OtherRefType->getAs<LValueReferenceType>()) {
14002     OtherRefType = OtherRef->getPointeeType();
14003     OtherQuals = OtherRefType.getQualifiers();
14004   }
14005 
14006   // Our location for everything implicitly-generated.
14007   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14008                            ? CopyAssignOperator->getEndLoc()
14009                            : CopyAssignOperator->getLocation();
14010 
14011   // Builds a DeclRefExpr for the "other" object.
14012   RefBuilder OtherRef(Other, OtherRefType);
14013 
14014   // Builds the "this" pointer.
14015   ThisBuilder This;
14016 
14017   // Assign base classes.
14018   bool Invalid = false;
14019   for (auto &Base : ClassDecl->bases()) {
14020     // Form the assignment:
14021     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14022     QualType BaseType = Base.getType().getUnqualifiedType();
14023     if (!BaseType->isRecordType()) {
14024       Invalid = true;
14025       continue;
14026     }
14027 
14028     CXXCastPath BasePath;
14029     BasePath.push_back(&Base);
14030 
14031     // Construct the "from" expression, which is an implicit cast to the
14032     // appropriately-qualified base type.
14033     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14034                      VK_LValue, BasePath);
14035 
14036     // Dereference "this".
14037     DerefBuilder DerefThis(This);
14038     CastBuilder To(DerefThis,
14039                    Context.getQualifiedType(
14040                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14041                    VK_LValue, BasePath);
14042 
14043     // Build the copy.
14044     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14045                                             To, From,
14046                                             /*CopyingBaseSubobject=*/true,
14047                                             /*Copying=*/true);
14048     if (Copy.isInvalid()) {
14049       CopyAssignOperator->setInvalidDecl();
14050       return;
14051     }
14052 
14053     // Success! Record the copy.
14054     Statements.push_back(Copy.getAs<Expr>());
14055   }
14056 
14057   // Assign non-static members.
14058   for (auto *Field : ClassDecl->fields()) {
14059     // FIXME: We should form some kind of AST representation for the implied
14060     // memcpy in a union copy operation.
14061     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14062       continue;
14063 
14064     if (Field->isInvalidDecl()) {
14065       Invalid = true;
14066       continue;
14067     }
14068 
14069     // Check for members of reference type; we can't copy those.
14070     if (Field->getType()->isReferenceType()) {
14071       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14072         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14073       Diag(Field->getLocation(), diag::note_declared_at);
14074       Invalid = true;
14075       continue;
14076     }
14077 
14078     // Check for members of const-qualified, non-class type.
14079     QualType BaseType = Context.getBaseElementType(Field->getType());
14080     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14081       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14082         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14083       Diag(Field->getLocation(), diag::note_declared_at);
14084       Invalid = true;
14085       continue;
14086     }
14087 
14088     // Suppress assigning zero-width bitfields.
14089     if (Field->isZeroLengthBitField(Context))
14090       continue;
14091 
14092     QualType FieldType = Field->getType().getNonReferenceType();
14093     if (FieldType->isIncompleteArrayType()) {
14094       assert(ClassDecl->hasFlexibleArrayMember() &&
14095              "Incomplete array type is not valid");
14096       continue;
14097     }
14098 
14099     // Build references to the field in the object we're copying from and to.
14100     CXXScopeSpec SS; // Intentionally empty
14101     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14102                               LookupMemberName);
14103     MemberLookup.addDecl(Field);
14104     MemberLookup.resolveKind();
14105 
14106     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14107 
14108     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14109 
14110     // Build the copy of this field.
14111     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14112                                             To, From,
14113                                             /*CopyingBaseSubobject=*/false,
14114                                             /*Copying=*/true);
14115     if (Copy.isInvalid()) {
14116       CopyAssignOperator->setInvalidDecl();
14117       return;
14118     }
14119 
14120     // Success! Record the copy.
14121     Statements.push_back(Copy.getAs<Stmt>());
14122   }
14123 
14124   if (!Invalid) {
14125     // Add a "return *this;"
14126     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14127 
14128     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14129     if (Return.isInvalid())
14130       Invalid = true;
14131     else
14132       Statements.push_back(Return.getAs<Stmt>());
14133   }
14134 
14135   if (Invalid) {
14136     CopyAssignOperator->setInvalidDecl();
14137     return;
14138   }
14139 
14140   StmtResult Body;
14141   {
14142     CompoundScopeRAII CompoundScope(*this);
14143     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14144                              /*isStmtExpr=*/false);
14145     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14146   }
14147   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14148   CopyAssignOperator->markUsed(Context);
14149 
14150   if (ASTMutationListener *L = getASTMutationListener()) {
14151     L->CompletedImplicitDefinition(CopyAssignOperator);
14152   }
14153 }
14154 
14155 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14156   assert(ClassDecl->needsImplicitMoveAssignment());
14157 
14158   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14159   if (DSM.isAlreadyBeingDeclared())
14160     return nullptr;
14161 
14162   // Note: The following rules are largely analoguous to the move
14163   // constructor rules.
14164 
14165   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14166   LangAS AS = getDefaultCXXMethodAddrSpace();
14167   if (AS != LangAS::Default)
14168     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14169   QualType RetType = Context.getLValueReferenceType(ArgType);
14170   ArgType = Context.getRValueReferenceType(ArgType);
14171 
14172   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14173                                                      CXXMoveAssignment,
14174                                                      false);
14175 
14176   //   An implicitly-declared move assignment operator is an inline public
14177   //   member of its class.
14178   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14179   SourceLocation ClassLoc = ClassDecl->getLocation();
14180   DeclarationNameInfo NameInfo(Name, ClassLoc);
14181   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14182       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14183       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14184       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14185       SourceLocation());
14186   MoveAssignment->setAccess(AS_public);
14187   MoveAssignment->setDefaulted();
14188   MoveAssignment->setImplicit();
14189 
14190   if (getLangOpts().CUDA) {
14191     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14192                                             MoveAssignment,
14193                                             /* ConstRHS */ false,
14194                                             /* Diagnose */ false);
14195   }
14196 
14197   // Build an exception specification pointing back at this member.
14198   FunctionProtoType::ExtProtoInfo EPI =
14199       getImplicitMethodEPI(*this, MoveAssignment);
14200   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14201 
14202   // Add the parameter to the operator.
14203   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14204                                                ClassLoc, ClassLoc,
14205                                                /*Id=*/nullptr, ArgType,
14206                                                /*TInfo=*/nullptr, SC_None,
14207                                                nullptr);
14208   MoveAssignment->setParams(FromParam);
14209 
14210   MoveAssignment->setTrivial(
14211     ClassDecl->needsOverloadResolutionForMoveAssignment()
14212       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14213       : ClassDecl->hasTrivialMoveAssignment());
14214 
14215   // Note that we have added this copy-assignment operator.
14216   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14217 
14218   Scope *S = getScopeForContext(ClassDecl);
14219   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14220 
14221   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14222     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14223     SetDeclDeleted(MoveAssignment, ClassLoc);
14224   }
14225 
14226   if (S)
14227     PushOnScopeChains(MoveAssignment, S, false);
14228   ClassDecl->addDecl(MoveAssignment);
14229 
14230   return MoveAssignment;
14231 }
14232 
14233 /// Check if we're implicitly defining a move assignment operator for a class
14234 /// with virtual bases. Such a move assignment might move-assign the virtual
14235 /// base multiple times.
14236 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14237                                                SourceLocation CurrentLocation) {
14238   assert(!Class->isDependentContext() && "should not define dependent move");
14239 
14240   // Only a virtual base could get implicitly move-assigned multiple times.
14241   // Only a non-trivial move assignment can observe this. We only want to
14242   // diagnose if we implicitly define an assignment operator that assigns
14243   // two base classes, both of which move-assign the same virtual base.
14244   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14245       Class->getNumBases() < 2)
14246     return;
14247 
14248   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14249   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14250   VBaseMap VBases;
14251 
14252   for (auto &BI : Class->bases()) {
14253     Worklist.push_back(&BI);
14254     while (!Worklist.empty()) {
14255       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14256       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14257 
14258       // If the base has no non-trivial move assignment operators,
14259       // we don't care about moves from it.
14260       if (!Base->hasNonTrivialMoveAssignment())
14261         continue;
14262 
14263       // If there's nothing virtual here, skip it.
14264       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14265         continue;
14266 
14267       // If we're not actually going to call a move assignment for this base,
14268       // or the selected move assignment is trivial, skip it.
14269       Sema::SpecialMemberOverloadResult SMOR =
14270         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14271                               /*ConstArg*/false, /*VolatileArg*/false,
14272                               /*RValueThis*/true, /*ConstThis*/false,
14273                               /*VolatileThis*/false);
14274       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14275           !SMOR.getMethod()->isMoveAssignmentOperator())
14276         continue;
14277 
14278       if (BaseSpec->isVirtual()) {
14279         // We're going to move-assign this virtual base, and its move
14280         // assignment operator is not trivial. If this can happen for
14281         // multiple distinct direct bases of Class, diagnose it. (If it
14282         // only happens in one base, we'll diagnose it when synthesizing
14283         // that base class's move assignment operator.)
14284         CXXBaseSpecifier *&Existing =
14285             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14286                 .first->second;
14287         if (Existing && Existing != &BI) {
14288           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14289             << Class << Base;
14290           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14291               << (Base->getCanonicalDecl() ==
14292                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14293               << Base << Existing->getType() << Existing->getSourceRange();
14294           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14295               << (Base->getCanonicalDecl() ==
14296                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14297               << Base << BI.getType() << BaseSpec->getSourceRange();
14298 
14299           // Only diagnose each vbase once.
14300           Existing = nullptr;
14301         }
14302       } else {
14303         // Only walk over bases that have defaulted move assignment operators.
14304         // We assume that any user-provided move assignment operator handles
14305         // the multiple-moves-of-vbase case itself somehow.
14306         if (!SMOR.getMethod()->isDefaulted())
14307           continue;
14308 
14309         // We're going to move the base classes of Base. Add them to the list.
14310         for (auto &BI : Base->bases())
14311           Worklist.push_back(&BI);
14312       }
14313     }
14314   }
14315 }
14316 
14317 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14318                                         CXXMethodDecl *MoveAssignOperator) {
14319   assert((MoveAssignOperator->isDefaulted() &&
14320           MoveAssignOperator->isOverloadedOperator() &&
14321           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14322           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14323           !MoveAssignOperator->isDeleted()) &&
14324          "DefineImplicitMoveAssignment called for wrong function");
14325   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14326     return;
14327 
14328   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14329   if (ClassDecl->isInvalidDecl()) {
14330     MoveAssignOperator->setInvalidDecl();
14331     return;
14332   }
14333 
14334   // C++0x [class.copy]p28:
14335   //   The implicitly-defined or move assignment operator for a non-union class
14336   //   X performs memberwise move assignment of its subobjects. The direct base
14337   //   classes of X are assigned first, in the order of their declaration in the
14338   //   base-specifier-list, and then the immediate non-static data members of X
14339   //   are assigned, in the order in which they were declared in the class
14340   //   definition.
14341 
14342   // Issue a warning if our implicit move assignment operator will move
14343   // from a virtual base more than once.
14344   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14345 
14346   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14347 
14348   // The exception specification is needed because we are defining the
14349   // function.
14350   ResolveExceptionSpec(CurrentLocation,
14351                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14352 
14353   // Add a context note for diagnostics produced after this point.
14354   Scope.addContextNote(CurrentLocation);
14355 
14356   // The statements that form the synthesized function body.
14357   SmallVector<Stmt*, 8> Statements;
14358 
14359   // The parameter for the "other" object, which we are move from.
14360   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14361   QualType OtherRefType =
14362       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14363 
14364   // Our location for everything implicitly-generated.
14365   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14366                            ? MoveAssignOperator->getEndLoc()
14367                            : MoveAssignOperator->getLocation();
14368 
14369   // Builds a reference to the "other" object.
14370   RefBuilder OtherRef(Other, OtherRefType);
14371   // Cast to rvalue.
14372   MoveCastBuilder MoveOther(OtherRef);
14373 
14374   // Builds the "this" pointer.
14375   ThisBuilder This;
14376 
14377   // Assign base classes.
14378   bool Invalid = false;
14379   for (auto &Base : ClassDecl->bases()) {
14380     // C++11 [class.copy]p28:
14381     //   It is unspecified whether subobjects representing virtual base classes
14382     //   are assigned more than once by the implicitly-defined copy assignment
14383     //   operator.
14384     // FIXME: Do not assign to a vbase that will be assigned by some other base
14385     // class. For a move-assignment, this can result in the vbase being moved
14386     // multiple times.
14387 
14388     // Form the assignment:
14389     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14390     QualType BaseType = Base.getType().getUnqualifiedType();
14391     if (!BaseType->isRecordType()) {
14392       Invalid = true;
14393       continue;
14394     }
14395 
14396     CXXCastPath BasePath;
14397     BasePath.push_back(&Base);
14398 
14399     // Construct the "from" expression, which is an implicit cast to the
14400     // appropriately-qualified base type.
14401     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14402 
14403     // Dereference "this".
14404     DerefBuilder DerefThis(This);
14405 
14406     // Implicitly cast "this" to the appropriately-qualified base type.
14407     CastBuilder To(DerefThis,
14408                    Context.getQualifiedType(
14409                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14410                    VK_LValue, BasePath);
14411 
14412     // Build the move.
14413     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14414                                             To, From,
14415                                             /*CopyingBaseSubobject=*/true,
14416                                             /*Copying=*/false);
14417     if (Move.isInvalid()) {
14418       MoveAssignOperator->setInvalidDecl();
14419       return;
14420     }
14421 
14422     // Success! Record the move.
14423     Statements.push_back(Move.getAs<Expr>());
14424   }
14425 
14426   // Assign non-static members.
14427   for (auto *Field : ClassDecl->fields()) {
14428     // FIXME: We should form some kind of AST representation for the implied
14429     // memcpy in a union copy operation.
14430     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14431       continue;
14432 
14433     if (Field->isInvalidDecl()) {
14434       Invalid = true;
14435       continue;
14436     }
14437 
14438     // Check for members of reference type; we can't move those.
14439     if (Field->getType()->isReferenceType()) {
14440       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14441         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14442       Diag(Field->getLocation(), diag::note_declared_at);
14443       Invalid = true;
14444       continue;
14445     }
14446 
14447     // Check for members of const-qualified, non-class type.
14448     QualType BaseType = Context.getBaseElementType(Field->getType());
14449     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14450       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14451         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14452       Diag(Field->getLocation(), diag::note_declared_at);
14453       Invalid = true;
14454       continue;
14455     }
14456 
14457     // Suppress assigning zero-width bitfields.
14458     if (Field->isZeroLengthBitField(Context))
14459       continue;
14460 
14461     QualType FieldType = Field->getType().getNonReferenceType();
14462     if (FieldType->isIncompleteArrayType()) {
14463       assert(ClassDecl->hasFlexibleArrayMember() &&
14464              "Incomplete array type is not valid");
14465       continue;
14466     }
14467 
14468     // Build references to the field in the object we're copying from and to.
14469     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14470                               LookupMemberName);
14471     MemberLookup.addDecl(Field);
14472     MemberLookup.resolveKind();
14473     MemberBuilder From(MoveOther, OtherRefType,
14474                        /*IsArrow=*/false, MemberLookup);
14475     MemberBuilder To(This, getCurrentThisType(),
14476                      /*IsArrow=*/true, MemberLookup);
14477 
14478     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14479         "Member reference with rvalue base must be rvalue except for reference "
14480         "members, which aren't allowed for move assignment.");
14481 
14482     // Build the move of this field.
14483     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14484                                             To, From,
14485                                             /*CopyingBaseSubobject=*/false,
14486                                             /*Copying=*/false);
14487     if (Move.isInvalid()) {
14488       MoveAssignOperator->setInvalidDecl();
14489       return;
14490     }
14491 
14492     // Success! Record the copy.
14493     Statements.push_back(Move.getAs<Stmt>());
14494   }
14495 
14496   if (!Invalid) {
14497     // Add a "return *this;"
14498     ExprResult ThisObj =
14499         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14500 
14501     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14502     if (Return.isInvalid())
14503       Invalid = true;
14504     else
14505       Statements.push_back(Return.getAs<Stmt>());
14506   }
14507 
14508   if (Invalid) {
14509     MoveAssignOperator->setInvalidDecl();
14510     return;
14511   }
14512 
14513   StmtResult Body;
14514   {
14515     CompoundScopeRAII CompoundScope(*this);
14516     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14517                              /*isStmtExpr=*/false);
14518     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14519   }
14520   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14521   MoveAssignOperator->markUsed(Context);
14522 
14523   if (ASTMutationListener *L = getASTMutationListener()) {
14524     L->CompletedImplicitDefinition(MoveAssignOperator);
14525   }
14526 }
14527 
14528 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14529                                                     CXXRecordDecl *ClassDecl) {
14530   // C++ [class.copy]p4:
14531   //   If the class definition does not explicitly declare a copy
14532   //   constructor, one is declared implicitly.
14533   assert(ClassDecl->needsImplicitCopyConstructor());
14534 
14535   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14536   if (DSM.isAlreadyBeingDeclared())
14537     return nullptr;
14538 
14539   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14540   QualType ArgType = ClassType;
14541   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14542   if (Const)
14543     ArgType = ArgType.withConst();
14544 
14545   LangAS AS = getDefaultCXXMethodAddrSpace();
14546   if (AS != LangAS::Default)
14547     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14548 
14549   ArgType = Context.getLValueReferenceType(ArgType);
14550 
14551   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14552                                                      CXXCopyConstructor,
14553                                                      Const);
14554 
14555   DeclarationName Name
14556     = Context.DeclarationNames.getCXXConstructorName(
14557                                            Context.getCanonicalType(ClassType));
14558   SourceLocation ClassLoc = ClassDecl->getLocation();
14559   DeclarationNameInfo NameInfo(Name, ClassLoc);
14560 
14561   //   An implicitly-declared copy constructor is an inline public
14562   //   member of its class.
14563   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14564       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14565       ExplicitSpecifier(),
14566       /*isInline=*/true,
14567       /*isImplicitlyDeclared=*/true,
14568       Constexpr ? CSK_constexpr : CSK_unspecified);
14569   CopyConstructor->setAccess(AS_public);
14570   CopyConstructor->setDefaulted();
14571 
14572   if (getLangOpts().CUDA) {
14573     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14574                                             CopyConstructor,
14575                                             /* ConstRHS */ Const,
14576                                             /* Diagnose */ false);
14577   }
14578 
14579   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14580 
14581   // Add the parameter to the constructor.
14582   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14583                                                ClassLoc, ClassLoc,
14584                                                /*IdentifierInfo=*/nullptr,
14585                                                ArgType, /*TInfo=*/nullptr,
14586                                                SC_None, nullptr);
14587   CopyConstructor->setParams(FromParam);
14588 
14589   CopyConstructor->setTrivial(
14590       ClassDecl->needsOverloadResolutionForCopyConstructor()
14591           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14592           : ClassDecl->hasTrivialCopyConstructor());
14593 
14594   CopyConstructor->setTrivialForCall(
14595       ClassDecl->hasAttr<TrivialABIAttr>() ||
14596       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14597            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14598              TAH_ConsiderTrivialABI)
14599            : ClassDecl->hasTrivialCopyConstructorForCall()));
14600 
14601   // Note that we have declared this constructor.
14602   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14603 
14604   Scope *S = getScopeForContext(ClassDecl);
14605   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14606 
14607   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14608     ClassDecl->setImplicitCopyConstructorIsDeleted();
14609     SetDeclDeleted(CopyConstructor, ClassLoc);
14610   }
14611 
14612   if (S)
14613     PushOnScopeChains(CopyConstructor, S, false);
14614   ClassDecl->addDecl(CopyConstructor);
14615 
14616   return CopyConstructor;
14617 }
14618 
14619 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14620                                          CXXConstructorDecl *CopyConstructor) {
14621   assert((CopyConstructor->isDefaulted() &&
14622           CopyConstructor->isCopyConstructor() &&
14623           !CopyConstructor->doesThisDeclarationHaveABody() &&
14624           !CopyConstructor->isDeleted()) &&
14625          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14626   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14627     return;
14628 
14629   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14630   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14631 
14632   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14633 
14634   // The exception specification is needed because we are defining the
14635   // function.
14636   ResolveExceptionSpec(CurrentLocation,
14637                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14638   MarkVTableUsed(CurrentLocation, ClassDecl);
14639 
14640   // Add a context note for diagnostics produced after this point.
14641   Scope.addContextNote(CurrentLocation);
14642 
14643   // C++11 [class.copy]p7:
14644   //   The [definition of an implicitly declared copy constructor] is
14645   //   deprecated if the class has a user-declared copy assignment operator
14646   //   or a user-declared destructor.
14647   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14648     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14649 
14650   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14651     CopyConstructor->setInvalidDecl();
14652   }  else {
14653     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14654                              ? CopyConstructor->getEndLoc()
14655                              : CopyConstructor->getLocation();
14656     Sema::CompoundScopeRAII CompoundScope(*this);
14657     CopyConstructor->setBody(
14658         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14659     CopyConstructor->markUsed(Context);
14660   }
14661 
14662   if (ASTMutationListener *L = getASTMutationListener()) {
14663     L->CompletedImplicitDefinition(CopyConstructor);
14664   }
14665 }
14666 
14667 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14668                                                     CXXRecordDecl *ClassDecl) {
14669   assert(ClassDecl->needsImplicitMoveConstructor());
14670 
14671   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14672   if (DSM.isAlreadyBeingDeclared())
14673     return nullptr;
14674 
14675   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14676 
14677   QualType ArgType = ClassType;
14678   LangAS AS = getDefaultCXXMethodAddrSpace();
14679   if (AS != LangAS::Default)
14680     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14681   ArgType = Context.getRValueReferenceType(ArgType);
14682 
14683   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14684                                                      CXXMoveConstructor,
14685                                                      false);
14686 
14687   DeclarationName Name
14688     = Context.DeclarationNames.getCXXConstructorName(
14689                                            Context.getCanonicalType(ClassType));
14690   SourceLocation ClassLoc = ClassDecl->getLocation();
14691   DeclarationNameInfo NameInfo(Name, ClassLoc);
14692 
14693   // C++11 [class.copy]p11:
14694   //   An implicitly-declared copy/move constructor is an inline public
14695   //   member of its class.
14696   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14697       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14698       ExplicitSpecifier(),
14699       /*isInline=*/true,
14700       /*isImplicitlyDeclared=*/true,
14701       Constexpr ? CSK_constexpr : CSK_unspecified);
14702   MoveConstructor->setAccess(AS_public);
14703   MoveConstructor->setDefaulted();
14704 
14705   if (getLangOpts().CUDA) {
14706     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14707                                             MoveConstructor,
14708                                             /* ConstRHS */ false,
14709                                             /* Diagnose */ false);
14710   }
14711 
14712   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14713 
14714   // Add the parameter to the constructor.
14715   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14716                                                ClassLoc, ClassLoc,
14717                                                /*IdentifierInfo=*/nullptr,
14718                                                ArgType, /*TInfo=*/nullptr,
14719                                                SC_None, nullptr);
14720   MoveConstructor->setParams(FromParam);
14721 
14722   MoveConstructor->setTrivial(
14723       ClassDecl->needsOverloadResolutionForMoveConstructor()
14724           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14725           : ClassDecl->hasTrivialMoveConstructor());
14726 
14727   MoveConstructor->setTrivialForCall(
14728       ClassDecl->hasAttr<TrivialABIAttr>() ||
14729       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14730            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14731                                     TAH_ConsiderTrivialABI)
14732            : ClassDecl->hasTrivialMoveConstructorForCall()));
14733 
14734   // Note that we have declared this constructor.
14735   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14736 
14737   Scope *S = getScopeForContext(ClassDecl);
14738   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14739 
14740   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14741     ClassDecl->setImplicitMoveConstructorIsDeleted();
14742     SetDeclDeleted(MoveConstructor, ClassLoc);
14743   }
14744 
14745   if (S)
14746     PushOnScopeChains(MoveConstructor, S, false);
14747   ClassDecl->addDecl(MoveConstructor);
14748 
14749   return MoveConstructor;
14750 }
14751 
14752 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14753                                          CXXConstructorDecl *MoveConstructor) {
14754   assert((MoveConstructor->isDefaulted() &&
14755           MoveConstructor->isMoveConstructor() &&
14756           !MoveConstructor->doesThisDeclarationHaveABody() &&
14757           !MoveConstructor->isDeleted()) &&
14758          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14759   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14760     return;
14761 
14762   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14763   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14764 
14765   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14766 
14767   // The exception specification is needed because we are defining the
14768   // function.
14769   ResolveExceptionSpec(CurrentLocation,
14770                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14771   MarkVTableUsed(CurrentLocation, ClassDecl);
14772 
14773   // Add a context note for diagnostics produced after this point.
14774   Scope.addContextNote(CurrentLocation);
14775 
14776   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14777     MoveConstructor->setInvalidDecl();
14778   } else {
14779     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14780                              ? MoveConstructor->getEndLoc()
14781                              : MoveConstructor->getLocation();
14782     Sema::CompoundScopeRAII CompoundScope(*this);
14783     MoveConstructor->setBody(ActOnCompoundStmt(
14784         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14785     MoveConstructor->markUsed(Context);
14786   }
14787 
14788   if (ASTMutationListener *L = getASTMutationListener()) {
14789     L->CompletedImplicitDefinition(MoveConstructor);
14790   }
14791 }
14792 
14793 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14794   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14795 }
14796 
14797 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14798                             SourceLocation CurrentLocation,
14799                             CXXConversionDecl *Conv) {
14800   SynthesizedFunctionScope Scope(*this, Conv);
14801   assert(!Conv->getReturnType()->isUndeducedType());
14802 
14803   CXXRecordDecl *Lambda = Conv->getParent();
14804   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14805   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14806 
14807   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14808     CallOp = InstantiateFunctionDeclaration(
14809         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14810     if (!CallOp)
14811       return;
14812 
14813     Invoker = InstantiateFunctionDeclaration(
14814         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14815     if (!Invoker)
14816       return;
14817   }
14818 
14819   if (CallOp->isInvalidDecl())
14820     return;
14821 
14822   // Mark the call operator referenced (and add to pending instantiations
14823   // if necessary).
14824   // For both the conversion and static-invoker template specializations
14825   // we construct their body's in this function, so no need to add them
14826   // to the PendingInstantiations.
14827   MarkFunctionReferenced(CurrentLocation, CallOp);
14828 
14829   // Fill in the __invoke function with a dummy implementation. IR generation
14830   // will fill in the actual details. Update its type in case it contained
14831   // an 'auto'.
14832   Invoker->markUsed(Context);
14833   Invoker->setReferenced();
14834   Invoker->setType(Conv->getReturnType()->getPointeeType());
14835   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14836 
14837   // Construct the body of the conversion function { return __invoke; }.
14838   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14839                                        VK_LValue, Conv->getLocation());
14840   assert(FunctionRef && "Can't refer to __invoke function?");
14841   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14842   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14843                                      Conv->getLocation()));
14844   Conv->markUsed(Context);
14845   Conv->setReferenced();
14846 
14847   if (ASTMutationListener *L = getASTMutationListener()) {
14848     L->CompletedImplicitDefinition(Conv);
14849     L->CompletedImplicitDefinition(Invoker);
14850   }
14851 }
14852 
14853 
14854 
14855 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14856        SourceLocation CurrentLocation,
14857        CXXConversionDecl *Conv)
14858 {
14859   assert(!Conv->getParent()->isGenericLambda());
14860 
14861   SynthesizedFunctionScope Scope(*this, Conv);
14862 
14863   // Copy-initialize the lambda object as needed to capture it.
14864   Expr *This = ActOnCXXThis(CurrentLocation).get();
14865   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14866 
14867   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14868                                                         Conv->getLocation(),
14869                                                         Conv, DerefThis);
14870 
14871   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14872   // behavior.  Note that only the general conversion function does this
14873   // (since it's unusable otherwise); in the case where we inline the
14874   // block literal, it has block literal lifetime semantics.
14875   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14876     BuildBlock = ImplicitCastExpr::Create(
14877         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14878         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14879 
14880   if (BuildBlock.isInvalid()) {
14881     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14882     Conv->setInvalidDecl();
14883     return;
14884   }
14885 
14886   // Create the return statement that returns the block from the conversion
14887   // function.
14888   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14889   if (Return.isInvalid()) {
14890     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14891     Conv->setInvalidDecl();
14892     return;
14893   }
14894 
14895   // Set the body of the conversion function.
14896   Stmt *ReturnS = Return.get();
14897   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14898                                      Conv->getLocation()));
14899   Conv->markUsed(Context);
14900 
14901   // We're done; notify the mutation listener, if any.
14902   if (ASTMutationListener *L = getASTMutationListener()) {
14903     L->CompletedImplicitDefinition(Conv);
14904   }
14905 }
14906 
14907 /// Determine whether the given list arguments contains exactly one
14908 /// "real" (non-default) argument.
14909 static bool hasOneRealArgument(MultiExprArg Args) {
14910   switch (Args.size()) {
14911   case 0:
14912     return false;
14913 
14914   default:
14915     if (!Args[1]->isDefaultArgument())
14916       return false;
14917 
14918     LLVM_FALLTHROUGH;
14919   case 1:
14920     return !Args[0]->isDefaultArgument();
14921   }
14922 
14923   return false;
14924 }
14925 
14926 ExprResult
14927 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14928                             NamedDecl *FoundDecl,
14929                             CXXConstructorDecl *Constructor,
14930                             MultiExprArg ExprArgs,
14931                             bool HadMultipleCandidates,
14932                             bool IsListInitialization,
14933                             bool IsStdInitListInitialization,
14934                             bool RequiresZeroInit,
14935                             unsigned ConstructKind,
14936                             SourceRange ParenRange) {
14937   bool Elidable = false;
14938 
14939   // C++0x [class.copy]p34:
14940   //   When certain criteria are met, an implementation is allowed to
14941   //   omit the copy/move construction of a class object, even if the
14942   //   copy/move constructor and/or destructor for the object have
14943   //   side effects. [...]
14944   //     - when a temporary class object that has not been bound to a
14945   //       reference (12.2) would be copied/moved to a class object
14946   //       with the same cv-unqualified type, the copy/move operation
14947   //       can be omitted by constructing the temporary object
14948   //       directly into the target of the omitted copy/move
14949   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14950       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14951     Expr *SubExpr = ExprArgs[0];
14952     Elidable = SubExpr->isTemporaryObject(
14953         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14954   }
14955 
14956   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14957                                FoundDecl, Constructor,
14958                                Elidable, ExprArgs, HadMultipleCandidates,
14959                                IsListInitialization,
14960                                IsStdInitListInitialization, RequiresZeroInit,
14961                                ConstructKind, ParenRange);
14962 }
14963 
14964 ExprResult
14965 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14966                             NamedDecl *FoundDecl,
14967                             CXXConstructorDecl *Constructor,
14968                             bool Elidable,
14969                             MultiExprArg ExprArgs,
14970                             bool HadMultipleCandidates,
14971                             bool IsListInitialization,
14972                             bool IsStdInitListInitialization,
14973                             bool RequiresZeroInit,
14974                             unsigned ConstructKind,
14975                             SourceRange ParenRange) {
14976   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14977     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14978     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14979       return ExprError();
14980   }
14981 
14982   return BuildCXXConstructExpr(
14983       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14984       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14985       RequiresZeroInit, ConstructKind, ParenRange);
14986 }
14987 
14988 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14989 /// including handling of its default argument expressions.
14990 ExprResult
14991 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14992                             CXXConstructorDecl *Constructor,
14993                             bool Elidable,
14994                             MultiExprArg ExprArgs,
14995                             bool HadMultipleCandidates,
14996                             bool IsListInitialization,
14997                             bool IsStdInitListInitialization,
14998                             bool RequiresZeroInit,
14999                             unsigned ConstructKind,
15000                             SourceRange ParenRange) {
15001   assert(declaresSameEntity(
15002              Constructor->getParent(),
15003              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15004          "given constructor for wrong type");
15005   MarkFunctionReferenced(ConstructLoc, Constructor);
15006   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15007     return ExprError();
15008   if (getLangOpts().SYCLIsDevice &&
15009       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15010     return ExprError();
15011 
15012   return CheckForImmediateInvocation(
15013       CXXConstructExpr::Create(
15014           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15015           HadMultipleCandidates, IsListInitialization,
15016           IsStdInitListInitialization, RequiresZeroInit,
15017           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15018           ParenRange),
15019       Constructor);
15020 }
15021 
15022 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15023   assert(Field->hasInClassInitializer());
15024 
15025   // If we already have the in-class initializer nothing needs to be done.
15026   if (Field->getInClassInitializer())
15027     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15028 
15029   // If we might have already tried and failed to instantiate, don't try again.
15030   if (Field->isInvalidDecl())
15031     return ExprError();
15032 
15033   // Maybe we haven't instantiated the in-class initializer. Go check the
15034   // pattern FieldDecl to see if it has one.
15035   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15036 
15037   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15038     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15039     DeclContext::lookup_result Lookup =
15040         ClassPattern->lookup(Field->getDeclName());
15041 
15042     // Lookup can return at most two results: the pattern for the field, or the
15043     // injected class name of the parent record. No other member can have the
15044     // same name as the field.
15045     // In modules mode, lookup can return multiple results (coming from
15046     // different modules).
15047     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15048            "more than two lookup results for field name");
15049     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15050     if (!Pattern) {
15051       assert(isa<CXXRecordDecl>(Lookup[0]) &&
15052              "cannot have other non-field member with same name");
15053       for (auto L : Lookup)
15054         if (isa<FieldDecl>(L)) {
15055           Pattern = cast<FieldDecl>(L);
15056           break;
15057         }
15058       assert(Pattern && "We must have set the Pattern!");
15059     }
15060 
15061     if (!Pattern->hasInClassInitializer() ||
15062         InstantiateInClassInitializer(Loc, Field, Pattern,
15063                                       getTemplateInstantiationArgs(Field))) {
15064       // Don't diagnose this again.
15065       Field->setInvalidDecl();
15066       return ExprError();
15067     }
15068     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15069   }
15070 
15071   // DR1351:
15072   //   If the brace-or-equal-initializer of a non-static data member
15073   //   invokes a defaulted default constructor of its class or of an
15074   //   enclosing class in a potentially evaluated subexpression, the
15075   //   program is ill-formed.
15076   //
15077   // This resolution is unworkable: the exception specification of the
15078   // default constructor can be needed in an unevaluated context, in
15079   // particular, in the operand of a noexcept-expression, and we can be
15080   // unable to compute an exception specification for an enclosed class.
15081   //
15082   // Any attempt to resolve the exception specification of a defaulted default
15083   // constructor before the initializer is lexically complete will ultimately
15084   // come here at which point we can diagnose it.
15085   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15086   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15087       << OutermostClass << Field;
15088   Diag(Field->getEndLoc(),
15089        diag::note_default_member_initializer_not_yet_parsed);
15090   // Recover by marking the field invalid, unless we're in a SFINAE context.
15091   if (!isSFINAEContext())
15092     Field->setInvalidDecl();
15093   return ExprError();
15094 }
15095 
15096 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15097   if (VD->isInvalidDecl()) return;
15098   // If initializing the variable failed, don't also diagnose problems with
15099   // the desctructor, they're likely related.
15100   if (VD->getInit() && VD->getInit()->containsErrors())
15101     return;
15102 
15103   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15104   if (ClassDecl->isInvalidDecl()) return;
15105   if (ClassDecl->hasIrrelevantDestructor()) return;
15106   if (ClassDecl->isDependentContext()) return;
15107 
15108   if (VD->isNoDestroy(getASTContext()))
15109     return;
15110 
15111   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15112 
15113   // If this is an array, we'll require the destructor during initialization, so
15114   // we can skip over this. We still want to emit exit-time destructor warnings
15115   // though.
15116   if (!VD->getType()->isArrayType()) {
15117     MarkFunctionReferenced(VD->getLocation(), Destructor);
15118     CheckDestructorAccess(VD->getLocation(), Destructor,
15119                           PDiag(diag::err_access_dtor_var)
15120                               << VD->getDeclName() << VD->getType());
15121     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15122   }
15123 
15124   if (Destructor->isTrivial()) return;
15125 
15126   // If the destructor is constexpr, check whether the variable has constant
15127   // destruction now.
15128   if (Destructor->isConstexpr()) {
15129     bool HasConstantInit = false;
15130     if (VD->getInit() && !VD->getInit()->isValueDependent())
15131       HasConstantInit = VD->evaluateValue();
15132     SmallVector<PartialDiagnosticAt, 8> Notes;
15133     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15134         HasConstantInit) {
15135       Diag(VD->getLocation(),
15136            diag::err_constexpr_var_requires_const_destruction) << VD;
15137       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15138         Diag(Notes[I].first, Notes[I].second);
15139     }
15140   }
15141 
15142   if (!VD->hasGlobalStorage()) return;
15143 
15144   // Emit warning for non-trivial dtor in global scope (a real global,
15145   // class-static, function-static).
15146   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15147 
15148   // TODO: this should be re-enabled for static locals by !CXAAtExit
15149   if (!VD->isStaticLocal())
15150     Diag(VD->getLocation(), diag::warn_global_destructor);
15151 }
15152 
15153 /// Given a constructor and the set of arguments provided for the
15154 /// constructor, convert the arguments and add any required default arguments
15155 /// to form a proper call to this constructor.
15156 ///
15157 /// \returns true if an error occurred, false otherwise.
15158 bool
15159 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15160                               MultiExprArg ArgsPtr,
15161                               SourceLocation Loc,
15162                               SmallVectorImpl<Expr*> &ConvertedArgs,
15163                               bool AllowExplicit,
15164                               bool IsListInitialization) {
15165   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15166   unsigned NumArgs = ArgsPtr.size();
15167   Expr **Args = ArgsPtr.data();
15168 
15169   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15170   unsigned NumParams = Proto->getNumParams();
15171 
15172   // If too few arguments are available, we'll fill in the rest with defaults.
15173   if (NumArgs < NumParams)
15174     ConvertedArgs.reserve(NumParams);
15175   else
15176     ConvertedArgs.reserve(NumArgs);
15177 
15178   VariadicCallType CallType =
15179     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15180   SmallVector<Expr *, 8> AllArgs;
15181   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15182                                         Proto, 0,
15183                                         llvm::makeArrayRef(Args, NumArgs),
15184                                         AllArgs,
15185                                         CallType, AllowExplicit,
15186                                         IsListInitialization);
15187   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15188 
15189   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15190 
15191   CheckConstructorCall(Constructor,
15192                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15193                        Proto, Loc);
15194 
15195   return Invalid;
15196 }
15197 
15198 static inline bool
15199 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15200                                        const FunctionDecl *FnDecl) {
15201   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15202   if (isa<NamespaceDecl>(DC)) {
15203     return SemaRef.Diag(FnDecl->getLocation(),
15204                         diag::err_operator_new_delete_declared_in_namespace)
15205       << FnDecl->getDeclName();
15206   }
15207 
15208   if (isa<TranslationUnitDecl>(DC) &&
15209       FnDecl->getStorageClass() == SC_Static) {
15210     return SemaRef.Diag(FnDecl->getLocation(),
15211                         diag::err_operator_new_delete_declared_static)
15212       << FnDecl->getDeclName();
15213   }
15214 
15215   return false;
15216 }
15217 
15218 static QualType
15219 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15220   QualType QTy = PtrTy->getPointeeType();
15221   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15222   return SemaRef.Context.getPointerType(QTy);
15223 }
15224 
15225 static inline bool
15226 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15227                             CanQualType ExpectedResultType,
15228                             CanQualType ExpectedFirstParamType,
15229                             unsigned DependentParamTypeDiag,
15230                             unsigned InvalidParamTypeDiag) {
15231   QualType ResultType =
15232       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15233 
15234   // The operator is valid on any address space for OpenCL.
15235   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15236     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15237       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15238     }
15239   }
15240 
15241   // Check that the result type is what we expect.
15242   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15243     // Reject even if the type is dependent; an operator delete function is
15244     // required to have a non-dependent result type.
15245     return SemaRef.Diag(
15246                FnDecl->getLocation(),
15247                ResultType->isDependentType()
15248                    ? diag::err_operator_new_delete_dependent_result_type
15249                    : diag::err_operator_new_delete_invalid_result_type)
15250            << FnDecl->getDeclName() << ExpectedResultType;
15251   }
15252 
15253   // A function template must have at least 2 parameters.
15254   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15255     return SemaRef.Diag(FnDecl->getLocation(),
15256                       diag::err_operator_new_delete_template_too_few_parameters)
15257         << FnDecl->getDeclName();
15258 
15259   // The function decl must have at least 1 parameter.
15260   if (FnDecl->getNumParams() == 0)
15261     return SemaRef.Diag(FnDecl->getLocation(),
15262                         diag::err_operator_new_delete_too_few_parameters)
15263       << FnDecl->getDeclName();
15264 
15265   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15266   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15267     // The operator is valid on any address space for OpenCL.
15268     if (auto *PtrTy =
15269             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15270       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15271     }
15272   }
15273 
15274   // Check that the first parameter type is what we expect.
15275   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15276       ExpectedFirstParamType) {
15277     // The first parameter type is not allowed to be dependent. As a tentative
15278     // DR resolution, we allow a dependent parameter type if it is the right
15279     // type anyway, to allow destroying operator delete in class templates.
15280     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15281                                                    ? DependentParamTypeDiag
15282                                                    : InvalidParamTypeDiag)
15283            << FnDecl->getDeclName() << ExpectedFirstParamType;
15284   }
15285 
15286   return false;
15287 }
15288 
15289 static bool
15290 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15291   // C++ [basic.stc.dynamic.allocation]p1:
15292   //   A program is ill-formed if an allocation function is declared in a
15293   //   namespace scope other than global scope or declared static in global
15294   //   scope.
15295   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15296     return true;
15297 
15298   CanQualType SizeTy =
15299     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15300 
15301   // C++ [basic.stc.dynamic.allocation]p1:
15302   //  The return type shall be void*. The first parameter shall have type
15303   //  std::size_t.
15304   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15305                                   SizeTy,
15306                                   diag::err_operator_new_dependent_param_type,
15307                                   diag::err_operator_new_param_type))
15308     return true;
15309 
15310   // C++ [basic.stc.dynamic.allocation]p1:
15311   //  The first parameter shall not have an associated default argument.
15312   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15313     return SemaRef.Diag(FnDecl->getLocation(),
15314                         diag::err_operator_new_default_arg)
15315       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15316 
15317   return false;
15318 }
15319 
15320 static bool
15321 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15322   // C++ [basic.stc.dynamic.deallocation]p1:
15323   //   A program is ill-formed if deallocation functions are declared in a
15324   //   namespace scope other than global scope or declared static in global
15325   //   scope.
15326   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15327     return true;
15328 
15329   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15330 
15331   // C++ P0722:
15332   //   Within a class C, the first parameter of a destroying operator delete
15333   //   shall be of type C *. The first parameter of any other deallocation
15334   //   function shall be of type void *.
15335   CanQualType ExpectedFirstParamType =
15336       MD && MD->isDestroyingOperatorDelete()
15337           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15338                 SemaRef.Context.getRecordType(MD->getParent())))
15339           : SemaRef.Context.VoidPtrTy;
15340 
15341   // C++ [basic.stc.dynamic.deallocation]p2:
15342   //   Each deallocation function shall return void
15343   if (CheckOperatorNewDeleteTypes(
15344           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15345           diag::err_operator_delete_dependent_param_type,
15346           diag::err_operator_delete_param_type))
15347     return true;
15348 
15349   // C++ P0722:
15350   //   A destroying operator delete shall be a usual deallocation function.
15351   if (MD && !MD->getParent()->isDependentContext() &&
15352       MD->isDestroyingOperatorDelete() &&
15353       !SemaRef.isUsualDeallocationFunction(MD)) {
15354     SemaRef.Diag(MD->getLocation(),
15355                  diag::err_destroying_operator_delete_not_usual);
15356     return true;
15357   }
15358 
15359   return false;
15360 }
15361 
15362 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15363 /// of this overloaded operator is well-formed. If so, returns false;
15364 /// otherwise, emits appropriate diagnostics and returns true.
15365 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15366   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15367          "Expected an overloaded operator declaration");
15368 
15369   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15370 
15371   // C++ [over.oper]p5:
15372   //   The allocation and deallocation functions, operator new,
15373   //   operator new[], operator delete and operator delete[], are
15374   //   described completely in 3.7.3. The attributes and restrictions
15375   //   found in the rest of this subclause do not apply to them unless
15376   //   explicitly stated in 3.7.3.
15377   if (Op == OO_Delete || Op == OO_Array_Delete)
15378     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15379 
15380   if (Op == OO_New || Op == OO_Array_New)
15381     return CheckOperatorNewDeclaration(*this, FnDecl);
15382 
15383   // C++ [over.oper]p6:
15384   //   An operator function shall either be a non-static member
15385   //   function or be a non-member function and have at least one
15386   //   parameter whose type is a class, a reference to a class, an
15387   //   enumeration, or a reference to an enumeration.
15388   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15389     if (MethodDecl->isStatic())
15390       return Diag(FnDecl->getLocation(),
15391                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15392   } else {
15393     bool ClassOrEnumParam = false;
15394     for (auto Param : FnDecl->parameters()) {
15395       QualType ParamType = Param->getType().getNonReferenceType();
15396       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15397           ParamType->isEnumeralType()) {
15398         ClassOrEnumParam = true;
15399         break;
15400       }
15401     }
15402 
15403     if (!ClassOrEnumParam)
15404       return Diag(FnDecl->getLocation(),
15405                   diag::err_operator_overload_needs_class_or_enum)
15406         << FnDecl->getDeclName();
15407   }
15408 
15409   // C++ [over.oper]p8:
15410   //   An operator function cannot have default arguments (8.3.6),
15411   //   except where explicitly stated below.
15412   //
15413   // Only the function-call operator allows default arguments
15414   // (C++ [over.call]p1).
15415   if (Op != OO_Call) {
15416     for (auto Param : FnDecl->parameters()) {
15417       if (Param->hasDefaultArg())
15418         return Diag(Param->getLocation(),
15419                     diag::err_operator_overload_default_arg)
15420           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15421     }
15422   }
15423 
15424   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15425     { false, false, false }
15426 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15427     , { Unary, Binary, MemberOnly }
15428 #include "clang/Basic/OperatorKinds.def"
15429   };
15430 
15431   bool CanBeUnaryOperator = OperatorUses[Op][0];
15432   bool CanBeBinaryOperator = OperatorUses[Op][1];
15433   bool MustBeMemberOperator = OperatorUses[Op][2];
15434 
15435   // C++ [over.oper]p8:
15436   //   [...] Operator functions cannot have more or fewer parameters
15437   //   than the number required for the corresponding operator, as
15438   //   described in the rest of this subclause.
15439   unsigned NumParams = FnDecl->getNumParams()
15440                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15441   if (Op != OO_Call &&
15442       ((NumParams == 1 && !CanBeUnaryOperator) ||
15443        (NumParams == 2 && !CanBeBinaryOperator) ||
15444        (NumParams < 1) || (NumParams > 2))) {
15445     // We have the wrong number of parameters.
15446     unsigned ErrorKind;
15447     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15448       ErrorKind = 2;  // 2 -> unary or binary.
15449     } else if (CanBeUnaryOperator) {
15450       ErrorKind = 0;  // 0 -> unary
15451     } else {
15452       assert(CanBeBinaryOperator &&
15453              "All non-call overloaded operators are unary or binary!");
15454       ErrorKind = 1;  // 1 -> binary
15455     }
15456 
15457     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15458       << FnDecl->getDeclName() << NumParams << ErrorKind;
15459   }
15460 
15461   // Overloaded operators other than operator() cannot be variadic.
15462   if (Op != OO_Call &&
15463       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15464     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15465       << FnDecl->getDeclName();
15466   }
15467 
15468   // Some operators must be non-static member functions.
15469   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15470     return Diag(FnDecl->getLocation(),
15471                 diag::err_operator_overload_must_be_member)
15472       << FnDecl->getDeclName();
15473   }
15474 
15475   // C++ [over.inc]p1:
15476   //   The user-defined function called operator++ implements the
15477   //   prefix and postfix ++ operator. If this function is a member
15478   //   function with no parameters, or a non-member function with one
15479   //   parameter of class or enumeration type, it defines the prefix
15480   //   increment operator ++ for objects of that type. If the function
15481   //   is a member function with one parameter (which shall be of type
15482   //   int) or a non-member function with two parameters (the second
15483   //   of which shall be of type int), it defines the postfix
15484   //   increment operator ++ for objects of that type.
15485   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15486     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15487     QualType ParamType = LastParam->getType();
15488 
15489     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15490         !ParamType->isDependentType())
15491       return Diag(LastParam->getLocation(),
15492                   diag::err_operator_overload_post_incdec_must_be_int)
15493         << LastParam->getType() << (Op == OO_MinusMinus);
15494   }
15495 
15496   return false;
15497 }
15498 
15499 static bool
15500 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15501                                           FunctionTemplateDecl *TpDecl) {
15502   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15503 
15504   // Must have one or two template parameters.
15505   if (TemplateParams->size() == 1) {
15506     NonTypeTemplateParmDecl *PmDecl =
15507         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15508 
15509     // The template parameter must be a char parameter pack.
15510     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15511         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15512       return false;
15513 
15514   } else if (TemplateParams->size() == 2) {
15515     TemplateTypeParmDecl *PmType =
15516         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15517     NonTypeTemplateParmDecl *PmArgs =
15518         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15519 
15520     // The second template parameter must be a parameter pack with the
15521     // first template parameter as its type.
15522     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15523         PmArgs->isTemplateParameterPack()) {
15524       const TemplateTypeParmType *TArgs =
15525           PmArgs->getType()->getAs<TemplateTypeParmType>();
15526       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15527           TArgs->getIndex() == PmType->getIndex()) {
15528         if (!SemaRef.inTemplateInstantiation())
15529           SemaRef.Diag(TpDecl->getLocation(),
15530                        diag::ext_string_literal_operator_template);
15531         return false;
15532       }
15533     }
15534   }
15535 
15536   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15537                diag::err_literal_operator_template)
15538       << TpDecl->getTemplateParameters()->getSourceRange();
15539   return true;
15540 }
15541 
15542 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15543 /// of this literal operator function is well-formed. If so, returns
15544 /// false; otherwise, emits appropriate diagnostics and returns true.
15545 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15546   if (isa<CXXMethodDecl>(FnDecl)) {
15547     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15548       << FnDecl->getDeclName();
15549     return true;
15550   }
15551 
15552   if (FnDecl->isExternC()) {
15553     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15554     if (const LinkageSpecDecl *LSD =
15555             FnDecl->getDeclContext()->getExternCContext())
15556       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15557     return true;
15558   }
15559 
15560   // This might be the definition of a literal operator template.
15561   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15562 
15563   // This might be a specialization of a literal operator template.
15564   if (!TpDecl)
15565     TpDecl = FnDecl->getPrimaryTemplate();
15566 
15567   // template <char...> type operator "" name() and
15568   // template <class T, T...> type operator "" name() are the only valid
15569   // template signatures, and the only valid signatures with no parameters.
15570   if (TpDecl) {
15571     if (FnDecl->param_size() != 0) {
15572       Diag(FnDecl->getLocation(),
15573            diag::err_literal_operator_template_with_params);
15574       return true;
15575     }
15576 
15577     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15578       return true;
15579 
15580   } else if (FnDecl->param_size() == 1) {
15581     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15582 
15583     QualType ParamType = Param->getType().getUnqualifiedType();
15584 
15585     // Only unsigned long long int, long double, any character type, and const
15586     // char * are allowed as the only parameters.
15587     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15588         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15589         Context.hasSameType(ParamType, Context.CharTy) ||
15590         Context.hasSameType(ParamType, Context.WideCharTy) ||
15591         Context.hasSameType(ParamType, Context.Char8Ty) ||
15592         Context.hasSameType(ParamType, Context.Char16Ty) ||
15593         Context.hasSameType(ParamType, Context.Char32Ty)) {
15594     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15595       QualType InnerType = Ptr->getPointeeType();
15596 
15597       // Pointer parameter must be a const char *.
15598       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15599                                 Context.CharTy) &&
15600             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15601         Diag(Param->getSourceRange().getBegin(),
15602              diag::err_literal_operator_param)
15603             << ParamType << "'const char *'" << Param->getSourceRange();
15604         return true;
15605       }
15606 
15607     } else if (ParamType->isRealFloatingType()) {
15608       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15609           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15610       return true;
15611 
15612     } else if (ParamType->isIntegerType()) {
15613       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15614           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15615       return true;
15616 
15617     } else {
15618       Diag(Param->getSourceRange().getBegin(),
15619            diag::err_literal_operator_invalid_param)
15620           << ParamType << Param->getSourceRange();
15621       return true;
15622     }
15623 
15624   } else if (FnDecl->param_size() == 2) {
15625     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15626 
15627     // First, verify that the first parameter is correct.
15628 
15629     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15630 
15631     // Two parameter function must have a pointer to const as a
15632     // first parameter; let's strip those qualifiers.
15633     const PointerType *PT = FirstParamType->getAs<PointerType>();
15634 
15635     if (!PT) {
15636       Diag((*Param)->getSourceRange().getBegin(),
15637            diag::err_literal_operator_param)
15638           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15639       return true;
15640     }
15641 
15642     QualType PointeeType = PT->getPointeeType();
15643     // First parameter must be const
15644     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15645       Diag((*Param)->getSourceRange().getBegin(),
15646            diag::err_literal_operator_param)
15647           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15648       return true;
15649     }
15650 
15651     QualType InnerType = PointeeType.getUnqualifiedType();
15652     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15653     // const char32_t* are allowed as the first parameter to a two-parameter
15654     // function
15655     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15656           Context.hasSameType(InnerType, Context.WideCharTy) ||
15657           Context.hasSameType(InnerType, Context.Char8Ty) ||
15658           Context.hasSameType(InnerType, Context.Char16Ty) ||
15659           Context.hasSameType(InnerType, Context.Char32Ty))) {
15660       Diag((*Param)->getSourceRange().getBegin(),
15661            diag::err_literal_operator_param)
15662           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15663       return true;
15664     }
15665 
15666     // Move on to the second and final parameter.
15667     ++Param;
15668 
15669     // The second parameter must be a std::size_t.
15670     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15671     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15672       Diag((*Param)->getSourceRange().getBegin(),
15673            diag::err_literal_operator_param)
15674           << SecondParamType << Context.getSizeType()
15675           << (*Param)->getSourceRange();
15676       return true;
15677     }
15678   } else {
15679     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15680     return true;
15681   }
15682 
15683   // Parameters are good.
15684 
15685   // A parameter-declaration-clause containing a default argument is not
15686   // equivalent to any of the permitted forms.
15687   for (auto Param : FnDecl->parameters()) {
15688     if (Param->hasDefaultArg()) {
15689       Diag(Param->getDefaultArgRange().getBegin(),
15690            diag::err_literal_operator_default_argument)
15691         << Param->getDefaultArgRange();
15692       break;
15693     }
15694   }
15695 
15696   StringRef LiteralName
15697     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15698   if (LiteralName[0] != '_' &&
15699       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15700     // C++11 [usrlit.suffix]p1:
15701     //   Literal suffix identifiers that do not start with an underscore
15702     //   are reserved for future standardization.
15703     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15704       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15705   }
15706 
15707   return false;
15708 }
15709 
15710 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15711 /// linkage specification, including the language and (if present)
15712 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15713 /// language string literal. LBraceLoc, if valid, provides the location of
15714 /// the '{' brace. Otherwise, this linkage specification does not
15715 /// have any braces.
15716 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15717                                            Expr *LangStr,
15718                                            SourceLocation LBraceLoc) {
15719   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15720   if (!Lit->isAscii()) {
15721     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15722       << LangStr->getSourceRange();
15723     return nullptr;
15724   }
15725 
15726   StringRef Lang = Lit->getString();
15727   LinkageSpecDecl::LanguageIDs Language;
15728   if (Lang == "C")
15729     Language = LinkageSpecDecl::lang_c;
15730   else if (Lang == "C++")
15731     Language = LinkageSpecDecl::lang_cxx;
15732   else {
15733     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15734       << LangStr->getSourceRange();
15735     return nullptr;
15736   }
15737 
15738   // FIXME: Add all the various semantics of linkage specifications
15739 
15740   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15741                                                LangStr->getExprLoc(), Language,
15742                                                LBraceLoc.isValid());
15743   CurContext->addDecl(D);
15744   PushDeclContext(S, D);
15745   return D;
15746 }
15747 
15748 /// ActOnFinishLinkageSpecification - Complete the definition of
15749 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15750 /// valid, it's the position of the closing '}' brace in a linkage
15751 /// specification that uses braces.
15752 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15753                                             Decl *LinkageSpec,
15754                                             SourceLocation RBraceLoc) {
15755   if (RBraceLoc.isValid()) {
15756     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15757     LSDecl->setRBraceLoc(RBraceLoc);
15758   }
15759   PopDeclContext();
15760   return LinkageSpec;
15761 }
15762 
15763 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15764                                   const ParsedAttributesView &AttrList,
15765                                   SourceLocation SemiLoc) {
15766   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15767   // Attribute declarations appertain to empty declaration so we handle
15768   // them here.
15769   ProcessDeclAttributeList(S, ED, AttrList);
15770 
15771   CurContext->addDecl(ED);
15772   return ED;
15773 }
15774 
15775 /// Perform semantic analysis for the variable declaration that
15776 /// occurs within a C++ catch clause, returning the newly-created
15777 /// variable.
15778 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15779                                          TypeSourceInfo *TInfo,
15780                                          SourceLocation StartLoc,
15781                                          SourceLocation Loc,
15782                                          IdentifierInfo *Name) {
15783   bool Invalid = false;
15784   QualType ExDeclType = TInfo->getType();
15785 
15786   // Arrays and functions decay.
15787   if (ExDeclType->isArrayType())
15788     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15789   else if (ExDeclType->isFunctionType())
15790     ExDeclType = Context.getPointerType(ExDeclType);
15791 
15792   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15793   // The exception-declaration shall not denote a pointer or reference to an
15794   // incomplete type, other than [cv] void*.
15795   // N2844 forbids rvalue references.
15796   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15797     Diag(Loc, diag::err_catch_rvalue_ref);
15798     Invalid = true;
15799   }
15800 
15801   if (ExDeclType->isVariablyModifiedType()) {
15802     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15803     Invalid = true;
15804   }
15805 
15806   QualType BaseType = ExDeclType;
15807   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15808   unsigned DK = diag::err_catch_incomplete;
15809   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15810     BaseType = Ptr->getPointeeType();
15811     Mode = 1;
15812     DK = diag::err_catch_incomplete_ptr;
15813   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15814     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15815     BaseType = Ref->getPointeeType();
15816     Mode = 2;
15817     DK = diag::err_catch_incomplete_ref;
15818   }
15819   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15820       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15821     Invalid = true;
15822 
15823   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15824     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15825     Invalid = true;
15826   }
15827 
15828   if (!Invalid && !ExDeclType->isDependentType() &&
15829       RequireNonAbstractType(Loc, ExDeclType,
15830                              diag::err_abstract_type_in_decl,
15831                              AbstractVariableType))
15832     Invalid = true;
15833 
15834   // Only the non-fragile NeXT runtime currently supports C++ catches
15835   // of ObjC types, and no runtime supports catching ObjC types by value.
15836   if (!Invalid && getLangOpts().ObjC) {
15837     QualType T = ExDeclType;
15838     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15839       T = RT->getPointeeType();
15840 
15841     if (T->isObjCObjectType()) {
15842       Diag(Loc, diag::err_objc_object_catch);
15843       Invalid = true;
15844     } else if (T->isObjCObjectPointerType()) {
15845       // FIXME: should this be a test for macosx-fragile specifically?
15846       if (getLangOpts().ObjCRuntime.isFragile())
15847         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15848     }
15849   }
15850 
15851   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15852                                     ExDeclType, TInfo, SC_None);
15853   ExDecl->setExceptionVariable(true);
15854 
15855   // In ARC, infer 'retaining' for variables of retainable type.
15856   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15857     Invalid = true;
15858 
15859   if (!Invalid && !ExDeclType->isDependentType()) {
15860     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15861       // Insulate this from anything else we might currently be parsing.
15862       EnterExpressionEvaluationContext scope(
15863           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15864 
15865       // C++ [except.handle]p16:
15866       //   The object declared in an exception-declaration or, if the
15867       //   exception-declaration does not specify a name, a temporary (12.2) is
15868       //   copy-initialized (8.5) from the exception object. [...]
15869       //   The object is destroyed when the handler exits, after the destruction
15870       //   of any automatic objects initialized within the handler.
15871       //
15872       // We just pretend to initialize the object with itself, then make sure
15873       // it can be destroyed later.
15874       QualType initType = Context.getExceptionObjectType(ExDeclType);
15875 
15876       InitializedEntity entity =
15877         InitializedEntity::InitializeVariable(ExDecl);
15878       InitializationKind initKind =
15879         InitializationKind::CreateCopy(Loc, SourceLocation());
15880 
15881       Expr *opaqueValue =
15882         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15883       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15884       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15885       if (result.isInvalid())
15886         Invalid = true;
15887       else {
15888         // If the constructor used was non-trivial, set this as the
15889         // "initializer".
15890         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15891         if (!construct->getConstructor()->isTrivial()) {
15892           Expr *init = MaybeCreateExprWithCleanups(construct);
15893           ExDecl->setInit(init);
15894         }
15895 
15896         // And make sure it's destructable.
15897         FinalizeVarWithDestructor(ExDecl, recordType);
15898       }
15899     }
15900   }
15901 
15902   if (Invalid)
15903     ExDecl->setInvalidDecl();
15904 
15905   return ExDecl;
15906 }
15907 
15908 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15909 /// handler.
15910 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15911   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15912   bool Invalid = D.isInvalidType();
15913 
15914   // Check for unexpanded parameter packs.
15915   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15916                                       UPPC_ExceptionType)) {
15917     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15918                                              D.getIdentifierLoc());
15919     Invalid = true;
15920   }
15921 
15922   IdentifierInfo *II = D.getIdentifier();
15923   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15924                                              LookupOrdinaryName,
15925                                              ForVisibleRedeclaration)) {
15926     // The scope should be freshly made just for us. There is just no way
15927     // it contains any previous declaration, except for function parameters in
15928     // a function-try-block's catch statement.
15929     assert(!S->isDeclScope(PrevDecl));
15930     if (isDeclInScope(PrevDecl, CurContext, S)) {
15931       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15932         << D.getIdentifier();
15933       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15934       Invalid = true;
15935     } else if (PrevDecl->isTemplateParameter())
15936       // Maybe we will complain about the shadowed template parameter.
15937       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15938   }
15939 
15940   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15941     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15942       << D.getCXXScopeSpec().getRange();
15943     Invalid = true;
15944   }
15945 
15946   VarDecl *ExDecl = BuildExceptionDeclaration(
15947       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15948   if (Invalid)
15949     ExDecl->setInvalidDecl();
15950 
15951   // Add the exception declaration into this scope.
15952   if (II)
15953     PushOnScopeChains(ExDecl, S);
15954   else
15955     CurContext->addDecl(ExDecl);
15956 
15957   ProcessDeclAttributes(S, ExDecl, D);
15958   return ExDecl;
15959 }
15960 
15961 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15962                                          Expr *AssertExpr,
15963                                          Expr *AssertMessageExpr,
15964                                          SourceLocation RParenLoc) {
15965   StringLiteral *AssertMessage =
15966       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15967 
15968   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15969     return nullptr;
15970 
15971   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15972                                       AssertMessage, RParenLoc, false);
15973 }
15974 
15975 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15976                                          Expr *AssertExpr,
15977                                          StringLiteral *AssertMessage,
15978                                          SourceLocation RParenLoc,
15979                                          bool Failed) {
15980   assert(AssertExpr != nullptr && "Expected non-null condition");
15981   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15982       !Failed) {
15983     // In a static_assert-declaration, the constant-expression shall be a
15984     // constant expression that can be contextually converted to bool.
15985     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15986     if (Converted.isInvalid())
15987       Failed = true;
15988 
15989     ExprResult FullAssertExpr =
15990         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15991                             /*DiscardedValue*/ false,
15992                             /*IsConstexpr*/ true);
15993     if (FullAssertExpr.isInvalid())
15994       Failed = true;
15995     else
15996       AssertExpr = FullAssertExpr.get();
15997 
15998     llvm::APSInt Cond;
15999     if (!Failed && VerifyIntegerConstantExpression(
16000                        AssertExpr, &Cond,
16001                        diag::err_static_assert_expression_is_not_constant)
16002                        .isInvalid())
16003       Failed = true;
16004 
16005     if (!Failed && !Cond) {
16006       SmallString<256> MsgBuffer;
16007       llvm::raw_svector_ostream Msg(MsgBuffer);
16008       if (AssertMessage)
16009         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16010 
16011       Expr *InnerCond = nullptr;
16012       std::string InnerCondDescription;
16013       std::tie(InnerCond, InnerCondDescription) =
16014         findFailedBooleanCondition(Converted.get());
16015       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16016         // Drill down into concept specialization expressions to see why they
16017         // weren't satisfied.
16018         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16019           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16020         ConstraintSatisfaction Satisfaction;
16021         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16022           DiagnoseUnsatisfiedConstraint(Satisfaction);
16023       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16024                            && !isa<IntegerLiteral>(InnerCond)) {
16025         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16026           << InnerCondDescription << !AssertMessage
16027           << Msg.str() << InnerCond->getSourceRange();
16028       } else {
16029         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16030           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16031       }
16032       Failed = true;
16033     }
16034   } else {
16035     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16036                                                     /*DiscardedValue*/false,
16037                                                     /*IsConstexpr*/true);
16038     if (FullAssertExpr.isInvalid())
16039       Failed = true;
16040     else
16041       AssertExpr = FullAssertExpr.get();
16042   }
16043 
16044   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16045                                         AssertExpr, AssertMessage, RParenLoc,
16046                                         Failed);
16047 
16048   CurContext->addDecl(Decl);
16049   return Decl;
16050 }
16051 
16052 /// Perform semantic analysis of the given friend type declaration.
16053 ///
16054 /// \returns A friend declaration that.
16055 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16056                                       SourceLocation FriendLoc,
16057                                       TypeSourceInfo *TSInfo) {
16058   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16059 
16060   QualType T = TSInfo->getType();
16061   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16062 
16063   // C++03 [class.friend]p2:
16064   //   An elaborated-type-specifier shall be used in a friend declaration
16065   //   for a class.*
16066   //
16067   //   * The class-key of the elaborated-type-specifier is required.
16068   if (!CodeSynthesisContexts.empty()) {
16069     // Do not complain about the form of friend template types during any kind
16070     // of code synthesis. For template instantiation, we will have complained
16071     // when the template was defined.
16072   } else {
16073     if (!T->isElaboratedTypeSpecifier()) {
16074       // If we evaluated the type to a record type, suggest putting
16075       // a tag in front.
16076       if (const RecordType *RT = T->getAs<RecordType>()) {
16077         RecordDecl *RD = RT->getDecl();
16078 
16079         SmallString<16> InsertionText(" ");
16080         InsertionText += RD->getKindName();
16081 
16082         Diag(TypeRange.getBegin(),
16083              getLangOpts().CPlusPlus11 ?
16084                diag::warn_cxx98_compat_unelaborated_friend_type :
16085                diag::ext_unelaborated_friend_type)
16086           << (unsigned) RD->getTagKind()
16087           << T
16088           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16089                                         InsertionText);
16090       } else {
16091         Diag(FriendLoc,
16092              getLangOpts().CPlusPlus11 ?
16093                diag::warn_cxx98_compat_nonclass_type_friend :
16094                diag::ext_nonclass_type_friend)
16095           << T
16096           << TypeRange;
16097       }
16098     } else if (T->getAs<EnumType>()) {
16099       Diag(FriendLoc,
16100            getLangOpts().CPlusPlus11 ?
16101              diag::warn_cxx98_compat_enum_friend :
16102              diag::ext_enum_friend)
16103         << T
16104         << TypeRange;
16105     }
16106 
16107     // C++11 [class.friend]p3:
16108     //   A friend declaration that does not declare a function shall have one
16109     //   of the following forms:
16110     //     friend elaborated-type-specifier ;
16111     //     friend simple-type-specifier ;
16112     //     friend typename-specifier ;
16113     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16114       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16115   }
16116 
16117   //   If the type specifier in a friend declaration designates a (possibly
16118   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16119   //   the friend declaration is ignored.
16120   return FriendDecl::Create(Context, CurContext,
16121                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16122                             FriendLoc);
16123 }
16124 
16125 /// Handle a friend tag declaration where the scope specifier was
16126 /// templated.
16127 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16128                                     unsigned TagSpec, SourceLocation TagLoc,
16129                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16130                                     SourceLocation NameLoc,
16131                                     const ParsedAttributesView &Attr,
16132                                     MultiTemplateParamsArg TempParamLists) {
16133   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16134 
16135   bool IsMemberSpecialization = false;
16136   bool Invalid = false;
16137 
16138   if (TemplateParameterList *TemplateParams =
16139           MatchTemplateParametersToScopeSpecifier(
16140               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16141               IsMemberSpecialization, Invalid)) {
16142     if (TemplateParams->size() > 0) {
16143       // This is a declaration of a class template.
16144       if (Invalid)
16145         return nullptr;
16146 
16147       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16148                                 NameLoc, Attr, TemplateParams, AS_public,
16149                                 /*ModulePrivateLoc=*/SourceLocation(),
16150                                 FriendLoc, TempParamLists.size() - 1,
16151                                 TempParamLists.data()).get();
16152     } else {
16153       // The "template<>" header is extraneous.
16154       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16155         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16156       IsMemberSpecialization = true;
16157     }
16158   }
16159 
16160   if (Invalid) return nullptr;
16161 
16162   bool isAllExplicitSpecializations = true;
16163   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16164     if (TempParamLists[I]->size()) {
16165       isAllExplicitSpecializations = false;
16166       break;
16167     }
16168   }
16169 
16170   // FIXME: don't ignore attributes.
16171 
16172   // If it's explicit specializations all the way down, just forget
16173   // about the template header and build an appropriate non-templated
16174   // friend.  TODO: for source fidelity, remember the headers.
16175   if (isAllExplicitSpecializations) {
16176     if (SS.isEmpty()) {
16177       bool Owned = false;
16178       bool IsDependent = false;
16179       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16180                       Attr, AS_public,
16181                       /*ModulePrivateLoc=*/SourceLocation(),
16182                       MultiTemplateParamsArg(), Owned, IsDependent,
16183                       /*ScopedEnumKWLoc=*/SourceLocation(),
16184                       /*ScopedEnumUsesClassTag=*/false,
16185                       /*UnderlyingType=*/TypeResult(),
16186                       /*IsTypeSpecifier=*/false,
16187                       /*IsTemplateParamOrArg=*/false);
16188     }
16189 
16190     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16191     ElaboratedTypeKeyword Keyword
16192       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16193     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16194                                    *Name, NameLoc);
16195     if (T.isNull())
16196       return nullptr;
16197 
16198     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16199     if (isa<DependentNameType>(T)) {
16200       DependentNameTypeLoc TL =
16201           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16202       TL.setElaboratedKeywordLoc(TagLoc);
16203       TL.setQualifierLoc(QualifierLoc);
16204       TL.setNameLoc(NameLoc);
16205     } else {
16206       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16207       TL.setElaboratedKeywordLoc(TagLoc);
16208       TL.setQualifierLoc(QualifierLoc);
16209       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16210     }
16211 
16212     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16213                                             TSI, FriendLoc, TempParamLists);
16214     Friend->setAccess(AS_public);
16215     CurContext->addDecl(Friend);
16216     return Friend;
16217   }
16218 
16219   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16220 
16221 
16222 
16223   // Handle the case of a templated-scope friend class.  e.g.
16224   //   template <class T> class A<T>::B;
16225   // FIXME: we don't support these right now.
16226   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16227     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16228   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16229   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16230   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16231   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16232   TL.setElaboratedKeywordLoc(TagLoc);
16233   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16234   TL.setNameLoc(NameLoc);
16235 
16236   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16237                                           TSI, FriendLoc, TempParamLists);
16238   Friend->setAccess(AS_public);
16239   Friend->setUnsupportedFriend(true);
16240   CurContext->addDecl(Friend);
16241   return Friend;
16242 }
16243 
16244 /// Handle a friend type declaration.  This works in tandem with
16245 /// ActOnTag.
16246 ///
16247 /// Notes on friend class templates:
16248 ///
16249 /// We generally treat friend class declarations as if they were
16250 /// declaring a class.  So, for example, the elaborated type specifier
16251 /// in a friend declaration is required to obey the restrictions of a
16252 /// class-head (i.e. no typedefs in the scope chain), template
16253 /// parameters are required to match up with simple template-ids, &c.
16254 /// However, unlike when declaring a template specialization, it's
16255 /// okay to refer to a template specialization without an empty
16256 /// template parameter declaration, e.g.
16257 ///   friend class A<T>::B<unsigned>;
16258 /// We permit this as a special case; if there are any template
16259 /// parameters present at all, require proper matching, i.e.
16260 ///   template <> template \<class T> friend class A<int>::B;
16261 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16262                                 MultiTemplateParamsArg TempParams) {
16263   SourceLocation Loc = DS.getBeginLoc();
16264 
16265   assert(DS.isFriendSpecified());
16266   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16267 
16268   // C++ [class.friend]p3:
16269   // A friend declaration that does not declare a function shall have one of
16270   // the following forms:
16271   //     friend elaborated-type-specifier ;
16272   //     friend simple-type-specifier ;
16273   //     friend typename-specifier ;
16274   //
16275   // Any declaration with a type qualifier does not have that form. (It's
16276   // legal to specify a qualified type as a friend, you just can't write the
16277   // keywords.)
16278   if (DS.getTypeQualifiers()) {
16279     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16280       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16281     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16282       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16283     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16284       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16285     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16286       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16287     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16288       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16289   }
16290 
16291   // Try to convert the decl specifier to a type.  This works for
16292   // friend templates because ActOnTag never produces a ClassTemplateDecl
16293   // for a TUK_Friend.
16294   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16295   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16296   QualType T = TSI->getType();
16297   if (TheDeclarator.isInvalidType())
16298     return nullptr;
16299 
16300   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16301     return nullptr;
16302 
16303   // This is definitely an error in C++98.  It's probably meant to
16304   // be forbidden in C++0x, too, but the specification is just
16305   // poorly written.
16306   //
16307   // The problem is with declarations like the following:
16308   //   template <T> friend A<T>::foo;
16309   // where deciding whether a class C is a friend or not now hinges
16310   // on whether there exists an instantiation of A that causes
16311   // 'foo' to equal C.  There are restrictions on class-heads
16312   // (which we declare (by fiat) elaborated friend declarations to
16313   // be) that makes this tractable.
16314   //
16315   // FIXME: handle "template <> friend class A<T>;", which
16316   // is possibly well-formed?  Who even knows?
16317   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16318     Diag(Loc, diag::err_tagless_friend_type_template)
16319       << DS.getSourceRange();
16320     return nullptr;
16321   }
16322 
16323   // C++98 [class.friend]p1: A friend of a class is a function
16324   //   or class that is not a member of the class . . .
16325   // This is fixed in DR77, which just barely didn't make the C++03
16326   // deadline.  It's also a very silly restriction that seriously
16327   // affects inner classes and which nobody else seems to implement;
16328   // thus we never diagnose it, not even in -pedantic.
16329   //
16330   // But note that we could warn about it: it's always useless to
16331   // friend one of your own members (it's not, however, worthless to
16332   // friend a member of an arbitrary specialization of your template).
16333 
16334   Decl *D;
16335   if (!TempParams.empty())
16336     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16337                                    TempParams,
16338                                    TSI,
16339                                    DS.getFriendSpecLoc());
16340   else
16341     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16342 
16343   if (!D)
16344     return nullptr;
16345 
16346   D->setAccess(AS_public);
16347   CurContext->addDecl(D);
16348 
16349   return D;
16350 }
16351 
16352 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16353                                         MultiTemplateParamsArg TemplateParams) {
16354   const DeclSpec &DS = D.getDeclSpec();
16355 
16356   assert(DS.isFriendSpecified());
16357   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16358 
16359   SourceLocation Loc = D.getIdentifierLoc();
16360   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16361 
16362   // C++ [class.friend]p1
16363   //   A friend of a class is a function or class....
16364   // Note that this sees through typedefs, which is intended.
16365   // It *doesn't* see through dependent types, which is correct
16366   // according to [temp.arg.type]p3:
16367   //   If a declaration acquires a function type through a
16368   //   type dependent on a template-parameter and this causes
16369   //   a declaration that does not use the syntactic form of a
16370   //   function declarator to have a function type, the program
16371   //   is ill-formed.
16372   if (!TInfo->getType()->isFunctionType()) {
16373     Diag(Loc, diag::err_unexpected_friend);
16374 
16375     // It might be worthwhile to try to recover by creating an
16376     // appropriate declaration.
16377     return nullptr;
16378   }
16379 
16380   // C++ [namespace.memdef]p3
16381   //  - If a friend declaration in a non-local class first declares a
16382   //    class or function, the friend class or function is a member
16383   //    of the innermost enclosing namespace.
16384   //  - The name of the friend is not found by simple name lookup
16385   //    until a matching declaration is provided in that namespace
16386   //    scope (either before or after the class declaration granting
16387   //    friendship).
16388   //  - If a friend function is called, its name may be found by the
16389   //    name lookup that considers functions from namespaces and
16390   //    classes associated with the types of the function arguments.
16391   //  - When looking for a prior declaration of a class or a function
16392   //    declared as a friend, scopes outside the innermost enclosing
16393   //    namespace scope are not considered.
16394 
16395   CXXScopeSpec &SS = D.getCXXScopeSpec();
16396   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16397   assert(NameInfo.getName());
16398 
16399   // Check for unexpanded parameter packs.
16400   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16401       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16402       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16403     return nullptr;
16404 
16405   // The context we found the declaration in, or in which we should
16406   // create the declaration.
16407   DeclContext *DC;
16408   Scope *DCScope = S;
16409   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16410                         ForExternalRedeclaration);
16411 
16412   // There are five cases here.
16413   //   - There's no scope specifier and we're in a local class. Only look
16414   //     for functions declared in the immediately-enclosing block scope.
16415   // We recover from invalid scope qualifiers as if they just weren't there.
16416   FunctionDecl *FunctionContainingLocalClass = nullptr;
16417   if ((SS.isInvalid() || !SS.isSet()) &&
16418       (FunctionContainingLocalClass =
16419            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16420     // C++11 [class.friend]p11:
16421     //   If a friend declaration appears in a local class and the name
16422     //   specified is an unqualified name, a prior declaration is
16423     //   looked up without considering scopes that are outside the
16424     //   innermost enclosing non-class scope. For a friend function
16425     //   declaration, if there is no prior declaration, the program is
16426     //   ill-formed.
16427 
16428     // Find the innermost enclosing non-class scope. This is the block
16429     // scope containing the local class definition (or for a nested class,
16430     // the outer local class).
16431     DCScope = S->getFnParent();
16432 
16433     // Look up the function name in the scope.
16434     Previous.clear(LookupLocalFriendName);
16435     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16436 
16437     if (!Previous.empty()) {
16438       // All possible previous declarations must have the same context:
16439       // either they were declared at block scope or they are members of
16440       // one of the enclosing local classes.
16441       DC = Previous.getRepresentativeDecl()->getDeclContext();
16442     } else {
16443       // This is ill-formed, but provide the context that we would have
16444       // declared the function in, if we were permitted to, for error recovery.
16445       DC = FunctionContainingLocalClass;
16446     }
16447     adjustContextForLocalExternDecl(DC);
16448 
16449     // C++ [class.friend]p6:
16450     //   A function can be defined in a friend declaration of a class if and
16451     //   only if the class is a non-local class (9.8), the function name is
16452     //   unqualified, and the function has namespace scope.
16453     if (D.isFunctionDefinition()) {
16454       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16455     }
16456 
16457   //   - There's no scope specifier, in which case we just go to the
16458   //     appropriate scope and look for a function or function template
16459   //     there as appropriate.
16460   } else if (SS.isInvalid() || !SS.isSet()) {
16461     // C++11 [namespace.memdef]p3:
16462     //   If the name in a friend declaration is neither qualified nor
16463     //   a template-id and the declaration is a function or an
16464     //   elaborated-type-specifier, the lookup to determine whether
16465     //   the entity has been previously declared shall not consider
16466     //   any scopes outside the innermost enclosing namespace.
16467     bool isTemplateId =
16468         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16469 
16470     // Find the appropriate context according to the above.
16471     DC = CurContext;
16472 
16473     // Skip class contexts.  If someone can cite chapter and verse
16474     // for this behavior, that would be nice --- it's what GCC and
16475     // EDG do, and it seems like a reasonable intent, but the spec
16476     // really only says that checks for unqualified existing
16477     // declarations should stop at the nearest enclosing namespace,
16478     // not that they should only consider the nearest enclosing
16479     // namespace.
16480     while (DC->isRecord())
16481       DC = DC->getParent();
16482 
16483     DeclContext *LookupDC = DC;
16484     while (LookupDC->isTransparentContext())
16485       LookupDC = LookupDC->getParent();
16486 
16487     while (true) {
16488       LookupQualifiedName(Previous, LookupDC);
16489 
16490       if (!Previous.empty()) {
16491         DC = LookupDC;
16492         break;
16493       }
16494 
16495       if (isTemplateId) {
16496         if (isa<TranslationUnitDecl>(LookupDC)) break;
16497       } else {
16498         if (LookupDC->isFileContext()) break;
16499       }
16500       LookupDC = LookupDC->getParent();
16501     }
16502 
16503     DCScope = getScopeForDeclContext(S, DC);
16504 
16505   //   - There's a non-dependent scope specifier, in which case we
16506   //     compute it and do a previous lookup there for a function
16507   //     or function template.
16508   } else if (!SS.getScopeRep()->isDependent()) {
16509     DC = computeDeclContext(SS);
16510     if (!DC) return nullptr;
16511 
16512     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16513 
16514     LookupQualifiedName(Previous, DC);
16515 
16516     // C++ [class.friend]p1: A friend of a class is a function or
16517     //   class that is not a member of the class . . .
16518     if (DC->Equals(CurContext))
16519       Diag(DS.getFriendSpecLoc(),
16520            getLangOpts().CPlusPlus11 ?
16521              diag::warn_cxx98_compat_friend_is_member :
16522              diag::err_friend_is_member);
16523 
16524     if (D.isFunctionDefinition()) {
16525       // C++ [class.friend]p6:
16526       //   A function can be defined in a friend declaration of a class if and
16527       //   only if the class is a non-local class (9.8), the function name is
16528       //   unqualified, and the function has namespace scope.
16529       //
16530       // FIXME: We should only do this if the scope specifier names the
16531       // innermost enclosing namespace; otherwise the fixit changes the
16532       // meaning of the code.
16533       SemaDiagnosticBuilder DB
16534         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16535 
16536       DB << SS.getScopeRep();
16537       if (DC->isFileContext())
16538         DB << FixItHint::CreateRemoval(SS.getRange());
16539       SS.clear();
16540     }
16541 
16542   //   - There's a scope specifier that does not match any template
16543   //     parameter lists, in which case we use some arbitrary context,
16544   //     create a method or method template, and wait for instantiation.
16545   //   - There's a scope specifier that does match some template
16546   //     parameter lists, which we don't handle right now.
16547   } else {
16548     if (D.isFunctionDefinition()) {
16549       // C++ [class.friend]p6:
16550       //   A function can be defined in a friend declaration of a class if and
16551       //   only if the class is a non-local class (9.8), the function name is
16552       //   unqualified, and the function has namespace scope.
16553       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16554         << SS.getScopeRep();
16555     }
16556 
16557     DC = CurContext;
16558     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16559   }
16560 
16561   if (!DC->isRecord()) {
16562     int DiagArg = -1;
16563     switch (D.getName().getKind()) {
16564     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16565     case UnqualifiedIdKind::IK_ConstructorName:
16566       DiagArg = 0;
16567       break;
16568     case UnqualifiedIdKind::IK_DestructorName:
16569       DiagArg = 1;
16570       break;
16571     case UnqualifiedIdKind::IK_ConversionFunctionId:
16572       DiagArg = 2;
16573       break;
16574     case UnqualifiedIdKind::IK_DeductionGuideName:
16575       DiagArg = 3;
16576       break;
16577     case UnqualifiedIdKind::IK_Identifier:
16578     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16579     case UnqualifiedIdKind::IK_LiteralOperatorId:
16580     case UnqualifiedIdKind::IK_OperatorFunctionId:
16581     case UnqualifiedIdKind::IK_TemplateId:
16582       break;
16583     }
16584     // This implies that it has to be an operator or function.
16585     if (DiagArg >= 0) {
16586       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16587       return nullptr;
16588     }
16589   }
16590 
16591   // FIXME: This is an egregious hack to cope with cases where the scope stack
16592   // does not contain the declaration context, i.e., in an out-of-line
16593   // definition of a class.
16594   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16595   if (!DCScope) {
16596     FakeDCScope.setEntity(DC);
16597     DCScope = &FakeDCScope;
16598   }
16599 
16600   bool AddToScope = true;
16601   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16602                                           TemplateParams, AddToScope);
16603   if (!ND) return nullptr;
16604 
16605   assert(ND->getLexicalDeclContext() == CurContext);
16606 
16607   // If we performed typo correction, we might have added a scope specifier
16608   // and changed the decl context.
16609   DC = ND->getDeclContext();
16610 
16611   // Add the function declaration to the appropriate lookup tables,
16612   // adjusting the redeclarations list as necessary.  We don't
16613   // want to do this yet if the friending class is dependent.
16614   //
16615   // Also update the scope-based lookup if the target context's
16616   // lookup context is in lexical scope.
16617   if (!CurContext->isDependentContext()) {
16618     DC = DC->getRedeclContext();
16619     DC->makeDeclVisibleInContext(ND);
16620     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16621       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16622   }
16623 
16624   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16625                                        D.getIdentifierLoc(), ND,
16626                                        DS.getFriendSpecLoc());
16627   FrD->setAccess(AS_public);
16628   CurContext->addDecl(FrD);
16629 
16630   if (ND->isInvalidDecl()) {
16631     FrD->setInvalidDecl();
16632   } else {
16633     if (DC->isRecord()) CheckFriendAccess(ND);
16634 
16635     FunctionDecl *FD;
16636     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16637       FD = FTD->getTemplatedDecl();
16638     else
16639       FD = cast<FunctionDecl>(ND);
16640 
16641     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16642     // default argument expression, that declaration shall be a definition
16643     // and shall be the only declaration of the function or function
16644     // template in the translation unit.
16645     if (functionDeclHasDefaultArgument(FD)) {
16646       // We can't look at FD->getPreviousDecl() because it may not have been set
16647       // if we're in a dependent context. If the function is known to be a
16648       // redeclaration, we will have narrowed Previous down to the right decl.
16649       if (D.isRedeclaration()) {
16650         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16651         Diag(Previous.getRepresentativeDecl()->getLocation(),
16652              diag::note_previous_declaration);
16653       } else if (!D.isFunctionDefinition())
16654         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16655     }
16656 
16657     // Mark templated-scope function declarations as unsupported.
16658     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16659       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16660         << SS.getScopeRep() << SS.getRange()
16661         << cast<CXXRecordDecl>(CurContext);
16662       FrD->setUnsupportedFriend(true);
16663     }
16664   }
16665 
16666   return ND;
16667 }
16668 
16669 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16670   AdjustDeclIfTemplate(Dcl);
16671 
16672   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16673   if (!Fn) {
16674     Diag(DelLoc, diag::err_deleted_non_function);
16675     return;
16676   }
16677 
16678   // Deleted function does not have a body.
16679   Fn->setWillHaveBody(false);
16680 
16681   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16682     // Don't consider the implicit declaration we generate for explicit
16683     // specializations. FIXME: Do not generate these implicit declarations.
16684     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16685          Prev->getPreviousDecl()) &&
16686         !Prev->isDefined()) {
16687       Diag(DelLoc, diag::err_deleted_decl_not_first);
16688       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16689            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16690                               : diag::note_previous_declaration);
16691       // We can't recover from this; the declaration might have already
16692       // been used.
16693       Fn->setInvalidDecl();
16694       return;
16695     }
16696 
16697     // To maintain the invariant that functions are only deleted on their first
16698     // declaration, mark the implicitly-instantiated declaration of the
16699     // explicitly-specialized function as deleted instead of marking the
16700     // instantiated redeclaration.
16701     Fn = Fn->getCanonicalDecl();
16702   }
16703 
16704   // dllimport/dllexport cannot be deleted.
16705   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16706     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16707     Fn->setInvalidDecl();
16708   }
16709 
16710   // C++11 [basic.start.main]p3:
16711   //   A program that defines main as deleted [...] is ill-formed.
16712   if (Fn->isMain())
16713     Diag(DelLoc, diag::err_deleted_main);
16714 
16715   // C++11 [dcl.fct.def.delete]p4:
16716   //  A deleted function is implicitly inline.
16717   Fn->setImplicitlyInline();
16718   Fn->setDeletedAsWritten();
16719 }
16720 
16721 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16722   if (!Dcl || Dcl->isInvalidDecl())
16723     return;
16724 
16725   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16726   if (!FD) {
16727     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16728       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16729         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16730         return;
16731       }
16732     }
16733 
16734     Diag(DefaultLoc, diag::err_default_special_members)
16735         << getLangOpts().CPlusPlus20;
16736     return;
16737   }
16738 
16739   // Reject if this can't possibly be a defaultable function.
16740   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16741   if (!DefKind &&
16742       // A dependent function that doesn't locally look defaultable can
16743       // still instantiate to a defaultable function if it's a constructor
16744       // or assignment operator.
16745       (!FD->isDependentContext() ||
16746        (!isa<CXXConstructorDecl>(FD) &&
16747         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16748     Diag(DefaultLoc, diag::err_default_special_members)
16749         << getLangOpts().CPlusPlus20;
16750     return;
16751   }
16752 
16753   if (DefKind.isComparison() &&
16754       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16755     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16756         << (int)DefKind.asComparison();
16757     return;
16758   }
16759 
16760   // Issue compatibility warning. We already warned if the operator is
16761   // 'operator<=>' when parsing the '<=>' token.
16762   if (DefKind.isComparison() &&
16763       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16764     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16765                          ? diag::warn_cxx17_compat_defaulted_comparison
16766                          : diag::ext_defaulted_comparison);
16767   }
16768 
16769   FD->setDefaulted();
16770   FD->setExplicitlyDefaulted();
16771 
16772   // Defer checking functions that are defaulted in a dependent context.
16773   if (FD->isDependentContext())
16774     return;
16775 
16776   // Unset that we will have a body for this function. We might not,
16777   // if it turns out to be trivial, and we don't need this marking now
16778   // that we've marked it as defaulted.
16779   FD->setWillHaveBody(false);
16780 
16781   // If this definition appears within the record, do the checking when
16782   // the record is complete. This is always the case for a defaulted
16783   // comparison.
16784   if (DefKind.isComparison())
16785     return;
16786   auto *MD = cast<CXXMethodDecl>(FD);
16787 
16788   const FunctionDecl *Primary = FD;
16789   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16790     // Ask the template instantiation pattern that actually had the
16791     // '= default' on it.
16792     Primary = Pattern;
16793 
16794   // If the method was defaulted on its first declaration, we will have
16795   // already performed the checking in CheckCompletedCXXClass. Such a
16796   // declaration doesn't trigger an implicit definition.
16797   if (Primary->getCanonicalDecl()->isDefaulted())
16798     return;
16799 
16800   // FIXME: Once we support defining comparisons out of class, check for a
16801   // defaulted comparison here.
16802   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16803     MD->setInvalidDecl();
16804   else
16805     DefineDefaultedFunction(*this, MD, DefaultLoc);
16806 }
16807 
16808 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16809   for (Stmt *SubStmt : S->children()) {
16810     if (!SubStmt)
16811       continue;
16812     if (isa<ReturnStmt>(SubStmt))
16813       Self.Diag(SubStmt->getBeginLoc(),
16814                 diag::err_return_in_constructor_handler);
16815     if (!isa<Expr>(SubStmt))
16816       SearchForReturnInStmt(Self, SubStmt);
16817   }
16818 }
16819 
16820 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16821   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16822     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16823     SearchForReturnInStmt(*this, Handler);
16824   }
16825 }
16826 
16827 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16828                                              const CXXMethodDecl *Old) {
16829   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16830   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16831 
16832   if (OldFT->hasExtParameterInfos()) {
16833     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16834       // A parameter of the overriding method should be annotated with noescape
16835       // if the corresponding parameter of the overridden method is annotated.
16836       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16837           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16838         Diag(New->getParamDecl(I)->getLocation(),
16839              diag::warn_overriding_method_missing_noescape);
16840         Diag(Old->getParamDecl(I)->getLocation(),
16841              diag::note_overridden_marked_noescape);
16842       }
16843   }
16844 
16845   // Virtual overrides must have the same code_seg.
16846   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16847   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16848   if ((NewCSA || OldCSA) &&
16849       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16850     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16851     Diag(Old->getLocation(), diag::note_previous_declaration);
16852     return true;
16853   }
16854 
16855   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16856 
16857   // If the calling conventions match, everything is fine
16858   if (NewCC == OldCC)
16859     return false;
16860 
16861   // If the calling conventions mismatch because the new function is static,
16862   // suppress the calling convention mismatch error; the error about static
16863   // function override (err_static_overrides_virtual from
16864   // Sema::CheckFunctionDeclaration) is more clear.
16865   if (New->getStorageClass() == SC_Static)
16866     return false;
16867 
16868   Diag(New->getLocation(),
16869        diag::err_conflicting_overriding_cc_attributes)
16870     << New->getDeclName() << New->getType() << Old->getType();
16871   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16872   return true;
16873 }
16874 
16875 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16876                                              const CXXMethodDecl *Old) {
16877   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16878   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16879 
16880   if (Context.hasSameType(NewTy, OldTy) ||
16881       NewTy->isDependentType() || OldTy->isDependentType())
16882     return false;
16883 
16884   // Check if the return types are covariant
16885   QualType NewClassTy, OldClassTy;
16886 
16887   /// Both types must be pointers or references to classes.
16888   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16889     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16890       NewClassTy = NewPT->getPointeeType();
16891       OldClassTy = OldPT->getPointeeType();
16892     }
16893   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16894     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16895       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16896         NewClassTy = NewRT->getPointeeType();
16897         OldClassTy = OldRT->getPointeeType();
16898       }
16899     }
16900   }
16901 
16902   // The return types aren't either both pointers or references to a class type.
16903   if (NewClassTy.isNull()) {
16904     Diag(New->getLocation(),
16905          diag::err_different_return_type_for_overriding_virtual_function)
16906         << New->getDeclName() << NewTy << OldTy
16907         << New->getReturnTypeSourceRange();
16908     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16909         << Old->getReturnTypeSourceRange();
16910 
16911     return true;
16912   }
16913 
16914   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16915     // C++14 [class.virtual]p8:
16916     //   If the class type in the covariant return type of D::f differs from
16917     //   that of B::f, the class type in the return type of D::f shall be
16918     //   complete at the point of declaration of D::f or shall be the class
16919     //   type D.
16920     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16921       if (!RT->isBeingDefined() &&
16922           RequireCompleteType(New->getLocation(), NewClassTy,
16923                               diag::err_covariant_return_incomplete,
16924                               New->getDeclName()))
16925         return true;
16926     }
16927 
16928     // Check if the new class derives from the old class.
16929     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16930       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16931           << New->getDeclName() << NewTy << OldTy
16932           << New->getReturnTypeSourceRange();
16933       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16934           << Old->getReturnTypeSourceRange();
16935       return true;
16936     }
16937 
16938     // Check if we the conversion from derived to base is valid.
16939     if (CheckDerivedToBaseConversion(
16940             NewClassTy, OldClassTy,
16941             diag::err_covariant_return_inaccessible_base,
16942             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16943             New->getLocation(), New->getReturnTypeSourceRange(),
16944             New->getDeclName(), nullptr)) {
16945       // FIXME: this note won't trigger for delayed access control
16946       // diagnostics, and it's impossible to get an undelayed error
16947       // here from access control during the original parse because
16948       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16949       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16950           << Old->getReturnTypeSourceRange();
16951       return true;
16952     }
16953   }
16954 
16955   // The qualifiers of the return types must be the same.
16956   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16957     Diag(New->getLocation(),
16958          diag::err_covariant_return_type_different_qualifications)
16959         << New->getDeclName() << NewTy << OldTy
16960         << New->getReturnTypeSourceRange();
16961     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16962         << Old->getReturnTypeSourceRange();
16963     return true;
16964   }
16965 
16966 
16967   // The new class type must have the same or less qualifiers as the old type.
16968   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16969     Diag(New->getLocation(),
16970          diag::err_covariant_return_type_class_type_more_qualified)
16971         << New->getDeclName() << NewTy << OldTy
16972         << New->getReturnTypeSourceRange();
16973     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16974         << Old->getReturnTypeSourceRange();
16975     return true;
16976   }
16977 
16978   return false;
16979 }
16980 
16981 /// Mark the given method pure.
16982 ///
16983 /// \param Method the method to be marked pure.
16984 ///
16985 /// \param InitRange the source range that covers the "0" initializer.
16986 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16987   SourceLocation EndLoc = InitRange.getEnd();
16988   if (EndLoc.isValid())
16989     Method->setRangeEnd(EndLoc);
16990 
16991   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16992     Method->setPure();
16993     return false;
16994   }
16995 
16996   if (!Method->isInvalidDecl())
16997     Diag(Method->getLocation(), diag::err_non_virtual_pure)
16998       << Method->getDeclName() << InitRange;
16999   return true;
17000 }
17001 
17002 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17003   if (D->getFriendObjectKind())
17004     Diag(D->getLocation(), diag::err_pure_friend);
17005   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17006     CheckPureMethod(M, ZeroLoc);
17007   else
17008     Diag(D->getLocation(), diag::err_illegal_initializer);
17009 }
17010 
17011 /// Determine whether the given declaration is a global variable or
17012 /// static data member.
17013 static bool isNonlocalVariable(const Decl *D) {
17014   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17015     return Var->hasGlobalStorage();
17016 
17017   return false;
17018 }
17019 
17020 /// Invoked when we are about to parse an initializer for the declaration
17021 /// 'Dcl'.
17022 ///
17023 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17024 /// static data member of class X, names should be looked up in the scope of
17025 /// class X. If the declaration had a scope specifier, a scope will have
17026 /// been created and passed in for this purpose. Otherwise, S will be null.
17027 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17028   // If there is no declaration, there was an error parsing it.
17029   if (!D || D->isInvalidDecl())
17030     return;
17031 
17032   // We will always have a nested name specifier here, but this declaration
17033   // might not be out of line if the specifier names the current namespace:
17034   //   extern int n;
17035   //   int ::n = 0;
17036   if (S && D->isOutOfLine())
17037     EnterDeclaratorContext(S, D->getDeclContext());
17038 
17039   // If we are parsing the initializer for a static data member, push a
17040   // new expression evaluation context that is associated with this static
17041   // data member.
17042   if (isNonlocalVariable(D))
17043     PushExpressionEvaluationContext(
17044         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17045 }
17046 
17047 /// Invoked after we are finished parsing an initializer for the declaration D.
17048 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17049   // If there is no declaration, there was an error parsing it.
17050   if (!D || D->isInvalidDecl())
17051     return;
17052 
17053   if (isNonlocalVariable(D))
17054     PopExpressionEvaluationContext();
17055 
17056   if (S && D->isOutOfLine())
17057     ExitDeclaratorContext(S);
17058 }
17059 
17060 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17061 /// C++ if/switch/while/for statement.
17062 /// e.g: "if (int x = f()) {...}"
17063 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17064   // C++ 6.4p2:
17065   // The declarator shall not specify a function or an array.
17066   // The type-specifier-seq shall not contain typedef and shall not declare a
17067   // new class or enumeration.
17068   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17069          "Parser allowed 'typedef' as storage class of condition decl.");
17070 
17071   Decl *Dcl = ActOnDeclarator(S, D);
17072   if (!Dcl)
17073     return true;
17074 
17075   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17076     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17077       << D.getSourceRange();
17078     return true;
17079   }
17080 
17081   return Dcl;
17082 }
17083 
17084 void Sema::LoadExternalVTableUses() {
17085   if (!ExternalSource)
17086     return;
17087 
17088   SmallVector<ExternalVTableUse, 4> VTables;
17089   ExternalSource->ReadUsedVTables(VTables);
17090   SmallVector<VTableUse, 4> NewUses;
17091   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17092     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17093       = VTablesUsed.find(VTables[I].Record);
17094     // Even if a definition wasn't required before, it may be required now.
17095     if (Pos != VTablesUsed.end()) {
17096       if (!Pos->second && VTables[I].DefinitionRequired)
17097         Pos->second = true;
17098       continue;
17099     }
17100 
17101     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17102     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17103   }
17104 
17105   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17106 }
17107 
17108 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17109                           bool DefinitionRequired) {
17110   // Ignore any vtable uses in unevaluated operands or for classes that do
17111   // not have a vtable.
17112   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17113       CurContext->isDependentContext() || isUnevaluatedContext())
17114     return;
17115   // Do not mark as used if compiling for the device outside of the target
17116   // region.
17117   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17118       !isInOpenMPDeclareTargetContext() &&
17119       !isInOpenMPTargetExecutionDirective()) {
17120     if (!DefinitionRequired)
17121       MarkVirtualMembersReferenced(Loc, Class);
17122     return;
17123   }
17124 
17125   // Try to insert this class into the map.
17126   LoadExternalVTableUses();
17127   Class = Class->getCanonicalDecl();
17128   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17129     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17130   if (!Pos.second) {
17131     // If we already had an entry, check to see if we are promoting this vtable
17132     // to require a definition. If so, we need to reappend to the VTableUses
17133     // list, since we may have already processed the first entry.
17134     if (DefinitionRequired && !Pos.first->second) {
17135       Pos.first->second = true;
17136     } else {
17137       // Otherwise, we can early exit.
17138       return;
17139     }
17140   } else {
17141     // The Microsoft ABI requires that we perform the destructor body
17142     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17143     // the deleting destructor is emitted with the vtable, not with the
17144     // destructor definition as in the Itanium ABI.
17145     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17146       CXXDestructorDecl *DD = Class->getDestructor();
17147       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17148         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17149           // If this is an out-of-line declaration, marking it referenced will
17150           // not do anything. Manually call CheckDestructor to look up operator
17151           // delete().
17152           ContextRAII SavedContext(*this, DD);
17153           CheckDestructor(DD);
17154         } else {
17155           MarkFunctionReferenced(Loc, Class->getDestructor());
17156         }
17157       }
17158     }
17159   }
17160 
17161   // Local classes need to have their virtual members marked
17162   // immediately. For all other classes, we mark their virtual members
17163   // at the end of the translation unit.
17164   if (Class->isLocalClass())
17165     MarkVirtualMembersReferenced(Loc, Class);
17166   else
17167     VTableUses.push_back(std::make_pair(Class, Loc));
17168 }
17169 
17170 bool Sema::DefineUsedVTables() {
17171   LoadExternalVTableUses();
17172   if (VTableUses.empty())
17173     return false;
17174 
17175   // Note: The VTableUses vector could grow as a result of marking
17176   // the members of a class as "used", so we check the size each
17177   // time through the loop and prefer indices (which are stable) to
17178   // iterators (which are not).
17179   bool DefinedAnything = false;
17180   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17181     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17182     if (!Class)
17183       continue;
17184     TemplateSpecializationKind ClassTSK =
17185         Class->getTemplateSpecializationKind();
17186 
17187     SourceLocation Loc = VTableUses[I].second;
17188 
17189     bool DefineVTable = true;
17190 
17191     // If this class has a key function, but that key function is
17192     // defined in another translation unit, we don't need to emit the
17193     // vtable even though we're using it.
17194     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17195     if (KeyFunction && !KeyFunction->hasBody()) {
17196       // The key function is in another translation unit.
17197       DefineVTable = false;
17198       TemplateSpecializationKind TSK =
17199           KeyFunction->getTemplateSpecializationKind();
17200       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17201              TSK != TSK_ImplicitInstantiation &&
17202              "Instantiations don't have key functions");
17203       (void)TSK;
17204     } else if (!KeyFunction) {
17205       // If we have a class with no key function that is the subject
17206       // of an explicit instantiation declaration, suppress the
17207       // vtable; it will live with the explicit instantiation
17208       // definition.
17209       bool IsExplicitInstantiationDeclaration =
17210           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17211       for (auto R : Class->redecls()) {
17212         TemplateSpecializationKind TSK
17213           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17214         if (TSK == TSK_ExplicitInstantiationDeclaration)
17215           IsExplicitInstantiationDeclaration = true;
17216         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17217           IsExplicitInstantiationDeclaration = false;
17218           break;
17219         }
17220       }
17221 
17222       if (IsExplicitInstantiationDeclaration)
17223         DefineVTable = false;
17224     }
17225 
17226     // The exception specifications for all virtual members may be needed even
17227     // if we are not providing an authoritative form of the vtable in this TU.
17228     // We may choose to emit it available_externally anyway.
17229     if (!DefineVTable) {
17230       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17231       continue;
17232     }
17233 
17234     // Mark all of the virtual members of this class as referenced, so
17235     // that we can build a vtable. Then, tell the AST consumer that a
17236     // vtable for this class is required.
17237     DefinedAnything = true;
17238     MarkVirtualMembersReferenced(Loc, Class);
17239     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17240     if (VTablesUsed[Canonical])
17241       Consumer.HandleVTable(Class);
17242 
17243     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17244     // no key function or the key function is inlined. Don't warn in C++ ABIs
17245     // that lack key functions, since the user won't be able to make one.
17246     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17247         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17248       const FunctionDecl *KeyFunctionDef = nullptr;
17249       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17250                            KeyFunctionDef->isInlined())) {
17251         Diag(Class->getLocation(),
17252              ClassTSK == TSK_ExplicitInstantiationDefinition
17253                  ? diag::warn_weak_template_vtable
17254                  : diag::warn_weak_vtable)
17255             << Class;
17256       }
17257     }
17258   }
17259   VTableUses.clear();
17260 
17261   return DefinedAnything;
17262 }
17263 
17264 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17265                                                  const CXXRecordDecl *RD) {
17266   for (const auto *I : RD->methods())
17267     if (I->isVirtual() && !I->isPure())
17268       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17269 }
17270 
17271 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17272                                         const CXXRecordDecl *RD,
17273                                         bool ConstexprOnly) {
17274   // Mark all functions which will appear in RD's vtable as used.
17275   CXXFinalOverriderMap FinalOverriders;
17276   RD->getFinalOverriders(FinalOverriders);
17277   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17278                                             E = FinalOverriders.end();
17279        I != E; ++I) {
17280     for (OverridingMethods::const_iterator OI = I->second.begin(),
17281                                            OE = I->second.end();
17282          OI != OE; ++OI) {
17283       assert(OI->second.size() > 0 && "no final overrider");
17284       CXXMethodDecl *Overrider = OI->second.front().Method;
17285 
17286       // C++ [basic.def.odr]p2:
17287       //   [...] A virtual member function is used if it is not pure. [...]
17288       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17289         MarkFunctionReferenced(Loc, Overrider);
17290     }
17291   }
17292 
17293   // Only classes that have virtual bases need a VTT.
17294   if (RD->getNumVBases() == 0)
17295     return;
17296 
17297   for (const auto &I : RD->bases()) {
17298     const auto *Base =
17299         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17300     if (Base->getNumVBases() == 0)
17301       continue;
17302     MarkVirtualMembersReferenced(Loc, Base);
17303   }
17304 }
17305 
17306 /// SetIvarInitializers - This routine builds initialization ASTs for the
17307 /// Objective-C implementation whose ivars need be initialized.
17308 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17309   if (!getLangOpts().CPlusPlus)
17310     return;
17311   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17312     SmallVector<ObjCIvarDecl*, 8> ivars;
17313     CollectIvarsToConstructOrDestruct(OID, ivars);
17314     if (ivars.empty())
17315       return;
17316     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17317     for (unsigned i = 0; i < ivars.size(); i++) {
17318       FieldDecl *Field = ivars[i];
17319       if (Field->isInvalidDecl())
17320         continue;
17321 
17322       CXXCtorInitializer *Member;
17323       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17324       InitializationKind InitKind =
17325         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17326 
17327       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17328       ExprResult MemberInit =
17329         InitSeq.Perform(*this, InitEntity, InitKind, None);
17330       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17331       // Note, MemberInit could actually come back empty if no initialization
17332       // is required (e.g., because it would call a trivial default constructor)
17333       if (!MemberInit.get() || MemberInit.isInvalid())
17334         continue;
17335 
17336       Member =
17337         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17338                                          SourceLocation(),
17339                                          MemberInit.getAs<Expr>(),
17340                                          SourceLocation());
17341       AllToInit.push_back(Member);
17342 
17343       // Be sure that the destructor is accessible and is marked as referenced.
17344       if (const RecordType *RecordTy =
17345               Context.getBaseElementType(Field->getType())
17346                   ->getAs<RecordType>()) {
17347         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17348         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17349           MarkFunctionReferenced(Field->getLocation(), Destructor);
17350           CheckDestructorAccess(Field->getLocation(), Destructor,
17351                             PDiag(diag::err_access_dtor_ivar)
17352                               << Context.getBaseElementType(Field->getType()));
17353         }
17354       }
17355     }
17356     ObjCImplementation->setIvarInitializers(Context,
17357                                             AllToInit.data(), AllToInit.size());
17358   }
17359 }
17360 
17361 static
17362 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17363                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17364                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17365                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17366                            Sema &S) {
17367   if (Ctor->isInvalidDecl())
17368     return;
17369 
17370   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17371 
17372   // Target may not be determinable yet, for instance if this is a dependent
17373   // call in an uninstantiated template.
17374   if (Target) {
17375     const FunctionDecl *FNTarget = nullptr;
17376     (void)Target->hasBody(FNTarget);
17377     Target = const_cast<CXXConstructorDecl*>(
17378       cast_or_null<CXXConstructorDecl>(FNTarget));
17379   }
17380 
17381   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17382                      // Avoid dereferencing a null pointer here.
17383                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17384 
17385   if (!Current.insert(Canonical).second)
17386     return;
17387 
17388   // We know that beyond here, we aren't chaining into a cycle.
17389   if (!Target || !Target->isDelegatingConstructor() ||
17390       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17391     Valid.insert(Current.begin(), Current.end());
17392     Current.clear();
17393   // We've hit a cycle.
17394   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17395              Current.count(TCanonical)) {
17396     // If we haven't diagnosed this cycle yet, do so now.
17397     if (!Invalid.count(TCanonical)) {
17398       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17399              diag::warn_delegating_ctor_cycle)
17400         << Ctor;
17401 
17402       // Don't add a note for a function delegating directly to itself.
17403       if (TCanonical != Canonical)
17404         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17405 
17406       CXXConstructorDecl *C = Target;
17407       while (C->getCanonicalDecl() != Canonical) {
17408         const FunctionDecl *FNTarget = nullptr;
17409         (void)C->getTargetConstructor()->hasBody(FNTarget);
17410         assert(FNTarget && "Ctor cycle through bodiless function");
17411 
17412         C = const_cast<CXXConstructorDecl*>(
17413           cast<CXXConstructorDecl>(FNTarget));
17414         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17415       }
17416     }
17417 
17418     Invalid.insert(Current.begin(), Current.end());
17419     Current.clear();
17420   } else {
17421     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17422   }
17423 }
17424 
17425 
17426 void Sema::CheckDelegatingCtorCycles() {
17427   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17428 
17429   for (DelegatingCtorDeclsType::iterator
17430          I = DelegatingCtorDecls.begin(ExternalSource),
17431          E = DelegatingCtorDecls.end();
17432        I != E; ++I)
17433     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17434 
17435   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17436     (*CI)->setInvalidDecl();
17437 }
17438 
17439 namespace {
17440   /// AST visitor that finds references to the 'this' expression.
17441   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17442     Sema &S;
17443 
17444   public:
17445     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17446 
17447     bool VisitCXXThisExpr(CXXThisExpr *E) {
17448       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17449         << E->isImplicit();
17450       return false;
17451     }
17452   };
17453 }
17454 
17455 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17456   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17457   if (!TSInfo)
17458     return false;
17459 
17460   TypeLoc TL = TSInfo->getTypeLoc();
17461   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17462   if (!ProtoTL)
17463     return false;
17464 
17465   // C++11 [expr.prim.general]p3:
17466   //   [The expression this] shall not appear before the optional
17467   //   cv-qualifier-seq and it shall not appear within the declaration of a
17468   //   static member function (although its type and value category are defined
17469   //   within a static member function as they are within a non-static member
17470   //   function). [ Note: this is because declaration matching does not occur
17471   //  until the complete declarator is known. - end note ]
17472   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17473   FindCXXThisExpr Finder(*this);
17474 
17475   // If the return type came after the cv-qualifier-seq, check it now.
17476   if (Proto->hasTrailingReturn() &&
17477       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17478     return true;
17479 
17480   // Check the exception specification.
17481   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17482     return true;
17483 
17484   // Check the trailing requires clause
17485   if (Expr *E = Method->getTrailingRequiresClause())
17486     if (!Finder.TraverseStmt(E))
17487       return true;
17488 
17489   return checkThisInStaticMemberFunctionAttributes(Method);
17490 }
17491 
17492 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17493   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17494   if (!TSInfo)
17495     return false;
17496 
17497   TypeLoc TL = TSInfo->getTypeLoc();
17498   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17499   if (!ProtoTL)
17500     return false;
17501 
17502   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17503   FindCXXThisExpr Finder(*this);
17504 
17505   switch (Proto->getExceptionSpecType()) {
17506   case EST_Unparsed:
17507   case EST_Uninstantiated:
17508   case EST_Unevaluated:
17509   case EST_BasicNoexcept:
17510   case EST_NoThrow:
17511   case EST_DynamicNone:
17512   case EST_MSAny:
17513   case EST_None:
17514     break;
17515 
17516   case EST_DependentNoexcept:
17517   case EST_NoexceptFalse:
17518   case EST_NoexceptTrue:
17519     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17520       return true;
17521     LLVM_FALLTHROUGH;
17522 
17523   case EST_Dynamic:
17524     for (const auto &E : Proto->exceptions()) {
17525       if (!Finder.TraverseType(E))
17526         return true;
17527     }
17528     break;
17529   }
17530 
17531   return false;
17532 }
17533 
17534 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17535   FindCXXThisExpr Finder(*this);
17536 
17537   // Check attributes.
17538   for (const auto *A : Method->attrs()) {
17539     // FIXME: This should be emitted by tblgen.
17540     Expr *Arg = nullptr;
17541     ArrayRef<Expr *> Args;
17542     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17543       Arg = G->getArg();
17544     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17545       Arg = G->getArg();
17546     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17547       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17548     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17549       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17550     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17551       Arg = ETLF->getSuccessValue();
17552       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17553     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17554       Arg = STLF->getSuccessValue();
17555       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17556     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17557       Arg = LR->getArg();
17558     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17559       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17560     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17561       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17562     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17563       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17564     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17565       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17566     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17567       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17568 
17569     if (Arg && !Finder.TraverseStmt(Arg))
17570       return true;
17571 
17572     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17573       if (!Finder.TraverseStmt(Args[I]))
17574         return true;
17575     }
17576   }
17577 
17578   return false;
17579 }
17580 
17581 void Sema::checkExceptionSpecification(
17582     bool IsTopLevel, ExceptionSpecificationType EST,
17583     ArrayRef<ParsedType> DynamicExceptions,
17584     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17585     SmallVectorImpl<QualType> &Exceptions,
17586     FunctionProtoType::ExceptionSpecInfo &ESI) {
17587   Exceptions.clear();
17588   ESI.Type = EST;
17589   if (EST == EST_Dynamic) {
17590     Exceptions.reserve(DynamicExceptions.size());
17591     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17592       // FIXME: Preserve type source info.
17593       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17594 
17595       if (IsTopLevel) {
17596         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17597         collectUnexpandedParameterPacks(ET, Unexpanded);
17598         if (!Unexpanded.empty()) {
17599           DiagnoseUnexpandedParameterPacks(
17600               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17601               Unexpanded);
17602           continue;
17603         }
17604       }
17605 
17606       // Check that the type is valid for an exception spec, and
17607       // drop it if not.
17608       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17609         Exceptions.push_back(ET);
17610     }
17611     ESI.Exceptions = Exceptions;
17612     return;
17613   }
17614 
17615   if (isComputedNoexcept(EST)) {
17616     assert((NoexceptExpr->isTypeDependent() ||
17617             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17618             Context.BoolTy) &&
17619            "Parser should have made sure that the expression is boolean");
17620     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17621       ESI.Type = EST_BasicNoexcept;
17622       return;
17623     }
17624 
17625     ESI.NoexceptExpr = NoexceptExpr;
17626     return;
17627   }
17628 }
17629 
17630 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17631              ExceptionSpecificationType EST,
17632              SourceRange SpecificationRange,
17633              ArrayRef<ParsedType> DynamicExceptions,
17634              ArrayRef<SourceRange> DynamicExceptionRanges,
17635              Expr *NoexceptExpr) {
17636   if (!MethodD)
17637     return;
17638 
17639   // Dig out the method we're referring to.
17640   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17641     MethodD = FunTmpl->getTemplatedDecl();
17642 
17643   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17644   if (!Method)
17645     return;
17646 
17647   // Check the exception specification.
17648   llvm::SmallVector<QualType, 4> Exceptions;
17649   FunctionProtoType::ExceptionSpecInfo ESI;
17650   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17651                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17652                               ESI);
17653 
17654   // Update the exception specification on the function type.
17655   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17656 
17657   if (Method->isStatic())
17658     checkThisInStaticMemberFunctionExceptionSpec(Method);
17659 
17660   if (Method->isVirtual()) {
17661     // Check overrides, which we previously had to delay.
17662     for (const CXXMethodDecl *O : Method->overridden_methods())
17663       CheckOverridingFunctionExceptionSpec(Method, O);
17664   }
17665 }
17666 
17667 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17668 ///
17669 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17670                                        SourceLocation DeclStart, Declarator &D,
17671                                        Expr *BitWidth,
17672                                        InClassInitStyle InitStyle,
17673                                        AccessSpecifier AS,
17674                                        const ParsedAttr &MSPropertyAttr) {
17675   IdentifierInfo *II = D.getIdentifier();
17676   if (!II) {
17677     Diag(DeclStart, diag::err_anonymous_property);
17678     return nullptr;
17679   }
17680   SourceLocation Loc = D.getIdentifierLoc();
17681 
17682   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17683   QualType T = TInfo->getType();
17684   if (getLangOpts().CPlusPlus) {
17685     CheckExtraCXXDefaultArguments(D);
17686 
17687     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17688                                         UPPC_DataMemberType)) {
17689       D.setInvalidType();
17690       T = Context.IntTy;
17691       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17692     }
17693   }
17694 
17695   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17696 
17697   if (D.getDeclSpec().isInlineSpecified())
17698     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17699         << getLangOpts().CPlusPlus17;
17700   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17701     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17702          diag::err_invalid_thread)
17703       << DeclSpec::getSpecifierName(TSCS);
17704 
17705   // Check to see if this name was declared as a member previously
17706   NamedDecl *PrevDecl = nullptr;
17707   LookupResult Previous(*this, II, Loc, LookupMemberName,
17708                         ForVisibleRedeclaration);
17709   LookupName(Previous, S);
17710   switch (Previous.getResultKind()) {
17711   case LookupResult::Found:
17712   case LookupResult::FoundUnresolvedValue:
17713     PrevDecl = Previous.getAsSingle<NamedDecl>();
17714     break;
17715 
17716   case LookupResult::FoundOverloaded:
17717     PrevDecl = Previous.getRepresentativeDecl();
17718     break;
17719 
17720   case LookupResult::NotFound:
17721   case LookupResult::NotFoundInCurrentInstantiation:
17722   case LookupResult::Ambiguous:
17723     break;
17724   }
17725 
17726   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17727     // Maybe we will complain about the shadowed template parameter.
17728     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17729     // Just pretend that we didn't see the previous declaration.
17730     PrevDecl = nullptr;
17731   }
17732 
17733   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17734     PrevDecl = nullptr;
17735 
17736   SourceLocation TSSL = D.getBeginLoc();
17737   MSPropertyDecl *NewPD =
17738       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17739                              MSPropertyAttr.getPropertyDataGetter(),
17740                              MSPropertyAttr.getPropertyDataSetter());
17741   ProcessDeclAttributes(TUScope, NewPD, D);
17742   NewPD->setAccess(AS);
17743 
17744   if (NewPD->isInvalidDecl())
17745     Record->setInvalidDecl();
17746 
17747   if (D.getDeclSpec().isModulePrivateSpecified())
17748     NewPD->setModulePrivate();
17749 
17750   if (NewPD->isInvalidDecl() && PrevDecl) {
17751     // Don't introduce NewFD into scope; there's already something
17752     // with the same name in the same scope.
17753   } else if (II) {
17754     PushOnScopeChains(NewPD, S);
17755   } else
17756     Record->addDecl(NewPD);
17757 
17758   return NewPD;
17759 }
17760 
17761 void Sema::ActOnStartFunctionDeclarationDeclarator(
17762     Declarator &Declarator, unsigned TemplateParameterDepth) {
17763   auto &Info = InventedParameterInfos.emplace_back();
17764   TemplateParameterList *ExplicitParams = nullptr;
17765   ArrayRef<TemplateParameterList *> ExplicitLists =
17766       Declarator.getTemplateParameterLists();
17767   if (!ExplicitLists.empty()) {
17768     bool IsMemberSpecialization, IsInvalid;
17769     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17770         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17771         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17772         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17773         /*SuppressDiagnostic=*/true);
17774   }
17775   if (ExplicitParams) {
17776     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17777     for (NamedDecl *Param : *ExplicitParams)
17778       Info.TemplateParams.push_back(Param);
17779     Info.NumExplicitTemplateParams = ExplicitParams->size();
17780   } else {
17781     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17782     Info.NumExplicitTemplateParams = 0;
17783   }
17784 }
17785 
17786 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17787   auto &FSI = InventedParameterInfos.back();
17788   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17789     if (FSI.NumExplicitTemplateParams != 0) {
17790       TemplateParameterList *ExplicitParams =
17791           Declarator.getTemplateParameterLists().back();
17792       Declarator.setInventedTemplateParameterList(
17793           TemplateParameterList::Create(
17794               Context, ExplicitParams->getTemplateLoc(),
17795               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17796               ExplicitParams->getRAngleLoc(),
17797               ExplicitParams->getRequiresClause()));
17798     } else {
17799       Declarator.setInventedTemplateParameterList(
17800           TemplateParameterList::Create(
17801               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17802               SourceLocation(), /*RequiresClause=*/nullptr));
17803     }
17804   }
17805   InventedParameterInfos.pop_back();
17806 }
17807