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     S.CheckCompleteVariableDeclaration(RefVD);
1254 
1255     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1256                                    DeclarationNameInfo(B->getDeclName(), Loc),
1257                                    RefVD);
1258     if (E.isInvalid())
1259       return true;
1260 
1261     B->setBinding(T, E.get());
1262     I++;
1263   }
1264 
1265   return false;
1266 }
1267 
1268 /// Find the base class to decompose in a built-in decomposition of a class type.
1269 /// This base class search is, unfortunately, not quite like any other that we
1270 /// perform anywhere else in C++.
1271 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1272                                                 const CXXRecordDecl *RD,
1273                                                 CXXCastPath &BasePath) {
1274   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1275                           CXXBasePath &Path) {
1276     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1277   };
1278 
1279   const CXXRecordDecl *ClassWithFields = nullptr;
1280   AccessSpecifier AS = AS_public;
1281   if (RD->hasDirectFields())
1282     // [dcl.decomp]p4:
1283     //   Otherwise, all of E's non-static data members shall be public direct
1284     //   members of E ...
1285     ClassWithFields = RD;
1286   else {
1287     //   ... or of ...
1288     CXXBasePaths Paths;
1289     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1290     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1291       // If no classes have fields, just decompose RD itself. (This will work
1292       // if and only if zero bindings were provided.)
1293       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1294     }
1295 
1296     CXXBasePath *BestPath = nullptr;
1297     for (auto &P : Paths) {
1298       if (!BestPath)
1299         BestPath = &P;
1300       else if (!S.Context.hasSameType(P.back().Base->getType(),
1301                                       BestPath->back().Base->getType())) {
1302         //   ... the same ...
1303         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1304           << false << RD << BestPath->back().Base->getType()
1305           << P.back().Base->getType();
1306         return DeclAccessPair();
1307       } else if (P.Access < BestPath->Access) {
1308         BestPath = &P;
1309       }
1310     }
1311 
1312     //   ... unambiguous ...
1313     QualType BaseType = BestPath->back().Base->getType();
1314     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1315       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1316         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1317       return DeclAccessPair();
1318     }
1319 
1320     //   ... [accessible, implied by other rules] base class of E.
1321     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1322                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1323     AS = BestPath->Access;
1324 
1325     ClassWithFields = BaseType->getAsCXXRecordDecl();
1326     S.BuildBasePathArray(Paths, BasePath);
1327   }
1328 
1329   // The above search did not check whether the selected class itself has base
1330   // classes with fields, so check that now.
1331   CXXBasePaths Paths;
1332   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1333     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1334       << (ClassWithFields == RD) << RD << ClassWithFields
1335       << Paths.front().back().Base->getType();
1336     return DeclAccessPair();
1337   }
1338 
1339   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1340 }
1341 
1342 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1343                                      ValueDecl *Src, QualType DecompType,
1344                                      const CXXRecordDecl *OrigRD) {
1345   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1346                             diag::err_incomplete_type))
1347     return true;
1348 
1349   CXXCastPath BasePath;
1350   DeclAccessPair BasePair =
1351       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1352   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1353   if (!RD)
1354     return true;
1355   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1356                                                  DecompType.getQualifiers());
1357 
1358   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1359     unsigned NumFields =
1360         std::count_if(RD->field_begin(), RD->field_end(),
1361                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1362     assert(Bindings.size() != NumFields);
1363     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1364         << DecompType << (unsigned)Bindings.size() << NumFields
1365         << (NumFields < Bindings.size());
1366     return true;
1367   };
1368 
1369   //   all of E's non-static data members shall be [...] well-formed
1370   //   when named as e.name in the context of the structured binding,
1371   //   E shall not have an anonymous union member, ...
1372   unsigned I = 0;
1373   for (auto *FD : RD->fields()) {
1374     if (FD->isUnnamedBitfield())
1375       continue;
1376 
1377     // All the non-static data members are required to be nameable, so they
1378     // must all have names.
1379     if (!FD->getDeclName()) {
1380       if (RD->isLambda()) {
1381         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1382         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1383         return true;
1384       }
1385 
1386       if (FD->isAnonymousStructOrUnion()) {
1387         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1388           << DecompType << FD->getType()->isUnionType();
1389         S.Diag(FD->getLocation(), diag::note_declared_at);
1390         return true;
1391       }
1392 
1393       // FIXME: Are there any other ways we could have an anonymous member?
1394     }
1395 
1396     // We have a real field to bind.
1397     if (I >= Bindings.size())
1398       return DiagnoseBadNumberOfBindings();
1399     auto *B = Bindings[I++];
1400     SourceLocation Loc = B->getLocation();
1401 
1402     // The field must be accessible in the context of the structured binding.
1403     // We already checked that the base class is accessible.
1404     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1405     // const_cast here.
1406     S.CheckStructuredBindingMemberAccess(
1407         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1408         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1409                                      BasePair.getAccess(), FD->getAccess())));
1410 
1411     // Initialize the binding to Src.FD.
1412     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1413     if (E.isInvalid())
1414       return true;
1415     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1416                             VK_LValue, &BasePath);
1417     if (E.isInvalid())
1418       return true;
1419     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1420                                   CXXScopeSpec(), FD,
1421                                   DeclAccessPair::make(FD, FD->getAccess()),
1422                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1423     if (E.isInvalid())
1424       return true;
1425 
1426     // If the type of the member is T, the referenced type is cv T, where cv is
1427     // the cv-qualification of the decomposition expression.
1428     //
1429     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1430     // 'const' to the type of the field.
1431     Qualifiers Q = DecompType.getQualifiers();
1432     if (FD->isMutable())
1433       Q.removeConst();
1434     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1435   }
1436 
1437   if (I != Bindings.size())
1438     return DiagnoseBadNumberOfBindings();
1439 
1440   return false;
1441 }
1442 
1443 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1444   QualType DecompType = DD->getType();
1445 
1446   // If the type of the decomposition is dependent, then so is the type of
1447   // each binding.
1448   if (DecompType->isDependentType()) {
1449     for (auto *B : DD->bindings())
1450       B->setType(Context.DependentTy);
1451     return;
1452   }
1453 
1454   DecompType = DecompType.getNonReferenceType();
1455   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1456 
1457   // C++1z [dcl.decomp]/2:
1458   //   If E is an array type [...]
1459   // As an extension, we also support decomposition of built-in complex and
1460   // vector types.
1461   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1462     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1463       DD->setInvalidDecl();
1464     return;
1465   }
1466   if (auto *VT = DecompType->getAs<VectorType>()) {
1467     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1468       DD->setInvalidDecl();
1469     return;
1470   }
1471   if (auto *CT = DecompType->getAs<ComplexType>()) {
1472     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1473       DD->setInvalidDecl();
1474     return;
1475   }
1476 
1477   // C++1z [dcl.decomp]/3:
1478   //   if the expression std::tuple_size<E>::value is a well-formed integral
1479   //   constant expression, [...]
1480   llvm::APSInt TupleSize(32);
1481   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1482   case IsTupleLike::Error:
1483     DD->setInvalidDecl();
1484     return;
1485 
1486   case IsTupleLike::TupleLike:
1487     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1488       DD->setInvalidDecl();
1489     return;
1490 
1491   case IsTupleLike::NotTupleLike:
1492     break;
1493   }
1494 
1495   // C++1z [dcl.dcl]/8:
1496   //   [E shall be of array or non-union class type]
1497   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1498   if (!RD || RD->isUnion()) {
1499     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1500         << DD << !RD << DecompType;
1501     DD->setInvalidDecl();
1502     return;
1503   }
1504 
1505   // C++1z [dcl.decomp]/4:
1506   //   all of E's non-static data members shall be [...] direct members of
1507   //   E or of the same unambiguous public base class of E, ...
1508   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1509     DD->setInvalidDecl();
1510 }
1511 
1512 /// Merge the exception specifications of two variable declarations.
1513 ///
1514 /// This is called when there's a redeclaration of a VarDecl. The function
1515 /// checks if the redeclaration might have an exception specification and
1516 /// validates compatibility and merges the specs if necessary.
1517 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1518   // Shortcut if exceptions are disabled.
1519   if (!getLangOpts().CXXExceptions)
1520     return;
1521 
1522   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1523          "Should only be called if types are otherwise the same.");
1524 
1525   QualType NewType = New->getType();
1526   QualType OldType = Old->getType();
1527 
1528   // We're only interested in pointers and references to functions, as well
1529   // as pointers to member functions.
1530   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1531     NewType = R->getPointeeType();
1532     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1533   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1534     NewType = P->getPointeeType();
1535     OldType = OldType->castAs<PointerType>()->getPointeeType();
1536   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1537     NewType = M->getPointeeType();
1538     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1539   }
1540 
1541   if (!NewType->isFunctionProtoType())
1542     return;
1543 
1544   // There's lots of special cases for functions. For function pointers, system
1545   // libraries are hopefully not as broken so that we don't need these
1546   // workarounds.
1547   if (CheckEquivalentExceptionSpec(
1548         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1549         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1550     New->setInvalidDecl();
1551   }
1552 }
1553 
1554 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1555 /// function declaration are well-formed according to C++
1556 /// [dcl.fct.default].
1557 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1558   unsigned NumParams = FD->getNumParams();
1559   unsigned ParamIdx = 0;
1560 
1561   // This checking doesn't make sense for explicit specializations; their
1562   // default arguments are determined by the declaration we're specializing,
1563   // not by FD.
1564   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1565     return;
1566   if (auto *FTD = FD->getDescribedFunctionTemplate())
1567     if (FTD->isMemberSpecialization())
1568       return;
1569 
1570   // Find first parameter with a default argument
1571   for (; ParamIdx < NumParams; ++ParamIdx) {
1572     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1573     if (Param->hasDefaultArg())
1574       break;
1575   }
1576 
1577   // C++20 [dcl.fct.default]p4:
1578   //   In a given function declaration, each parameter subsequent to a parameter
1579   //   with a default argument shall have a default argument supplied in this or
1580   //   a previous declaration, unless the parameter was expanded from a
1581   //   parameter pack, or shall be a function parameter pack.
1582   for (; ParamIdx < NumParams; ++ParamIdx) {
1583     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1584     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1585         !(CurrentInstantiationScope &&
1586           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1587       if (Param->isInvalidDecl())
1588         /* We already complained about this parameter. */;
1589       else if (Param->getIdentifier())
1590         Diag(Param->getLocation(),
1591              diag::err_param_default_argument_missing_name)
1592           << Param->getIdentifier();
1593       else
1594         Diag(Param->getLocation(),
1595              diag::err_param_default_argument_missing);
1596     }
1597   }
1598 }
1599 
1600 /// Check that the given type is a literal type. Issue a diagnostic if not,
1601 /// if Kind is Diagnose.
1602 /// \return \c true if a problem has been found (and optionally diagnosed).
1603 template <typename... Ts>
1604 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1605                              SourceLocation Loc, QualType T, unsigned DiagID,
1606                              Ts &&...DiagArgs) {
1607   if (T->isDependentType())
1608     return false;
1609 
1610   switch (Kind) {
1611   case Sema::CheckConstexprKind::Diagnose:
1612     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1613                                       std::forward<Ts>(DiagArgs)...);
1614 
1615   case Sema::CheckConstexprKind::CheckValid:
1616     return !T->isLiteralType(SemaRef.Context);
1617   }
1618 
1619   llvm_unreachable("unknown CheckConstexprKind");
1620 }
1621 
1622 /// Determine whether a destructor cannot be constexpr due to
1623 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1624                                                const CXXDestructorDecl *DD,
1625                                                Sema::CheckConstexprKind Kind) {
1626   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1627     const CXXRecordDecl *RD =
1628         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1629     if (!RD || RD->hasConstexprDestructor())
1630       return true;
1631 
1632     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1633       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1634           << DD->getConstexprKind() << !FD
1635           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1636       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1637           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1638     }
1639     return false;
1640   };
1641 
1642   const CXXRecordDecl *RD = DD->getParent();
1643   for (const CXXBaseSpecifier &B : RD->bases())
1644     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1645       return false;
1646   for (const FieldDecl *FD : RD->fields())
1647     if (!Check(FD->getLocation(), FD->getType(), FD))
1648       return false;
1649   return true;
1650 }
1651 
1652 /// Check whether a function's parameter types are all literal types. If so,
1653 /// return true. If not, produce a suitable diagnostic and return false.
1654 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1655                                          const FunctionDecl *FD,
1656                                          Sema::CheckConstexprKind Kind) {
1657   unsigned ArgIndex = 0;
1658   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1659   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1660                                               e = FT->param_type_end();
1661        i != e; ++i, ++ArgIndex) {
1662     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1663     SourceLocation ParamLoc = PD->getLocation();
1664     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1665                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1666                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1667                          FD->isConsteval()))
1668       return false;
1669   }
1670   return true;
1671 }
1672 
1673 /// Check whether a function's return type is a literal type. If so, return
1674 /// true. If not, produce a suitable diagnostic and return false.
1675 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1676                                      Sema::CheckConstexprKind Kind) {
1677   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1678                        diag::err_constexpr_non_literal_return,
1679                        FD->isConsteval()))
1680     return false;
1681   return true;
1682 }
1683 
1684 /// Get diagnostic %select index for tag kind for
1685 /// record diagnostic message.
1686 /// WARNING: Indexes apply to particular diagnostics only!
1687 ///
1688 /// \returns diagnostic %select index.
1689 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1690   switch (Tag) {
1691   case TTK_Struct: return 0;
1692   case TTK_Interface: return 1;
1693   case TTK_Class:  return 2;
1694   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1695   }
1696 }
1697 
1698 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1699                                        Stmt *Body,
1700                                        Sema::CheckConstexprKind Kind);
1701 
1702 // Check whether a function declaration satisfies the requirements of a
1703 // constexpr function definition or a constexpr constructor definition. If so,
1704 // return true. If not, produce appropriate diagnostics (unless asked not to by
1705 // Kind) and return false.
1706 //
1707 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1708 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1709                                             CheckConstexprKind Kind) {
1710   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1711   if (MD && MD->isInstance()) {
1712     // C++11 [dcl.constexpr]p4:
1713     //  The definition of a constexpr constructor shall satisfy the following
1714     //  constraints:
1715     //  - the class shall not have any virtual base classes;
1716     //
1717     // FIXME: This only applies to constructors and destructors, not arbitrary
1718     // member functions.
1719     const CXXRecordDecl *RD = MD->getParent();
1720     if (RD->getNumVBases()) {
1721       if (Kind == CheckConstexprKind::CheckValid)
1722         return false;
1723 
1724       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1725         << isa<CXXConstructorDecl>(NewFD)
1726         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1727       for (const auto &I : RD->vbases())
1728         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1729             << I.getSourceRange();
1730       return false;
1731     }
1732   }
1733 
1734   if (!isa<CXXConstructorDecl>(NewFD)) {
1735     // C++11 [dcl.constexpr]p3:
1736     //  The definition of a constexpr function shall satisfy the following
1737     //  constraints:
1738     // - it shall not be virtual; (removed in C++20)
1739     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1740     if (Method && Method->isVirtual()) {
1741       if (getLangOpts().CPlusPlus20) {
1742         if (Kind == CheckConstexprKind::Diagnose)
1743           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1744       } else {
1745         if (Kind == CheckConstexprKind::CheckValid)
1746           return false;
1747 
1748         Method = Method->getCanonicalDecl();
1749         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1750 
1751         // If it's not obvious why this function is virtual, find an overridden
1752         // function which uses the 'virtual' keyword.
1753         const CXXMethodDecl *WrittenVirtual = Method;
1754         while (!WrittenVirtual->isVirtualAsWritten())
1755           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1756         if (WrittenVirtual != Method)
1757           Diag(WrittenVirtual->getLocation(),
1758                diag::note_overridden_virtual_function);
1759         return false;
1760       }
1761     }
1762 
1763     // - its return type shall be a literal type;
1764     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1765       return false;
1766   }
1767 
1768   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1769     // A destructor can be constexpr only if the defaulted destructor could be;
1770     // we don't need to check the members and bases if we already know they all
1771     // have constexpr destructors.
1772     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1773       if (Kind == CheckConstexprKind::CheckValid)
1774         return false;
1775       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1776         return false;
1777     }
1778   }
1779 
1780   // - each of its parameter types shall be a literal type;
1781   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1782     return false;
1783 
1784   Stmt *Body = NewFD->getBody();
1785   assert(Body &&
1786          "CheckConstexprFunctionDefinition called on function with no body");
1787   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1788 }
1789 
1790 /// Check the given declaration statement is legal within a constexpr function
1791 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1792 ///
1793 /// \return true if the body is OK (maybe only as an extension), false if we
1794 ///         have diagnosed a problem.
1795 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1796                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1797                                    Sema::CheckConstexprKind Kind) {
1798   // C++11 [dcl.constexpr]p3 and p4:
1799   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1800   //  contain only
1801   for (const auto *DclIt : DS->decls()) {
1802     switch (DclIt->getKind()) {
1803     case Decl::StaticAssert:
1804     case Decl::Using:
1805     case Decl::UsingShadow:
1806     case Decl::UsingDirective:
1807     case Decl::UnresolvedUsingTypename:
1808     case Decl::UnresolvedUsingValue:
1809       //   - static_assert-declarations
1810       //   - using-declarations,
1811       //   - using-directives,
1812       continue;
1813 
1814     case Decl::Typedef:
1815     case Decl::TypeAlias: {
1816       //   - typedef declarations and alias-declarations that do not define
1817       //     classes or enumerations,
1818       const auto *TN = cast<TypedefNameDecl>(DclIt);
1819       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1820         // Don't allow variably-modified types in constexpr functions.
1821         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1822           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1823           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1824             << TL.getSourceRange() << TL.getType()
1825             << isa<CXXConstructorDecl>(Dcl);
1826         }
1827         return false;
1828       }
1829       continue;
1830     }
1831 
1832     case Decl::Enum:
1833     case Decl::CXXRecord:
1834       // C++1y allows types to be defined, not just declared.
1835       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1836         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1837           SemaRef.Diag(DS->getBeginLoc(),
1838                        SemaRef.getLangOpts().CPlusPlus14
1839                            ? diag::warn_cxx11_compat_constexpr_type_definition
1840                            : diag::ext_constexpr_type_definition)
1841               << isa<CXXConstructorDecl>(Dcl);
1842         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1843           return false;
1844         }
1845       }
1846       continue;
1847 
1848     case Decl::EnumConstant:
1849     case Decl::IndirectField:
1850     case Decl::ParmVar:
1851       // These can only appear with other declarations which are banned in
1852       // C++11 and permitted in C++1y, so ignore them.
1853       continue;
1854 
1855     case Decl::Var:
1856     case Decl::Decomposition: {
1857       // C++1y [dcl.constexpr]p3 allows anything except:
1858       //   a definition of a variable of non-literal type or of static or
1859       //   thread storage duration or [before C++2a] for which no
1860       //   initialization is performed.
1861       const auto *VD = cast<VarDecl>(DclIt);
1862       if (VD->isThisDeclarationADefinition()) {
1863         if (VD->isStaticLocal()) {
1864           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1865             SemaRef.Diag(VD->getLocation(),
1866                          diag::err_constexpr_local_var_static)
1867               << isa<CXXConstructorDecl>(Dcl)
1868               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1869           }
1870           return false;
1871         }
1872         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1873                              diag::err_constexpr_local_var_non_literal_type,
1874                              isa<CXXConstructorDecl>(Dcl)))
1875           return false;
1876         if (!VD->getType()->isDependentType() &&
1877             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1878           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879             SemaRef.Diag(
1880                 VD->getLocation(),
1881                 SemaRef.getLangOpts().CPlusPlus20
1882                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1883                     : diag::ext_constexpr_local_var_no_init)
1884                 << isa<CXXConstructorDecl>(Dcl);
1885           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1886             return false;
1887           }
1888           continue;
1889         }
1890       }
1891       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1892         SemaRef.Diag(VD->getLocation(),
1893                      SemaRef.getLangOpts().CPlusPlus14
1894                       ? diag::warn_cxx11_compat_constexpr_local_var
1895                       : diag::ext_constexpr_local_var)
1896           << isa<CXXConstructorDecl>(Dcl);
1897       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1898         return false;
1899       }
1900       continue;
1901     }
1902 
1903     case Decl::NamespaceAlias:
1904     case Decl::Function:
1905       // These are disallowed in C++11 and permitted in C++1y. Allow them
1906       // everywhere as an extension.
1907       if (!Cxx1yLoc.isValid())
1908         Cxx1yLoc = DS->getBeginLoc();
1909       continue;
1910 
1911     default:
1912       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1913         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1914             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1915       }
1916       return false;
1917     }
1918   }
1919 
1920   return true;
1921 }
1922 
1923 /// Check that the given field is initialized within a constexpr constructor.
1924 ///
1925 /// \param Dcl The constexpr constructor being checked.
1926 /// \param Field The field being checked. This may be a member of an anonymous
1927 ///        struct or union nested within the class being checked.
1928 /// \param Inits All declarations, including anonymous struct/union members and
1929 ///        indirect members, for which any initialization was provided.
1930 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1931 ///        multiple notes for different members to the same error.
1932 /// \param Kind Whether we're diagnosing a constructor as written or determining
1933 ///        whether the formal requirements are satisfied.
1934 /// \return \c false if we're checking for validity and the constructor does
1935 ///         not satisfy the requirements on a constexpr constructor.
1936 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1937                                           const FunctionDecl *Dcl,
1938                                           FieldDecl *Field,
1939                                           llvm::SmallSet<Decl*, 16> &Inits,
1940                                           bool &Diagnosed,
1941                                           Sema::CheckConstexprKind Kind) {
1942   // In C++20 onwards, there's nothing to check for validity.
1943   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1944       SemaRef.getLangOpts().CPlusPlus20)
1945     return true;
1946 
1947   if (Field->isInvalidDecl())
1948     return true;
1949 
1950   if (Field->isUnnamedBitfield())
1951     return true;
1952 
1953   // Anonymous unions with no variant members and empty anonymous structs do not
1954   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1955   // indirect fields don't need initializing.
1956   if (Field->isAnonymousStructOrUnion() &&
1957       (Field->getType()->isUnionType()
1958            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1959            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1960     return true;
1961 
1962   if (!Inits.count(Field)) {
1963     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1964       if (!Diagnosed) {
1965         SemaRef.Diag(Dcl->getLocation(),
1966                      SemaRef.getLangOpts().CPlusPlus20
1967                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1968                          : diag::ext_constexpr_ctor_missing_init);
1969         Diagnosed = true;
1970       }
1971       SemaRef.Diag(Field->getLocation(),
1972                    diag::note_constexpr_ctor_missing_init);
1973     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1974       return false;
1975     }
1976   } else if (Field->isAnonymousStructOrUnion()) {
1977     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1978     for (auto *I : RD->fields())
1979       // If an anonymous union contains an anonymous struct of which any member
1980       // is initialized, all members must be initialized.
1981       if (!RD->isUnion() || Inits.count(I))
1982         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1983                                            Kind))
1984           return false;
1985   }
1986   return true;
1987 }
1988 
1989 /// Check the provided statement is allowed in a constexpr function
1990 /// definition.
1991 static bool
1992 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1993                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1994                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1995                            Sema::CheckConstexprKind Kind) {
1996   // - its function-body shall be [...] a compound-statement that contains only
1997   switch (S->getStmtClass()) {
1998   case Stmt::NullStmtClass:
1999     //   - null statements,
2000     return true;
2001 
2002   case Stmt::DeclStmtClass:
2003     //   - static_assert-declarations
2004     //   - using-declarations,
2005     //   - using-directives,
2006     //   - typedef declarations and alias-declarations that do not define
2007     //     classes or enumerations,
2008     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2009       return false;
2010     return true;
2011 
2012   case Stmt::ReturnStmtClass:
2013     //   - and exactly one return statement;
2014     if (isa<CXXConstructorDecl>(Dcl)) {
2015       // C++1y allows return statements in constexpr constructors.
2016       if (!Cxx1yLoc.isValid())
2017         Cxx1yLoc = S->getBeginLoc();
2018       return true;
2019     }
2020 
2021     ReturnStmts.push_back(S->getBeginLoc());
2022     return true;
2023 
2024   case Stmt::CompoundStmtClass: {
2025     // C++1y allows compound-statements.
2026     if (!Cxx1yLoc.isValid())
2027       Cxx1yLoc = S->getBeginLoc();
2028 
2029     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2030     for (auto *BodyIt : CompStmt->body()) {
2031       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2032                                       Cxx1yLoc, Cxx2aLoc, Kind))
2033         return false;
2034     }
2035     return true;
2036   }
2037 
2038   case Stmt::AttributedStmtClass:
2039     if (!Cxx1yLoc.isValid())
2040       Cxx1yLoc = S->getBeginLoc();
2041     return true;
2042 
2043   case Stmt::IfStmtClass: {
2044     // C++1y allows if-statements.
2045     if (!Cxx1yLoc.isValid())
2046       Cxx1yLoc = S->getBeginLoc();
2047 
2048     IfStmt *If = cast<IfStmt>(S);
2049     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2050                                     Cxx1yLoc, Cxx2aLoc, Kind))
2051       return false;
2052     if (If->getElse() &&
2053         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2054                                     Cxx1yLoc, Cxx2aLoc, Kind))
2055       return false;
2056     return true;
2057   }
2058 
2059   case Stmt::WhileStmtClass:
2060   case Stmt::DoStmtClass:
2061   case Stmt::ForStmtClass:
2062   case Stmt::CXXForRangeStmtClass:
2063   case Stmt::ContinueStmtClass:
2064     // C++1y allows all of these. We don't allow them as extensions in C++11,
2065     // because they don't make sense without variable mutation.
2066     if (!SemaRef.getLangOpts().CPlusPlus14)
2067       break;
2068     if (!Cxx1yLoc.isValid())
2069       Cxx1yLoc = S->getBeginLoc();
2070     for (Stmt *SubStmt : S->children())
2071       if (SubStmt &&
2072           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2073                                       Cxx1yLoc, Cxx2aLoc, Kind))
2074         return false;
2075     return true;
2076 
2077   case Stmt::SwitchStmtClass:
2078   case Stmt::CaseStmtClass:
2079   case Stmt::DefaultStmtClass:
2080   case Stmt::BreakStmtClass:
2081     // C++1y allows switch-statements, and since they don't need variable
2082     // mutation, we can reasonably allow them in C++11 as an extension.
2083     if (!Cxx1yLoc.isValid())
2084       Cxx1yLoc = S->getBeginLoc();
2085     for (Stmt *SubStmt : S->children())
2086       if (SubStmt &&
2087           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2088                                       Cxx1yLoc, Cxx2aLoc, Kind))
2089         return false;
2090     return true;
2091 
2092   case Stmt::GCCAsmStmtClass:
2093   case Stmt::MSAsmStmtClass:
2094     // C++2a allows inline assembly statements.
2095   case Stmt::CXXTryStmtClass:
2096     if (Cxx2aLoc.isInvalid())
2097       Cxx2aLoc = S->getBeginLoc();
2098     for (Stmt *SubStmt : S->children()) {
2099       if (SubStmt &&
2100           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2101                                       Cxx1yLoc, Cxx2aLoc, Kind))
2102         return false;
2103     }
2104     return true;
2105 
2106   case Stmt::CXXCatchStmtClass:
2107     // Do not bother checking the language mode (already covered by the
2108     // try block check).
2109     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2110                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2111                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2112       return false;
2113     return true;
2114 
2115   default:
2116     if (!isa<Expr>(S))
2117       break;
2118 
2119     // C++1y allows expression-statements.
2120     if (!Cxx1yLoc.isValid())
2121       Cxx1yLoc = S->getBeginLoc();
2122     return true;
2123   }
2124 
2125   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2126     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2127         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2128   }
2129   return false;
2130 }
2131 
2132 /// Check the body for the given constexpr function declaration only contains
2133 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2134 ///
2135 /// \return true if the body is OK, false if we have found or diagnosed a
2136 /// problem.
2137 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2138                                        Stmt *Body,
2139                                        Sema::CheckConstexprKind Kind) {
2140   SmallVector<SourceLocation, 4> ReturnStmts;
2141 
2142   if (isa<CXXTryStmt>(Body)) {
2143     // C++11 [dcl.constexpr]p3:
2144     //  The definition of a constexpr function shall satisfy the following
2145     //  constraints: [...]
2146     // - its function-body shall be = delete, = default, or a
2147     //   compound-statement
2148     //
2149     // C++11 [dcl.constexpr]p4:
2150     //  In the definition of a constexpr constructor, [...]
2151     // - its function-body shall not be a function-try-block;
2152     //
2153     // This restriction is lifted in C++2a, as long as inner statements also
2154     // apply the general constexpr rules.
2155     switch (Kind) {
2156     case Sema::CheckConstexprKind::CheckValid:
2157       if (!SemaRef.getLangOpts().CPlusPlus20)
2158         return false;
2159       break;
2160 
2161     case Sema::CheckConstexprKind::Diagnose:
2162       SemaRef.Diag(Body->getBeginLoc(),
2163            !SemaRef.getLangOpts().CPlusPlus20
2164                ? diag::ext_constexpr_function_try_block_cxx20
2165                : diag::warn_cxx17_compat_constexpr_function_try_block)
2166           << isa<CXXConstructorDecl>(Dcl);
2167       break;
2168     }
2169   }
2170 
2171   // - its function-body shall be [...] a compound-statement that contains only
2172   //   [... list of cases ...]
2173   //
2174   // Note that walking the children here is enough to properly check for
2175   // CompoundStmt and CXXTryStmt body.
2176   SourceLocation Cxx1yLoc, Cxx2aLoc;
2177   for (Stmt *SubStmt : Body->children()) {
2178     if (SubStmt &&
2179         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2180                                     Cxx1yLoc, Cxx2aLoc, Kind))
2181       return false;
2182   }
2183 
2184   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2185     // If this is only valid as an extension, report that we don't satisfy the
2186     // constraints of the current language.
2187     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2188         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2189       return false;
2190   } else if (Cxx2aLoc.isValid()) {
2191     SemaRef.Diag(Cxx2aLoc,
2192          SemaRef.getLangOpts().CPlusPlus20
2193            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2194            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2195       << isa<CXXConstructorDecl>(Dcl);
2196   } else if (Cxx1yLoc.isValid()) {
2197     SemaRef.Diag(Cxx1yLoc,
2198          SemaRef.getLangOpts().CPlusPlus14
2199            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2200            : diag::ext_constexpr_body_invalid_stmt)
2201       << isa<CXXConstructorDecl>(Dcl);
2202   }
2203 
2204   if (const CXXConstructorDecl *Constructor
2205         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2206     const CXXRecordDecl *RD = Constructor->getParent();
2207     // DR1359:
2208     // - every non-variant non-static data member and base class sub-object
2209     //   shall be initialized;
2210     // DR1460:
2211     // - if the class is a union having variant members, exactly one of them
2212     //   shall be initialized;
2213     if (RD->isUnion()) {
2214       if (Constructor->getNumCtorInitializers() == 0 &&
2215           RD->hasVariantMembers()) {
2216         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2217           SemaRef.Diag(
2218               Dcl->getLocation(),
2219               SemaRef.getLangOpts().CPlusPlus20
2220                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2221                   : diag::ext_constexpr_union_ctor_no_init);
2222         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2223           return false;
2224         }
2225       }
2226     } else if (!Constructor->isDependentContext() &&
2227                !Constructor->isDelegatingConstructor()) {
2228       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2229 
2230       // Skip detailed checking if we have enough initializers, and we would
2231       // allow at most one initializer per member.
2232       bool AnyAnonStructUnionMembers = false;
2233       unsigned Fields = 0;
2234       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2235            E = RD->field_end(); I != E; ++I, ++Fields) {
2236         if (I->isAnonymousStructOrUnion()) {
2237           AnyAnonStructUnionMembers = true;
2238           break;
2239         }
2240       }
2241       // DR1460:
2242       // - if the class is a union-like class, but is not a union, for each of
2243       //   its anonymous union members having variant members, exactly one of
2244       //   them shall be initialized;
2245       if (AnyAnonStructUnionMembers ||
2246           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2247         // Check initialization of non-static data members. Base classes are
2248         // always initialized so do not need to be checked. Dependent bases
2249         // might not have initializers in the member initializer list.
2250         llvm::SmallSet<Decl*, 16> Inits;
2251         for (const auto *I: Constructor->inits()) {
2252           if (FieldDecl *FD = I->getMember())
2253             Inits.insert(FD);
2254           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2255             Inits.insert(ID->chain_begin(), ID->chain_end());
2256         }
2257 
2258         bool Diagnosed = false;
2259         for (auto *I : RD->fields())
2260           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2261                                              Kind))
2262             return false;
2263       }
2264     }
2265   } else {
2266     if (ReturnStmts.empty()) {
2267       // C++1y doesn't require constexpr functions to contain a 'return'
2268       // statement. We still do, unless the return type might be void, because
2269       // otherwise if there's no return statement, the function cannot
2270       // be used in a core constant expression.
2271       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2272                 (Dcl->getReturnType()->isVoidType() ||
2273                  Dcl->getReturnType()->isDependentType());
2274       switch (Kind) {
2275       case Sema::CheckConstexprKind::Diagnose:
2276         SemaRef.Diag(Dcl->getLocation(),
2277                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2278                         : diag::err_constexpr_body_no_return)
2279             << Dcl->isConsteval();
2280         if (!OK)
2281           return false;
2282         break;
2283 
2284       case Sema::CheckConstexprKind::CheckValid:
2285         // The formal requirements don't include this rule in C++14, even
2286         // though the "must be able to produce a constant expression" rules
2287         // still imply it in some cases.
2288         if (!SemaRef.getLangOpts().CPlusPlus14)
2289           return false;
2290         break;
2291       }
2292     } else if (ReturnStmts.size() > 1) {
2293       switch (Kind) {
2294       case Sema::CheckConstexprKind::Diagnose:
2295         SemaRef.Diag(
2296             ReturnStmts.back(),
2297             SemaRef.getLangOpts().CPlusPlus14
2298                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2299                 : diag::ext_constexpr_body_multiple_return);
2300         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2301           SemaRef.Diag(ReturnStmts[I],
2302                        diag::note_constexpr_body_previous_return);
2303         break;
2304 
2305       case Sema::CheckConstexprKind::CheckValid:
2306         if (!SemaRef.getLangOpts().CPlusPlus14)
2307           return false;
2308         break;
2309       }
2310     }
2311   }
2312 
2313   // C++11 [dcl.constexpr]p5:
2314   //   if no function argument values exist such that the function invocation
2315   //   substitution would produce a constant expression, the program is
2316   //   ill-formed; no diagnostic required.
2317   // C++11 [dcl.constexpr]p3:
2318   //   - every constructor call and implicit conversion used in initializing the
2319   //     return value shall be one of those allowed in a constant expression.
2320   // C++11 [dcl.constexpr]p4:
2321   //   - every constructor involved in initializing non-static data members and
2322   //     base class sub-objects shall be a constexpr constructor.
2323   //
2324   // Note that this rule is distinct from the "requirements for a constexpr
2325   // function", so is not checked in CheckValid mode.
2326   SmallVector<PartialDiagnosticAt, 8> Diags;
2327   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2328       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2329     SemaRef.Diag(Dcl->getLocation(),
2330                  diag::ext_constexpr_function_never_constant_expr)
2331         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2332     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2333       SemaRef.Diag(Diags[I].first, Diags[I].second);
2334     // Don't return false here: we allow this for compatibility in
2335     // system headers.
2336   }
2337 
2338   return true;
2339 }
2340 
2341 /// Get the class that is directly named by the current context. This is the
2342 /// class for which an unqualified-id in this scope could name a constructor
2343 /// or destructor.
2344 ///
2345 /// If the scope specifier denotes a class, this will be that class.
2346 /// If the scope specifier is empty, this will be the class whose
2347 /// member-specification we are currently within. Otherwise, there
2348 /// is no such class.
2349 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2350   assert(getLangOpts().CPlusPlus && "No class names in C!");
2351 
2352   if (SS && SS->isInvalid())
2353     return nullptr;
2354 
2355   if (SS && SS->isNotEmpty()) {
2356     DeclContext *DC = computeDeclContext(*SS, true);
2357     return dyn_cast_or_null<CXXRecordDecl>(DC);
2358   }
2359 
2360   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2361 }
2362 
2363 /// isCurrentClassName - Determine whether the identifier II is the
2364 /// name of the class type currently being defined. In the case of
2365 /// nested classes, this will only return true if II is the name of
2366 /// the innermost class.
2367 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2368                               const CXXScopeSpec *SS) {
2369   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2370   return CurDecl && &II == CurDecl->getIdentifier();
2371 }
2372 
2373 /// Determine whether the identifier II is a typo for the name of
2374 /// the class type currently being defined. If so, update it to the identifier
2375 /// that should have been used.
2376 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2377   assert(getLangOpts().CPlusPlus && "No class names in C!");
2378 
2379   if (!getLangOpts().SpellChecking)
2380     return false;
2381 
2382   CXXRecordDecl *CurDecl;
2383   if (SS && SS->isSet() && !SS->isInvalid()) {
2384     DeclContext *DC = computeDeclContext(*SS, true);
2385     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2386   } else
2387     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2388 
2389   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2390       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2391           < II->getLength()) {
2392     II = CurDecl->getIdentifier();
2393     return true;
2394   }
2395 
2396   return false;
2397 }
2398 
2399 /// Determine whether the given class is a base class of the given
2400 /// class, including looking at dependent bases.
2401 static bool findCircularInheritance(const CXXRecordDecl *Class,
2402                                     const CXXRecordDecl *Current) {
2403   SmallVector<const CXXRecordDecl*, 8> Queue;
2404 
2405   Class = Class->getCanonicalDecl();
2406   while (true) {
2407     for (const auto &I : Current->bases()) {
2408       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2409       if (!Base)
2410         continue;
2411 
2412       Base = Base->getDefinition();
2413       if (!Base)
2414         continue;
2415 
2416       if (Base->getCanonicalDecl() == Class)
2417         return true;
2418 
2419       Queue.push_back(Base);
2420     }
2421 
2422     if (Queue.empty())
2423       return false;
2424 
2425     Current = Queue.pop_back_val();
2426   }
2427 
2428   return false;
2429 }
2430 
2431 /// Check the validity of a C++ base class specifier.
2432 ///
2433 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2434 /// and returns NULL otherwise.
2435 CXXBaseSpecifier *
2436 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2437                          SourceRange SpecifierRange,
2438                          bool Virtual, AccessSpecifier Access,
2439                          TypeSourceInfo *TInfo,
2440                          SourceLocation EllipsisLoc) {
2441   QualType BaseType = TInfo->getType();
2442   if (BaseType->containsErrors()) {
2443     // Already emitted a diagnostic when parsing the error type.
2444     return nullptr;
2445   }
2446   // C++ [class.union]p1:
2447   //   A union shall not have base classes.
2448   if (Class->isUnion()) {
2449     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2450       << SpecifierRange;
2451     return nullptr;
2452   }
2453 
2454   if (EllipsisLoc.isValid() &&
2455       !TInfo->getType()->containsUnexpandedParameterPack()) {
2456     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2457       << TInfo->getTypeLoc().getSourceRange();
2458     EllipsisLoc = SourceLocation();
2459   }
2460 
2461   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2462 
2463   if (BaseType->isDependentType()) {
2464     // Make sure that we don't have circular inheritance among our dependent
2465     // bases. For non-dependent bases, the check for completeness below handles
2466     // this.
2467     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2468       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2469           ((BaseDecl = BaseDecl->getDefinition()) &&
2470            findCircularInheritance(Class, BaseDecl))) {
2471         Diag(BaseLoc, diag::err_circular_inheritance)
2472           << BaseType << Context.getTypeDeclType(Class);
2473 
2474         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2475           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2476             << BaseType;
2477 
2478         return nullptr;
2479       }
2480     }
2481 
2482     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2483                                           Class->getTagKind() == TTK_Class,
2484                                           Access, TInfo, EllipsisLoc);
2485   }
2486 
2487   // Base specifiers must be record types.
2488   if (!BaseType->isRecordType()) {
2489     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2490     return nullptr;
2491   }
2492 
2493   // C++ [class.union]p1:
2494   //   A union shall not be used as a base class.
2495   if (BaseType->isUnionType()) {
2496     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2497     return nullptr;
2498   }
2499 
2500   // For the MS ABI, propagate DLL attributes to base class templates.
2501   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2502     if (Attr *ClassAttr = getDLLAttr(Class)) {
2503       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2504               BaseType->getAsCXXRecordDecl())) {
2505         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2506                                             BaseLoc);
2507       }
2508     }
2509   }
2510 
2511   // C++ [class.derived]p2:
2512   //   The class-name in a base-specifier shall not be an incompletely
2513   //   defined class.
2514   if (RequireCompleteType(BaseLoc, BaseType,
2515                           diag::err_incomplete_base_class, SpecifierRange)) {
2516     Class->setInvalidDecl();
2517     return nullptr;
2518   }
2519 
2520   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2521   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2522   assert(BaseDecl && "Record type has no declaration");
2523   BaseDecl = BaseDecl->getDefinition();
2524   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2525   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2526   assert(CXXBaseDecl && "Base type is not a C++ type");
2527 
2528   // Microsoft docs say:
2529   // "If a base-class has a code_seg attribute, derived classes must have the
2530   // same attribute."
2531   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2532   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2533   if ((DerivedCSA || BaseCSA) &&
2534       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2535     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2536     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2537       << CXXBaseDecl;
2538     return nullptr;
2539   }
2540 
2541   // A class which contains a flexible array member is not suitable for use as a
2542   // base class:
2543   //   - If the layout determines that a base comes before another base,
2544   //     the flexible array member would index into the subsequent base.
2545   //   - If the layout determines that base comes before the derived class,
2546   //     the flexible array member would index into the derived class.
2547   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2548     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2549       << CXXBaseDecl->getDeclName();
2550     return nullptr;
2551   }
2552 
2553   // C++ [class]p3:
2554   //   If a class is marked final and it appears as a base-type-specifier in
2555   //   base-clause, the program is ill-formed.
2556   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2557     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2558       << CXXBaseDecl->getDeclName()
2559       << FA->isSpelledAsSealed();
2560     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2561         << CXXBaseDecl->getDeclName() << FA->getRange();
2562     return nullptr;
2563   }
2564 
2565   if (BaseDecl->isInvalidDecl())
2566     Class->setInvalidDecl();
2567 
2568   // Create the base specifier.
2569   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2570                                         Class->getTagKind() == TTK_Class,
2571                                         Access, TInfo, EllipsisLoc);
2572 }
2573 
2574 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2575 /// one entry in the base class list of a class specifier, for
2576 /// example:
2577 ///    class foo : public bar, virtual private baz {
2578 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2579 BaseResult
2580 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2581                          ParsedAttributes &Attributes,
2582                          bool Virtual, AccessSpecifier Access,
2583                          ParsedType basetype, SourceLocation BaseLoc,
2584                          SourceLocation EllipsisLoc) {
2585   if (!classdecl)
2586     return true;
2587 
2588   AdjustDeclIfTemplate(classdecl);
2589   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2590   if (!Class)
2591     return true;
2592 
2593   // We haven't yet attached the base specifiers.
2594   Class->setIsParsingBaseSpecifiers();
2595 
2596   // We do not support any C++11 attributes on base-specifiers yet.
2597   // Diagnose any attributes we see.
2598   for (const ParsedAttr &AL : Attributes) {
2599     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2600       continue;
2601     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2602                           ? (unsigned)diag::warn_unknown_attribute_ignored
2603                           : (unsigned)diag::err_base_specifier_attribute)
2604         << AL;
2605   }
2606 
2607   TypeSourceInfo *TInfo = nullptr;
2608   GetTypeFromParser(basetype, &TInfo);
2609 
2610   if (EllipsisLoc.isInvalid() &&
2611       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2612                                       UPPC_BaseType))
2613     return true;
2614 
2615   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2616                                                       Virtual, Access, TInfo,
2617                                                       EllipsisLoc))
2618     return BaseSpec;
2619   else
2620     Class->setInvalidDecl();
2621 
2622   return true;
2623 }
2624 
2625 /// Use small set to collect indirect bases.  As this is only used
2626 /// locally, there's no need to abstract the small size parameter.
2627 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2628 
2629 /// Recursively add the bases of Type.  Don't add Type itself.
2630 static void
2631 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2632                   const QualType &Type)
2633 {
2634   // Even though the incoming type is a base, it might not be
2635   // a class -- it could be a template parm, for instance.
2636   if (auto Rec = Type->getAs<RecordType>()) {
2637     auto Decl = Rec->getAsCXXRecordDecl();
2638 
2639     // Iterate over its bases.
2640     for (const auto &BaseSpec : Decl->bases()) {
2641       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2642         .getUnqualifiedType();
2643       if (Set.insert(Base).second)
2644         // If we've not already seen it, recurse.
2645         NoteIndirectBases(Context, Set, Base);
2646     }
2647   }
2648 }
2649 
2650 /// Performs the actual work of attaching the given base class
2651 /// specifiers to a C++ class.
2652 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2653                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2654  if (Bases.empty())
2655     return false;
2656 
2657   // Used to keep track of which base types we have already seen, so
2658   // that we can properly diagnose redundant direct base types. Note
2659   // that the key is always the unqualified canonical type of the base
2660   // class.
2661   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2662 
2663   // Used to track indirect bases so we can see if a direct base is
2664   // ambiguous.
2665   IndirectBaseSet IndirectBaseTypes;
2666 
2667   // Copy non-redundant base specifiers into permanent storage.
2668   unsigned NumGoodBases = 0;
2669   bool Invalid = false;
2670   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2671     QualType NewBaseType
2672       = Context.getCanonicalType(Bases[idx]->getType());
2673     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2674 
2675     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2676     if (KnownBase) {
2677       // C++ [class.mi]p3:
2678       //   A class shall not be specified as a direct base class of a
2679       //   derived class more than once.
2680       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2681           << KnownBase->getType() << Bases[idx]->getSourceRange();
2682 
2683       // Delete the duplicate base class specifier; we're going to
2684       // overwrite its pointer later.
2685       Context.Deallocate(Bases[idx]);
2686 
2687       Invalid = true;
2688     } else {
2689       // Okay, add this new base class.
2690       KnownBase = Bases[idx];
2691       Bases[NumGoodBases++] = Bases[idx];
2692 
2693       // Note this base's direct & indirect bases, if there could be ambiguity.
2694       if (Bases.size() > 1)
2695         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2696 
2697       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2698         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2699         if (Class->isInterface() &&
2700               (!RD->isInterfaceLike() ||
2701                KnownBase->getAccessSpecifier() != AS_public)) {
2702           // The Microsoft extension __interface does not permit bases that
2703           // are not themselves public interfaces.
2704           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2705               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2706               << RD->getSourceRange();
2707           Invalid = true;
2708         }
2709         if (RD->hasAttr<WeakAttr>())
2710           Class->addAttr(WeakAttr::CreateImplicit(Context));
2711       }
2712     }
2713   }
2714 
2715   // Attach the remaining base class specifiers to the derived class.
2716   Class->setBases(Bases.data(), NumGoodBases);
2717 
2718   // Check that the only base classes that are duplicate are virtual.
2719   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2720     // Check whether this direct base is inaccessible due to ambiguity.
2721     QualType BaseType = Bases[idx]->getType();
2722 
2723     // Skip all dependent types in templates being used as base specifiers.
2724     // Checks below assume that the base specifier is a CXXRecord.
2725     if (BaseType->isDependentType())
2726       continue;
2727 
2728     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2729       .getUnqualifiedType();
2730 
2731     if (IndirectBaseTypes.count(CanonicalBase)) {
2732       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2733                          /*DetectVirtual=*/true);
2734       bool found
2735         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2736       assert(found);
2737       (void)found;
2738 
2739       if (Paths.isAmbiguous(CanonicalBase))
2740         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2741             << BaseType << getAmbiguousPathsDisplayString(Paths)
2742             << Bases[idx]->getSourceRange();
2743       else
2744         assert(Bases[idx]->isVirtual());
2745     }
2746 
2747     // Delete the base class specifier, since its data has been copied
2748     // into the CXXRecordDecl.
2749     Context.Deallocate(Bases[idx]);
2750   }
2751 
2752   return Invalid;
2753 }
2754 
2755 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2756 /// class, after checking whether there are any duplicate base
2757 /// classes.
2758 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2759                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2760   if (!ClassDecl || Bases.empty())
2761     return;
2762 
2763   AdjustDeclIfTemplate(ClassDecl);
2764   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2765 }
2766 
2767 /// Determine whether the type \p Derived is a C++ class that is
2768 /// derived from the type \p Base.
2769 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2770   if (!getLangOpts().CPlusPlus)
2771     return false;
2772 
2773   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2774   if (!DerivedRD)
2775     return false;
2776 
2777   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2778   if (!BaseRD)
2779     return false;
2780 
2781   // If either the base or the derived type is invalid, don't try to
2782   // check whether one is derived from the other.
2783   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2784     return false;
2785 
2786   // FIXME: In a modules build, do we need the entire path to be visible for us
2787   // to be able to use the inheritance relationship?
2788   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2789     return false;
2790 
2791   return DerivedRD->isDerivedFrom(BaseRD);
2792 }
2793 
2794 /// Determine whether the type \p Derived is a C++ class that is
2795 /// derived from the type \p Base.
2796 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2797                          CXXBasePaths &Paths) {
2798   if (!getLangOpts().CPlusPlus)
2799     return false;
2800 
2801   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2802   if (!DerivedRD)
2803     return false;
2804 
2805   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2806   if (!BaseRD)
2807     return false;
2808 
2809   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2810     return false;
2811 
2812   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2813 }
2814 
2815 static void BuildBasePathArray(const CXXBasePath &Path,
2816                                CXXCastPath &BasePathArray) {
2817   // We first go backward and check if we have a virtual base.
2818   // FIXME: It would be better if CXXBasePath had the base specifier for
2819   // the nearest virtual base.
2820   unsigned Start = 0;
2821   for (unsigned I = Path.size(); I != 0; --I) {
2822     if (Path[I - 1].Base->isVirtual()) {
2823       Start = I - 1;
2824       break;
2825     }
2826   }
2827 
2828   // Now add all bases.
2829   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2830     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2831 }
2832 
2833 
2834 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2835                               CXXCastPath &BasePathArray) {
2836   assert(BasePathArray.empty() && "Base path array must be empty!");
2837   assert(Paths.isRecordingPaths() && "Must record paths!");
2838   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2839 }
2840 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2841 /// conversion (where Derived and Base are class types) is
2842 /// well-formed, meaning that the conversion is unambiguous (and
2843 /// that all of the base classes are accessible). Returns true
2844 /// and emits a diagnostic if the code is ill-formed, returns false
2845 /// otherwise. Loc is the location where this routine should point to
2846 /// if there is an error, and Range is the source range to highlight
2847 /// if there is an error.
2848 ///
2849 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2850 /// diagnostic for the respective type of error will be suppressed, but the
2851 /// check for ill-formed code will still be performed.
2852 bool
2853 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2854                                    unsigned InaccessibleBaseID,
2855                                    unsigned AmbiguousBaseConvID,
2856                                    SourceLocation Loc, SourceRange Range,
2857                                    DeclarationName Name,
2858                                    CXXCastPath *BasePath,
2859                                    bool IgnoreAccess) {
2860   // First, determine whether the path from Derived to Base is
2861   // ambiguous. This is slightly more expensive than checking whether
2862   // the Derived to Base conversion exists, because here we need to
2863   // explore multiple paths to determine if there is an ambiguity.
2864   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2865                      /*DetectVirtual=*/false);
2866   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2867   if (!DerivationOkay)
2868     return true;
2869 
2870   const CXXBasePath *Path = nullptr;
2871   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2872     Path = &Paths.front();
2873 
2874   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2875   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2876   // user to access such bases.
2877   if (!Path && getLangOpts().MSVCCompat) {
2878     for (const CXXBasePath &PossiblePath : Paths) {
2879       if (PossiblePath.size() == 1) {
2880         Path = &PossiblePath;
2881         if (AmbiguousBaseConvID)
2882           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2883               << Base << Derived << Range;
2884         break;
2885       }
2886     }
2887   }
2888 
2889   if (Path) {
2890     if (!IgnoreAccess) {
2891       // Check that the base class can be accessed.
2892       switch (
2893           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2894       case AR_inaccessible:
2895         return true;
2896       case AR_accessible:
2897       case AR_dependent:
2898       case AR_delayed:
2899         break;
2900       }
2901     }
2902 
2903     // Build a base path if necessary.
2904     if (BasePath)
2905       ::BuildBasePathArray(*Path, *BasePath);
2906     return false;
2907   }
2908 
2909   if (AmbiguousBaseConvID) {
2910     // We know that the derived-to-base conversion is ambiguous, and
2911     // we're going to produce a diagnostic. Perform the derived-to-base
2912     // search just one more time to compute all of the possible paths so
2913     // that we can print them out. This is more expensive than any of
2914     // the previous derived-to-base checks we've done, but at this point
2915     // performance isn't as much of an issue.
2916     Paths.clear();
2917     Paths.setRecordingPaths(true);
2918     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2919     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2920     (void)StillOkay;
2921 
2922     // Build up a textual representation of the ambiguous paths, e.g.,
2923     // D -> B -> A, that will be used to illustrate the ambiguous
2924     // conversions in the diagnostic. We only print one of the paths
2925     // to each base class subobject.
2926     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2927 
2928     Diag(Loc, AmbiguousBaseConvID)
2929     << Derived << Base << PathDisplayStr << Range << Name;
2930   }
2931   return true;
2932 }
2933 
2934 bool
2935 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2936                                    SourceLocation Loc, SourceRange Range,
2937                                    CXXCastPath *BasePath,
2938                                    bool IgnoreAccess) {
2939   return CheckDerivedToBaseConversion(
2940       Derived, Base, diag::err_upcast_to_inaccessible_base,
2941       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2942       BasePath, IgnoreAccess);
2943 }
2944 
2945 
2946 /// Builds a string representing ambiguous paths from a
2947 /// specific derived class to different subobjects of the same base
2948 /// class.
2949 ///
2950 /// This function builds a string that can be used in error messages
2951 /// to show the different paths that one can take through the
2952 /// inheritance hierarchy to go from the derived class to different
2953 /// subobjects of a base class. The result looks something like this:
2954 /// @code
2955 /// struct D -> struct B -> struct A
2956 /// struct D -> struct C -> struct A
2957 /// @endcode
2958 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2959   std::string PathDisplayStr;
2960   std::set<unsigned> DisplayedPaths;
2961   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2962        Path != Paths.end(); ++Path) {
2963     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2964       // We haven't displayed a path to this particular base
2965       // class subobject yet.
2966       PathDisplayStr += "\n    ";
2967       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2968       for (CXXBasePath::const_iterator Element = Path->begin();
2969            Element != Path->end(); ++Element)
2970         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2971     }
2972   }
2973 
2974   return PathDisplayStr;
2975 }
2976 
2977 //===----------------------------------------------------------------------===//
2978 // C++ class member Handling
2979 //===----------------------------------------------------------------------===//
2980 
2981 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2982 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2983                                 SourceLocation ColonLoc,
2984                                 const ParsedAttributesView &Attrs) {
2985   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2986   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2987                                                   ASLoc, ColonLoc);
2988   CurContext->addHiddenDecl(ASDecl);
2989   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2990 }
2991 
2992 /// CheckOverrideControl - Check C++11 override control semantics.
2993 void Sema::CheckOverrideControl(NamedDecl *D) {
2994   if (D->isInvalidDecl())
2995     return;
2996 
2997   // We only care about "override" and "final" declarations.
2998   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2999     return;
3000 
3001   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3002 
3003   // We can't check dependent instance methods.
3004   if (MD && MD->isInstance() &&
3005       (MD->getParent()->hasAnyDependentBases() ||
3006        MD->getType()->isDependentType()))
3007     return;
3008 
3009   if (MD && !MD->isVirtual()) {
3010     // If we have a non-virtual method, check if if hides a virtual method.
3011     // (In that case, it's most likely the method has the wrong type.)
3012     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3013     FindHiddenVirtualMethods(MD, OverloadedMethods);
3014 
3015     if (!OverloadedMethods.empty()) {
3016       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3017         Diag(OA->getLocation(),
3018              diag::override_keyword_hides_virtual_member_function)
3019           << "override" << (OverloadedMethods.size() > 1);
3020       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3021         Diag(FA->getLocation(),
3022              diag::override_keyword_hides_virtual_member_function)
3023           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3024           << (OverloadedMethods.size() > 1);
3025       }
3026       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3027       MD->setInvalidDecl();
3028       return;
3029     }
3030     // Fall through into the general case diagnostic.
3031     // FIXME: We might want to attempt typo correction here.
3032   }
3033 
3034   if (!MD || !MD->isVirtual()) {
3035     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3036       Diag(OA->getLocation(),
3037            diag::override_keyword_only_allowed_on_virtual_member_functions)
3038         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3039       D->dropAttr<OverrideAttr>();
3040     }
3041     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3042       Diag(FA->getLocation(),
3043            diag::override_keyword_only_allowed_on_virtual_member_functions)
3044         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3045         << FixItHint::CreateRemoval(FA->getLocation());
3046       D->dropAttr<FinalAttr>();
3047     }
3048     return;
3049   }
3050 
3051   // C++11 [class.virtual]p5:
3052   //   If a function is marked with the virt-specifier override and
3053   //   does not override a member function of a base class, the program is
3054   //   ill-formed.
3055   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3056   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3057     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3058       << MD->getDeclName();
3059 }
3060 
3061 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3062   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3063     return;
3064   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3065   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3066     return;
3067 
3068   SourceLocation Loc = MD->getLocation();
3069   SourceLocation SpellingLoc = Loc;
3070   if (getSourceManager().isMacroArgExpansion(Loc))
3071     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3072   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3073   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3074       return;
3075 
3076   if (MD->size_overridden_methods() > 0) {
3077     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3078       unsigned DiagID =
3079           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3080               ? DiagInconsistent
3081               : DiagSuggest;
3082       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3083       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3084       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3085     };
3086     if (isa<CXXDestructorDecl>(MD))
3087       EmitDiag(
3088           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3089           diag::warn_suggest_destructor_marked_not_override_overriding);
3090     else
3091       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3092                diag::warn_suggest_function_marked_not_override_overriding);
3093   }
3094 }
3095 
3096 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3097 /// function overrides a virtual member function marked 'final', according to
3098 /// C++11 [class.virtual]p4.
3099 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3100                                                   const CXXMethodDecl *Old) {
3101   FinalAttr *FA = Old->getAttr<FinalAttr>();
3102   if (!FA)
3103     return false;
3104 
3105   Diag(New->getLocation(), diag::err_final_function_overridden)
3106     << New->getDeclName()
3107     << FA->isSpelledAsSealed();
3108   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3109   return true;
3110 }
3111 
3112 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3113   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3114   // FIXME: Destruction of ObjC lifetime types has side-effects.
3115   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3116     return !RD->isCompleteDefinition() ||
3117            !RD->hasTrivialDefaultConstructor() ||
3118            !RD->hasTrivialDestructor();
3119   return false;
3120 }
3121 
3122 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3123   ParsedAttributesView::const_iterator Itr =
3124       llvm::find_if(list, [](const ParsedAttr &AL) {
3125         return AL.isDeclspecPropertyAttribute();
3126       });
3127   if (Itr != list.end())
3128     return &*Itr;
3129   return nullptr;
3130 }
3131 
3132 // Check if there is a field shadowing.
3133 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3134                                       DeclarationName FieldName,
3135                                       const CXXRecordDecl *RD,
3136                                       bool DeclIsField) {
3137   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3138     return;
3139 
3140   // To record a shadowed field in a base
3141   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3142   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3143                            CXXBasePath &Path) {
3144     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3145     // Record an ambiguous path directly
3146     if (Bases.find(Base) != Bases.end())
3147       return true;
3148     for (const auto Field : Base->lookup(FieldName)) {
3149       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3150           Field->getAccess() != AS_private) {
3151         assert(Field->getAccess() != AS_none);
3152         assert(Bases.find(Base) == Bases.end());
3153         Bases[Base] = Field;
3154         return true;
3155       }
3156     }
3157     return false;
3158   };
3159 
3160   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3161                      /*DetectVirtual=*/true);
3162   if (!RD->lookupInBases(FieldShadowed, Paths))
3163     return;
3164 
3165   for (const auto &P : Paths) {
3166     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3167     auto It = Bases.find(Base);
3168     // Skip duplicated bases
3169     if (It == Bases.end())
3170       continue;
3171     auto BaseField = It->second;
3172     assert(BaseField->getAccess() != AS_private);
3173     if (AS_none !=
3174         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3175       Diag(Loc, diag::warn_shadow_field)
3176         << FieldName << RD << Base << DeclIsField;
3177       Diag(BaseField->getLocation(), diag::note_shadow_field);
3178       Bases.erase(It);
3179     }
3180   }
3181 }
3182 
3183 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3184 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3185 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3186 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3187 /// present (but parsing it has been deferred).
3188 NamedDecl *
3189 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3190                                MultiTemplateParamsArg TemplateParameterLists,
3191                                Expr *BW, const VirtSpecifiers &VS,
3192                                InClassInitStyle InitStyle) {
3193   const DeclSpec &DS = D.getDeclSpec();
3194   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3195   DeclarationName Name = NameInfo.getName();
3196   SourceLocation Loc = NameInfo.getLoc();
3197 
3198   // For anonymous bitfields, the location should point to the type.
3199   if (Loc.isInvalid())
3200     Loc = D.getBeginLoc();
3201 
3202   Expr *BitWidth = static_cast<Expr*>(BW);
3203 
3204   assert(isa<CXXRecordDecl>(CurContext));
3205   assert(!DS.isFriendSpecified());
3206 
3207   bool isFunc = D.isDeclarationOfFunction();
3208   const ParsedAttr *MSPropertyAttr =
3209       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3210 
3211   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3212     // The Microsoft extension __interface only permits public member functions
3213     // and prohibits constructors, destructors, operators, non-public member
3214     // functions, static methods and data members.
3215     unsigned InvalidDecl;
3216     bool ShowDeclName = true;
3217     if (!isFunc &&
3218         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3219       InvalidDecl = 0;
3220     else if (!isFunc)
3221       InvalidDecl = 1;
3222     else if (AS != AS_public)
3223       InvalidDecl = 2;
3224     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3225       InvalidDecl = 3;
3226     else switch (Name.getNameKind()) {
3227       case DeclarationName::CXXConstructorName:
3228         InvalidDecl = 4;
3229         ShowDeclName = false;
3230         break;
3231 
3232       case DeclarationName::CXXDestructorName:
3233         InvalidDecl = 5;
3234         ShowDeclName = false;
3235         break;
3236 
3237       case DeclarationName::CXXOperatorName:
3238       case DeclarationName::CXXConversionFunctionName:
3239         InvalidDecl = 6;
3240         break;
3241 
3242       default:
3243         InvalidDecl = 0;
3244         break;
3245     }
3246 
3247     if (InvalidDecl) {
3248       if (ShowDeclName)
3249         Diag(Loc, diag::err_invalid_member_in_interface)
3250           << (InvalidDecl-1) << Name;
3251       else
3252         Diag(Loc, diag::err_invalid_member_in_interface)
3253           << (InvalidDecl-1) << "";
3254       return nullptr;
3255     }
3256   }
3257 
3258   // C++ 9.2p6: A member shall not be declared to have automatic storage
3259   // duration (auto, register) or with the extern storage-class-specifier.
3260   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3261   // data members and cannot be applied to names declared const or static,
3262   // and cannot be applied to reference members.
3263   switch (DS.getStorageClassSpec()) {
3264   case DeclSpec::SCS_unspecified:
3265   case DeclSpec::SCS_typedef:
3266   case DeclSpec::SCS_static:
3267     break;
3268   case DeclSpec::SCS_mutable:
3269     if (isFunc) {
3270       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3271 
3272       // FIXME: It would be nicer if the keyword was ignored only for this
3273       // declarator. Otherwise we could get follow-up errors.
3274       D.getMutableDeclSpec().ClearStorageClassSpecs();
3275     }
3276     break;
3277   default:
3278     Diag(DS.getStorageClassSpecLoc(),
3279          diag::err_storageclass_invalid_for_member);
3280     D.getMutableDeclSpec().ClearStorageClassSpecs();
3281     break;
3282   }
3283 
3284   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3285                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3286                       !isFunc);
3287 
3288   if (DS.hasConstexprSpecifier() && isInstField) {
3289     SemaDiagnosticBuilder B =
3290         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3291     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3292     if (InitStyle == ICIS_NoInit) {
3293       B << 0 << 0;
3294       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3295         B << FixItHint::CreateRemoval(ConstexprLoc);
3296       else {
3297         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3298         D.getMutableDeclSpec().ClearConstexprSpec();
3299         const char *PrevSpec;
3300         unsigned DiagID;
3301         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3302             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3303         (void)Failed;
3304         assert(!Failed && "Making a constexpr member const shouldn't fail");
3305       }
3306     } else {
3307       B << 1;
3308       const char *PrevSpec;
3309       unsigned DiagID;
3310       if (D.getMutableDeclSpec().SetStorageClassSpec(
3311           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3312           Context.getPrintingPolicy())) {
3313         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3314                "This is the only DeclSpec that should fail to be applied");
3315         B << 1;
3316       } else {
3317         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3318         isInstField = false;
3319       }
3320     }
3321   }
3322 
3323   NamedDecl *Member;
3324   if (isInstField) {
3325     CXXScopeSpec &SS = D.getCXXScopeSpec();
3326 
3327     // Data members must have identifiers for names.
3328     if (!Name.isIdentifier()) {
3329       Diag(Loc, diag::err_bad_variable_name)
3330         << Name;
3331       return nullptr;
3332     }
3333 
3334     IdentifierInfo *II = Name.getAsIdentifierInfo();
3335 
3336     // Member field could not be with "template" keyword.
3337     // So TemplateParameterLists should be empty in this case.
3338     if (TemplateParameterLists.size()) {
3339       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3340       if (TemplateParams->size()) {
3341         // There is no such thing as a member field template.
3342         Diag(D.getIdentifierLoc(), diag::err_template_member)
3343             << II
3344             << SourceRange(TemplateParams->getTemplateLoc(),
3345                 TemplateParams->getRAngleLoc());
3346       } else {
3347         // There is an extraneous 'template<>' for this member.
3348         Diag(TemplateParams->getTemplateLoc(),
3349             diag::err_template_member_noparams)
3350             << II
3351             << SourceRange(TemplateParams->getTemplateLoc(),
3352                 TemplateParams->getRAngleLoc());
3353       }
3354       return nullptr;
3355     }
3356 
3357     if (SS.isSet() && !SS.isInvalid()) {
3358       // The user provided a superfluous scope specifier inside a class
3359       // definition:
3360       //
3361       // class X {
3362       //   int X::member;
3363       // };
3364       if (DeclContext *DC = computeDeclContext(SS, false))
3365         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3366                                      D.getName().getKind() ==
3367                                          UnqualifiedIdKind::IK_TemplateId);
3368       else
3369         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3370           << Name << SS.getRange();
3371 
3372       SS.clear();
3373     }
3374 
3375     if (MSPropertyAttr) {
3376       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3377                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3378       if (!Member)
3379         return nullptr;
3380       isInstField = false;
3381     } else {
3382       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3383                                 BitWidth, InitStyle, AS);
3384       if (!Member)
3385         return nullptr;
3386     }
3387 
3388     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3389   } else {
3390     Member = HandleDeclarator(S, D, TemplateParameterLists);
3391     if (!Member)
3392       return nullptr;
3393 
3394     // Non-instance-fields can't have a bitfield.
3395     if (BitWidth) {
3396       if (Member->isInvalidDecl()) {
3397         // don't emit another diagnostic.
3398       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3399         // C++ 9.6p3: A bit-field shall not be a static member.
3400         // "static member 'A' cannot be a bit-field"
3401         Diag(Loc, diag::err_static_not_bitfield)
3402           << Name << BitWidth->getSourceRange();
3403       } else if (isa<TypedefDecl>(Member)) {
3404         // "typedef member 'x' cannot be a bit-field"
3405         Diag(Loc, diag::err_typedef_not_bitfield)
3406           << Name << BitWidth->getSourceRange();
3407       } else {
3408         // A function typedef ("typedef int f(); f a;").
3409         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3410         Diag(Loc, diag::err_not_integral_type_bitfield)
3411           << Name << cast<ValueDecl>(Member)->getType()
3412           << BitWidth->getSourceRange();
3413       }
3414 
3415       BitWidth = nullptr;
3416       Member->setInvalidDecl();
3417     }
3418 
3419     NamedDecl *NonTemplateMember = Member;
3420     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3421       NonTemplateMember = FunTmpl->getTemplatedDecl();
3422     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3423       NonTemplateMember = VarTmpl->getTemplatedDecl();
3424 
3425     Member->setAccess(AS);
3426 
3427     // If we have declared a member function template or static data member
3428     // template, set the access of the templated declaration as well.
3429     if (NonTemplateMember != Member)
3430       NonTemplateMember->setAccess(AS);
3431 
3432     // C++ [temp.deduct.guide]p3:
3433     //   A deduction guide [...] for a member class template [shall be
3434     //   declared] with the same access [as the template].
3435     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3436       auto *TD = DG->getDeducedTemplate();
3437       // Access specifiers are only meaningful if both the template and the
3438       // deduction guide are from the same scope.
3439       if (AS != TD->getAccess() &&
3440           TD->getDeclContext()->getRedeclContext()->Equals(
3441               DG->getDeclContext()->getRedeclContext())) {
3442         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3443         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3444             << TD->getAccess();
3445         const AccessSpecDecl *LastAccessSpec = nullptr;
3446         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3447           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3448             LastAccessSpec = AccessSpec;
3449         }
3450         assert(LastAccessSpec && "differing access with no access specifier");
3451         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3452             << AS;
3453       }
3454     }
3455   }
3456 
3457   if (VS.isOverrideSpecified())
3458     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3459                                          AttributeCommonInfo::AS_Keyword));
3460   if (VS.isFinalSpecified())
3461     Member->addAttr(FinalAttr::Create(
3462         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3463         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3464 
3465   if (VS.getLastLocation().isValid()) {
3466     // Update the end location of a method that has a virt-specifiers.
3467     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3468       MD->setRangeEnd(VS.getLastLocation());
3469   }
3470 
3471   CheckOverrideControl(Member);
3472 
3473   assert((Name || isInstField) && "No identifier for non-field ?");
3474 
3475   if (isInstField) {
3476     FieldDecl *FD = cast<FieldDecl>(Member);
3477     FieldCollector->Add(FD);
3478 
3479     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3480       // Remember all explicit private FieldDecls that have a name, no side
3481       // effects and are not part of a dependent type declaration.
3482       if (!FD->isImplicit() && FD->getDeclName() &&
3483           FD->getAccess() == AS_private &&
3484           !FD->hasAttr<UnusedAttr>() &&
3485           !FD->getParent()->isDependentContext() &&
3486           !InitializationHasSideEffects(*FD))
3487         UnusedPrivateFields.insert(FD);
3488     }
3489   }
3490 
3491   return Member;
3492 }
3493 
3494 namespace {
3495   class UninitializedFieldVisitor
3496       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3497     Sema &S;
3498     // List of Decls to generate a warning on.  Also remove Decls that become
3499     // initialized.
3500     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3501     // List of base classes of the record.  Classes are removed after their
3502     // initializers.
3503     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3504     // Vector of decls to be removed from the Decl set prior to visiting the
3505     // nodes.  These Decls may have been initialized in the prior initializer.
3506     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3507     // If non-null, add a note to the warning pointing back to the constructor.
3508     const CXXConstructorDecl *Constructor;
3509     // Variables to hold state when processing an initializer list.  When
3510     // InitList is true, special case initialization of FieldDecls matching
3511     // InitListFieldDecl.
3512     bool InitList;
3513     FieldDecl *InitListFieldDecl;
3514     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3515 
3516   public:
3517     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3518     UninitializedFieldVisitor(Sema &S,
3519                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3520                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3521       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3522         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3523 
3524     // Returns true if the use of ME is not an uninitialized use.
3525     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3526                                          bool CheckReferenceOnly) {
3527       llvm::SmallVector<FieldDecl*, 4> Fields;
3528       bool ReferenceField = false;
3529       while (ME) {
3530         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3531         if (!FD)
3532           return false;
3533         Fields.push_back(FD);
3534         if (FD->getType()->isReferenceType())
3535           ReferenceField = true;
3536         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3537       }
3538 
3539       // Binding a reference to an uninitialized field is not an
3540       // uninitialized use.
3541       if (CheckReferenceOnly && !ReferenceField)
3542         return true;
3543 
3544       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3545       // Discard the first field since it is the field decl that is being
3546       // initialized.
3547       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3548         UsedFieldIndex.push_back((*I)->getFieldIndex());
3549       }
3550 
3551       for (auto UsedIter = UsedFieldIndex.begin(),
3552                 UsedEnd = UsedFieldIndex.end(),
3553                 OrigIter = InitFieldIndex.begin(),
3554                 OrigEnd = InitFieldIndex.end();
3555            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3556         if (*UsedIter < *OrigIter)
3557           return true;
3558         if (*UsedIter > *OrigIter)
3559           break;
3560       }
3561 
3562       return false;
3563     }
3564 
3565     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3566                           bool AddressOf) {
3567       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3568         return;
3569 
3570       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3571       // or union.
3572       MemberExpr *FieldME = ME;
3573 
3574       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3575 
3576       Expr *Base = ME;
3577       while (MemberExpr *SubME =
3578                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3579 
3580         if (isa<VarDecl>(SubME->getMemberDecl()))
3581           return;
3582 
3583         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3584           if (!FD->isAnonymousStructOrUnion())
3585             FieldME = SubME;
3586 
3587         if (!FieldME->getType().isPODType(S.Context))
3588           AllPODFields = false;
3589 
3590         Base = SubME->getBase();
3591       }
3592 
3593       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3594         Visit(Base);
3595         return;
3596       }
3597 
3598       if (AddressOf && AllPODFields)
3599         return;
3600 
3601       ValueDecl* FoundVD = FieldME->getMemberDecl();
3602 
3603       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3604         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3605           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3606         }
3607 
3608         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3609           QualType T = BaseCast->getType();
3610           if (T->isPointerType() &&
3611               BaseClasses.count(T->getPointeeType())) {
3612             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3613                 << T->getPointeeType() << FoundVD;
3614           }
3615         }
3616       }
3617 
3618       if (!Decls.count(FoundVD))
3619         return;
3620 
3621       const bool IsReference = FoundVD->getType()->isReferenceType();
3622 
3623       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3624         // Special checking for initializer lists.
3625         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3626           return;
3627         }
3628       } else {
3629         // Prevent double warnings on use of unbounded references.
3630         if (CheckReferenceOnly && !IsReference)
3631           return;
3632       }
3633 
3634       unsigned diag = IsReference
3635           ? diag::warn_reference_field_is_uninit
3636           : diag::warn_field_is_uninit;
3637       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3638       if (Constructor)
3639         S.Diag(Constructor->getLocation(),
3640                diag::note_uninit_in_this_constructor)
3641           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3642 
3643     }
3644 
3645     void HandleValue(Expr *E, bool AddressOf) {
3646       E = E->IgnoreParens();
3647 
3648       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3649         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3650                          AddressOf /*AddressOf*/);
3651         return;
3652       }
3653 
3654       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3655         Visit(CO->getCond());
3656         HandleValue(CO->getTrueExpr(), AddressOf);
3657         HandleValue(CO->getFalseExpr(), AddressOf);
3658         return;
3659       }
3660 
3661       if (BinaryConditionalOperator *BCO =
3662               dyn_cast<BinaryConditionalOperator>(E)) {
3663         Visit(BCO->getCond());
3664         HandleValue(BCO->getFalseExpr(), AddressOf);
3665         return;
3666       }
3667 
3668       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3669         HandleValue(OVE->getSourceExpr(), AddressOf);
3670         return;
3671       }
3672 
3673       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3674         switch (BO->getOpcode()) {
3675         default:
3676           break;
3677         case(BO_PtrMemD):
3678         case(BO_PtrMemI):
3679           HandleValue(BO->getLHS(), AddressOf);
3680           Visit(BO->getRHS());
3681           return;
3682         case(BO_Comma):
3683           Visit(BO->getLHS());
3684           HandleValue(BO->getRHS(), AddressOf);
3685           return;
3686         }
3687       }
3688 
3689       Visit(E);
3690     }
3691 
3692     void CheckInitListExpr(InitListExpr *ILE) {
3693       InitFieldIndex.push_back(0);
3694       for (auto Child : ILE->children()) {
3695         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3696           CheckInitListExpr(SubList);
3697         } else {
3698           Visit(Child);
3699         }
3700         ++InitFieldIndex.back();
3701       }
3702       InitFieldIndex.pop_back();
3703     }
3704 
3705     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3706                           FieldDecl *Field, const Type *BaseClass) {
3707       // Remove Decls that may have been initialized in the previous
3708       // initializer.
3709       for (ValueDecl* VD : DeclsToRemove)
3710         Decls.erase(VD);
3711       DeclsToRemove.clear();
3712 
3713       Constructor = FieldConstructor;
3714       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3715 
3716       if (ILE && Field) {
3717         InitList = true;
3718         InitListFieldDecl = Field;
3719         InitFieldIndex.clear();
3720         CheckInitListExpr(ILE);
3721       } else {
3722         InitList = false;
3723         Visit(E);
3724       }
3725 
3726       if (Field)
3727         Decls.erase(Field);
3728       if (BaseClass)
3729         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3730     }
3731 
3732     void VisitMemberExpr(MemberExpr *ME) {
3733       // All uses of unbounded reference fields will warn.
3734       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3735     }
3736 
3737     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3738       if (E->getCastKind() == CK_LValueToRValue) {
3739         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3740         return;
3741       }
3742 
3743       Inherited::VisitImplicitCastExpr(E);
3744     }
3745 
3746     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3747       if (E->getConstructor()->isCopyConstructor()) {
3748         Expr *ArgExpr = E->getArg(0);
3749         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3750           if (ILE->getNumInits() == 1)
3751             ArgExpr = ILE->getInit(0);
3752         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3753           if (ICE->getCastKind() == CK_NoOp)
3754             ArgExpr = ICE->getSubExpr();
3755         HandleValue(ArgExpr, false /*AddressOf*/);
3756         return;
3757       }
3758       Inherited::VisitCXXConstructExpr(E);
3759     }
3760 
3761     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3762       Expr *Callee = E->getCallee();
3763       if (isa<MemberExpr>(Callee)) {
3764         HandleValue(Callee, false /*AddressOf*/);
3765         for (auto Arg : E->arguments())
3766           Visit(Arg);
3767         return;
3768       }
3769 
3770       Inherited::VisitCXXMemberCallExpr(E);
3771     }
3772 
3773     void VisitCallExpr(CallExpr *E) {
3774       // Treat std::move as a use.
3775       if (E->isCallToStdMove()) {
3776         HandleValue(E->getArg(0), /*AddressOf=*/false);
3777         return;
3778       }
3779 
3780       Inherited::VisitCallExpr(E);
3781     }
3782 
3783     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3784       Expr *Callee = E->getCallee();
3785 
3786       if (isa<UnresolvedLookupExpr>(Callee))
3787         return Inherited::VisitCXXOperatorCallExpr(E);
3788 
3789       Visit(Callee);
3790       for (auto Arg : E->arguments())
3791         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3792     }
3793 
3794     void VisitBinaryOperator(BinaryOperator *E) {
3795       // If a field assignment is detected, remove the field from the
3796       // uninitiailized field set.
3797       if (E->getOpcode() == BO_Assign)
3798         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3799           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3800             if (!FD->getType()->isReferenceType())
3801               DeclsToRemove.push_back(FD);
3802 
3803       if (E->isCompoundAssignmentOp()) {
3804         HandleValue(E->getLHS(), false /*AddressOf*/);
3805         Visit(E->getRHS());
3806         return;
3807       }
3808 
3809       Inherited::VisitBinaryOperator(E);
3810     }
3811 
3812     void VisitUnaryOperator(UnaryOperator *E) {
3813       if (E->isIncrementDecrementOp()) {
3814         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3815         return;
3816       }
3817       if (E->getOpcode() == UO_AddrOf) {
3818         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3819           HandleValue(ME->getBase(), true /*AddressOf*/);
3820           return;
3821         }
3822       }
3823 
3824       Inherited::VisitUnaryOperator(E);
3825     }
3826   };
3827 
3828   // Diagnose value-uses of fields to initialize themselves, e.g.
3829   //   foo(foo)
3830   // where foo is not also a parameter to the constructor.
3831   // Also diagnose across field uninitialized use such as
3832   //   x(y), y(x)
3833   // TODO: implement -Wuninitialized and fold this into that framework.
3834   static void DiagnoseUninitializedFields(
3835       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3836 
3837     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3838                                            Constructor->getLocation())) {
3839       return;
3840     }
3841 
3842     if (Constructor->isInvalidDecl())
3843       return;
3844 
3845     const CXXRecordDecl *RD = Constructor->getParent();
3846 
3847     if (RD->isDependentContext())
3848       return;
3849 
3850     // Holds fields that are uninitialized.
3851     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3852 
3853     // At the beginning, all fields are uninitialized.
3854     for (auto *I : RD->decls()) {
3855       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3856         UninitializedFields.insert(FD);
3857       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3858         UninitializedFields.insert(IFD->getAnonField());
3859       }
3860     }
3861 
3862     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3863     for (auto I : RD->bases())
3864       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3865 
3866     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3867       return;
3868 
3869     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3870                                                    UninitializedFields,
3871                                                    UninitializedBaseClasses);
3872 
3873     for (const auto *FieldInit : Constructor->inits()) {
3874       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3875         break;
3876 
3877       Expr *InitExpr = FieldInit->getInit();
3878       if (!InitExpr)
3879         continue;
3880 
3881       if (CXXDefaultInitExpr *Default =
3882               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3883         InitExpr = Default->getExpr();
3884         if (!InitExpr)
3885           continue;
3886         // In class initializers will point to the constructor.
3887         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3888                                               FieldInit->getAnyMember(),
3889                                               FieldInit->getBaseClass());
3890       } else {
3891         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3892                                               FieldInit->getAnyMember(),
3893                                               FieldInit->getBaseClass());
3894       }
3895     }
3896   }
3897 } // namespace
3898 
3899 /// Enter a new C++ default initializer scope. After calling this, the
3900 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3901 /// parsing or instantiating the initializer failed.
3902 void Sema::ActOnStartCXXInClassMemberInitializer() {
3903   // Create a synthetic function scope to represent the call to the constructor
3904   // that notionally surrounds a use of this initializer.
3905   PushFunctionScope();
3906 }
3907 
3908 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3909   if (!D.isFunctionDeclarator())
3910     return;
3911   auto &FTI = D.getFunctionTypeInfo();
3912   if (!FTI.Params)
3913     return;
3914   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3915                                                           FTI.NumParams)) {
3916     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3917     if (ParamDecl->getDeclName())
3918       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3919   }
3920 }
3921 
3922 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3923   if (ConstraintExpr.isInvalid())
3924     return ExprError();
3925   return CorrectDelayedTyposInExpr(ConstraintExpr);
3926 }
3927 
3928 /// This is invoked after parsing an in-class initializer for a
3929 /// non-static C++ class member, and after instantiating an in-class initializer
3930 /// in a class template. Such actions are deferred until the class is complete.
3931 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3932                                                   SourceLocation InitLoc,
3933                                                   Expr *InitExpr) {
3934   // Pop the notional constructor scope we created earlier.
3935   PopFunctionScopeInfo(nullptr, D);
3936 
3937   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3938   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3939          "must set init style when field is created");
3940 
3941   if (!InitExpr) {
3942     D->setInvalidDecl();
3943     if (FD)
3944       FD->removeInClassInitializer();
3945     return;
3946   }
3947 
3948   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3949     FD->setInvalidDecl();
3950     FD->removeInClassInitializer();
3951     return;
3952   }
3953 
3954   ExprResult Init = InitExpr;
3955   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3956     InitializedEntity Entity =
3957         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3958     InitializationKind Kind =
3959         FD->getInClassInitStyle() == ICIS_ListInit
3960             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3961                                                    InitExpr->getBeginLoc(),
3962                                                    InitExpr->getEndLoc())
3963             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3964     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3965     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3966     if (Init.isInvalid()) {
3967       FD->setInvalidDecl();
3968       return;
3969     }
3970   }
3971 
3972   // C++11 [class.base.init]p7:
3973   //   The initialization of each base and member constitutes a
3974   //   full-expression.
3975   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3976   if (Init.isInvalid()) {
3977     FD->setInvalidDecl();
3978     return;
3979   }
3980 
3981   InitExpr = Init.get();
3982 
3983   FD->setInClassInitializer(InitExpr);
3984 }
3985 
3986 /// Find the direct and/or virtual base specifiers that
3987 /// correspond to the given base type, for use in base initialization
3988 /// within a constructor.
3989 static bool FindBaseInitializer(Sema &SemaRef,
3990                                 CXXRecordDecl *ClassDecl,
3991                                 QualType BaseType,
3992                                 const CXXBaseSpecifier *&DirectBaseSpec,
3993                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3994   // First, check for a direct base class.
3995   DirectBaseSpec = nullptr;
3996   for (const auto &Base : ClassDecl->bases()) {
3997     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3998       // We found a direct base of this type. That's what we're
3999       // initializing.
4000       DirectBaseSpec = &Base;
4001       break;
4002     }
4003   }
4004 
4005   // Check for a virtual base class.
4006   // FIXME: We might be able to short-circuit this if we know in advance that
4007   // there are no virtual bases.
4008   VirtualBaseSpec = nullptr;
4009   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4010     // We haven't found a base yet; search the class hierarchy for a
4011     // virtual base class.
4012     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4013                        /*DetectVirtual=*/false);
4014     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4015                               SemaRef.Context.getTypeDeclType(ClassDecl),
4016                               BaseType, Paths)) {
4017       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4018            Path != Paths.end(); ++Path) {
4019         if (Path->back().Base->isVirtual()) {
4020           VirtualBaseSpec = Path->back().Base;
4021           break;
4022         }
4023       }
4024     }
4025   }
4026 
4027   return DirectBaseSpec || VirtualBaseSpec;
4028 }
4029 
4030 /// Handle a C++ member initializer using braced-init-list syntax.
4031 MemInitResult
4032 Sema::ActOnMemInitializer(Decl *ConstructorD,
4033                           Scope *S,
4034                           CXXScopeSpec &SS,
4035                           IdentifierInfo *MemberOrBase,
4036                           ParsedType TemplateTypeTy,
4037                           const DeclSpec &DS,
4038                           SourceLocation IdLoc,
4039                           Expr *InitList,
4040                           SourceLocation EllipsisLoc) {
4041   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4042                              DS, IdLoc, InitList,
4043                              EllipsisLoc);
4044 }
4045 
4046 /// Handle a C++ member initializer using parentheses syntax.
4047 MemInitResult
4048 Sema::ActOnMemInitializer(Decl *ConstructorD,
4049                           Scope *S,
4050                           CXXScopeSpec &SS,
4051                           IdentifierInfo *MemberOrBase,
4052                           ParsedType TemplateTypeTy,
4053                           const DeclSpec &DS,
4054                           SourceLocation IdLoc,
4055                           SourceLocation LParenLoc,
4056                           ArrayRef<Expr *> Args,
4057                           SourceLocation RParenLoc,
4058                           SourceLocation EllipsisLoc) {
4059   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4060   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4061                              DS, IdLoc, List, EllipsisLoc);
4062 }
4063 
4064 namespace {
4065 
4066 // Callback to only accept typo corrections that can be a valid C++ member
4067 // intializer: either a non-static field member or a base class.
4068 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4069 public:
4070   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4071       : ClassDecl(ClassDecl) {}
4072 
4073   bool ValidateCandidate(const TypoCorrection &candidate) override {
4074     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4075       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4076         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4077       return isa<TypeDecl>(ND);
4078     }
4079     return false;
4080   }
4081 
4082   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4083     return std::make_unique<MemInitializerValidatorCCC>(*this);
4084   }
4085 
4086 private:
4087   CXXRecordDecl *ClassDecl;
4088 };
4089 
4090 }
4091 
4092 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4093                                              CXXScopeSpec &SS,
4094                                              ParsedType TemplateTypeTy,
4095                                              IdentifierInfo *MemberOrBase) {
4096   if (SS.getScopeRep() || TemplateTypeTy)
4097     return nullptr;
4098   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4099   if (Result.empty())
4100     return nullptr;
4101   ValueDecl *Member;
4102   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4103       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4104     return Member;
4105   return nullptr;
4106 }
4107 
4108 /// Handle a C++ member initializer.
4109 MemInitResult
4110 Sema::BuildMemInitializer(Decl *ConstructorD,
4111                           Scope *S,
4112                           CXXScopeSpec &SS,
4113                           IdentifierInfo *MemberOrBase,
4114                           ParsedType TemplateTypeTy,
4115                           const DeclSpec &DS,
4116                           SourceLocation IdLoc,
4117                           Expr *Init,
4118                           SourceLocation EllipsisLoc) {
4119   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4120   if (!Res.isUsable())
4121     return true;
4122   Init = Res.get();
4123 
4124   if (!ConstructorD)
4125     return true;
4126 
4127   AdjustDeclIfTemplate(ConstructorD);
4128 
4129   CXXConstructorDecl *Constructor
4130     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4131   if (!Constructor) {
4132     // The user wrote a constructor initializer on a function that is
4133     // not a C++ constructor. Ignore the error for now, because we may
4134     // have more member initializers coming; we'll diagnose it just
4135     // once in ActOnMemInitializers.
4136     return true;
4137   }
4138 
4139   CXXRecordDecl *ClassDecl = Constructor->getParent();
4140 
4141   // C++ [class.base.init]p2:
4142   //   Names in a mem-initializer-id are looked up in the scope of the
4143   //   constructor's class and, if not found in that scope, are looked
4144   //   up in the scope containing the constructor's definition.
4145   //   [Note: if the constructor's class contains a member with the
4146   //   same name as a direct or virtual base class of the class, a
4147   //   mem-initializer-id naming the member or base class and composed
4148   //   of a single identifier refers to the class member. A
4149   //   mem-initializer-id for the hidden base class may be specified
4150   //   using a qualified name. ]
4151 
4152   // Look for a member, first.
4153   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4154           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4155     if (EllipsisLoc.isValid())
4156       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4157           << MemberOrBase
4158           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4159 
4160     return BuildMemberInitializer(Member, Init, IdLoc);
4161   }
4162   // It didn't name a member, so see if it names a class.
4163   QualType BaseType;
4164   TypeSourceInfo *TInfo = nullptr;
4165 
4166   if (TemplateTypeTy) {
4167     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4168     if (BaseType.isNull())
4169       return true;
4170   } else if (DS.getTypeSpecType() == TST_decltype) {
4171     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4172   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4173     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4174     return true;
4175   } else {
4176     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4177     LookupParsedName(R, S, &SS);
4178 
4179     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4180     if (!TyD) {
4181       if (R.isAmbiguous()) return true;
4182 
4183       // We don't want access-control diagnostics here.
4184       R.suppressDiagnostics();
4185 
4186       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4187         bool NotUnknownSpecialization = false;
4188         DeclContext *DC = computeDeclContext(SS, false);
4189         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4190           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4191 
4192         if (!NotUnknownSpecialization) {
4193           // When the scope specifier can refer to a member of an unknown
4194           // specialization, we take it as a type name.
4195           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4196                                        SS.getWithLocInContext(Context),
4197                                        *MemberOrBase, IdLoc);
4198           if (BaseType.isNull())
4199             return true;
4200 
4201           TInfo = Context.CreateTypeSourceInfo(BaseType);
4202           DependentNameTypeLoc TL =
4203               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4204           if (!TL.isNull()) {
4205             TL.setNameLoc(IdLoc);
4206             TL.setElaboratedKeywordLoc(SourceLocation());
4207             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4208           }
4209 
4210           R.clear();
4211           R.setLookupName(MemberOrBase);
4212         }
4213       }
4214 
4215       // If no results were found, try to correct typos.
4216       TypoCorrection Corr;
4217       MemInitializerValidatorCCC CCC(ClassDecl);
4218       if (R.empty() && BaseType.isNull() &&
4219           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4220                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4221         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4222           // We have found a non-static data member with a similar
4223           // name to what was typed; complain and initialize that
4224           // member.
4225           diagnoseTypo(Corr,
4226                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4227                          << MemberOrBase << true);
4228           return BuildMemberInitializer(Member, Init, IdLoc);
4229         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4230           const CXXBaseSpecifier *DirectBaseSpec;
4231           const CXXBaseSpecifier *VirtualBaseSpec;
4232           if (FindBaseInitializer(*this, ClassDecl,
4233                                   Context.getTypeDeclType(Type),
4234                                   DirectBaseSpec, VirtualBaseSpec)) {
4235             // We have found a direct or virtual base class with a
4236             // similar name to what was typed; complain and initialize
4237             // that base class.
4238             diagnoseTypo(Corr,
4239                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4240                            << MemberOrBase << false,
4241                          PDiag() /*Suppress note, we provide our own.*/);
4242 
4243             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4244                                                               : VirtualBaseSpec;
4245             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4246                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4247 
4248             TyD = Type;
4249           }
4250         }
4251       }
4252 
4253       if (!TyD && BaseType.isNull()) {
4254         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4255           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4256         return true;
4257       }
4258     }
4259 
4260     if (BaseType.isNull()) {
4261       BaseType = Context.getTypeDeclType(TyD);
4262       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4263       if (SS.isSet()) {
4264         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4265                                              BaseType);
4266         TInfo = Context.CreateTypeSourceInfo(BaseType);
4267         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4268         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4269         TL.setElaboratedKeywordLoc(SourceLocation());
4270         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4271       }
4272     }
4273   }
4274 
4275   if (!TInfo)
4276     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4277 
4278   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4279 }
4280 
4281 MemInitResult
4282 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4283                              SourceLocation IdLoc) {
4284   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4285   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4286   assert((DirectMember || IndirectMember) &&
4287          "Member must be a FieldDecl or IndirectFieldDecl");
4288 
4289   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4290     return true;
4291 
4292   if (Member->isInvalidDecl())
4293     return true;
4294 
4295   MultiExprArg Args;
4296   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4297     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4298   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4299     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4300   } else {
4301     // Template instantiation doesn't reconstruct ParenListExprs for us.
4302     Args = Init;
4303   }
4304 
4305   SourceRange InitRange = Init->getSourceRange();
4306 
4307   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4308     // Can't check initialization for a member of dependent type or when
4309     // any of the arguments are type-dependent expressions.
4310     DiscardCleanupsInEvaluationContext();
4311   } else {
4312     bool InitList = false;
4313     if (isa<InitListExpr>(Init)) {
4314       InitList = true;
4315       Args = Init;
4316     }
4317 
4318     // Initialize the member.
4319     InitializedEntity MemberEntity =
4320       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4321                    : InitializedEntity::InitializeMember(IndirectMember,
4322                                                          nullptr);
4323     InitializationKind Kind =
4324         InitList ? InitializationKind::CreateDirectList(
4325                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4326                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4327                                                     InitRange.getEnd());
4328 
4329     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4330     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4331                                             nullptr);
4332     if (MemberInit.isInvalid())
4333       return true;
4334 
4335     // C++11 [class.base.init]p7:
4336     //   The initialization of each base and member constitutes a
4337     //   full-expression.
4338     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4339                                      /*DiscardedValue*/ false);
4340     if (MemberInit.isInvalid())
4341       return true;
4342 
4343     Init = MemberInit.get();
4344   }
4345 
4346   if (DirectMember) {
4347     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4348                                             InitRange.getBegin(), Init,
4349                                             InitRange.getEnd());
4350   } else {
4351     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4352                                             InitRange.getBegin(), Init,
4353                                             InitRange.getEnd());
4354   }
4355 }
4356 
4357 MemInitResult
4358 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4359                                  CXXRecordDecl *ClassDecl) {
4360   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4361   if (!LangOpts.CPlusPlus11)
4362     return Diag(NameLoc, diag::err_delegating_ctor)
4363       << TInfo->getTypeLoc().getLocalSourceRange();
4364   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4365 
4366   bool InitList = true;
4367   MultiExprArg Args = Init;
4368   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4369     InitList = false;
4370     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4371   }
4372 
4373   SourceRange InitRange = Init->getSourceRange();
4374   // Initialize the object.
4375   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4376                                      QualType(ClassDecl->getTypeForDecl(), 0));
4377   InitializationKind Kind =
4378       InitList ? InitializationKind::CreateDirectList(
4379                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4380                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4381                                                   InitRange.getEnd());
4382   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4383   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4384                                               Args, nullptr);
4385   if (DelegationInit.isInvalid())
4386     return true;
4387 
4388   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4389          "Delegating constructor with no target?");
4390 
4391   // C++11 [class.base.init]p7:
4392   //   The initialization of each base and member constitutes a
4393   //   full-expression.
4394   DelegationInit = ActOnFinishFullExpr(
4395       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4396   if (DelegationInit.isInvalid())
4397     return true;
4398 
4399   // If we are in a dependent context, template instantiation will
4400   // perform this type-checking again. Just save the arguments that we
4401   // received in a ParenListExpr.
4402   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4403   // of the information that we have about the base
4404   // initializer. However, deconstructing the ASTs is a dicey process,
4405   // and this approach is far more likely to get the corner cases right.
4406   if (CurContext->isDependentContext())
4407     DelegationInit = Init;
4408 
4409   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4410                                           DelegationInit.getAs<Expr>(),
4411                                           InitRange.getEnd());
4412 }
4413 
4414 MemInitResult
4415 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4416                            Expr *Init, CXXRecordDecl *ClassDecl,
4417                            SourceLocation EllipsisLoc) {
4418   SourceLocation BaseLoc
4419     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4420 
4421   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4422     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4423              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4424 
4425   // C++ [class.base.init]p2:
4426   //   [...] Unless the mem-initializer-id names a nonstatic data
4427   //   member of the constructor's class or a direct or virtual base
4428   //   of that class, the mem-initializer is ill-formed. A
4429   //   mem-initializer-list can initialize a base class using any
4430   //   name that denotes that base class type.
4431   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4432 
4433   SourceRange InitRange = Init->getSourceRange();
4434   if (EllipsisLoc.isValid()) {
4435     // This is a pack expansion.
4436     if (!BaseType->containsUnexpandedParameterPack())  {
4437       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4438         << SourceRange(BaseLoc, InitRange.getEnd());
4439 
4440       EllipsisLoc = SourceLocation();
4441     }
4442   } else {
4443     // Check for any unexpanded parameter packs.
4444     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4445       return true;
4446 
4447     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4448       return true;
4449   }
4450 
4451   // Check for direct and virtual base classes.
4452   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4453   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4454   if (!Dependent) {
4455     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4456                                        BaseType))
4457       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4458 
4459     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4460                         VirtualBaseSpec);
4461 
4462     // C++ [base.class.init]p2:
4463     // Unless the mem-initializer-id names a nonstatic data member of the
4464     // constructor's class or a direct or virtual base of that class, the
4465     // mem-initializer is ill-formed.
4466     if (!DirectBaseSpec && !VirtualBaseSpec) {
4467       // If the class has any dependent bases, then it's possible that
4468       // one of those types will resolve to the same type as
4469       // BaseType. Therefore, just treat this as a dependent base
4470       // class initialization.  FIXME: Should we try to check the
4471       // initialization anyway? It seems odd.
4472       if (ClassDecl->hasAnyDependentBases())
4473         Dependent = true;
4474       else
4475         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4476           << BaseType << Context.getTypeDeclType(ClassDecl)
4477           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4478     }
4479   }
4480 
4481   if (Dependent) {
4482     DiscardCleanupsInEvaluationContext();
4483 
4484     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4485                                             /*IsVirtual=*/false,
4486                                             InitRange.getBegin(), Init,
4487                                             InitRange.getEnd(), EllipsisLoc);
4488   }
4489 
4490   // C++ [base.class.init]p2:
4491   //   If a mem-initializer-id is ambiguous because it designates both
4492   //   a direct non-virtual base class and an inherited virtual base
4493   //   class, the mem-initializer is ill-formed.
4494   if (DirectBaseSpec && VirtualBaseSpec)
4495     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4496       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4497 
4498   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4499   if (!BaseSpec)
4500     BaseSpec = VirtualBaseSpec;
4501 
4502   // Initialize the base.
4503   bool InitList = true;
4504   MultiExprArg Args = Init;
4505   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4506     InitList = false;
4507     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4508   }
4509 
4510   InitializedEntity BaseEntity =
4511     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4512   InitializationKind Kind =
4513       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4514                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4515                                                   InitRange.getEnd());
4516   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4517   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4518   if (BaseInit.isInvalid())
4519     return true;
4520 
4521   // C++11 [class.base.init]p7:
4522   //   The initialization of each base and member constitutes a
4523   //   full-expression.
4524   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4525                                  /*DiscardedValue*/ false);
4526   if (BaseInit.isInvalid())
4527     return true;
4528 
4529   // If we are in a dependent context, template instantiation will
4530   // perform this type-checking again. Just save the arguments that we
4531   // received in a ParenListExpr.
4532   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4533   // of the information that we have about the base
4534   // initializer. However, deconstructing the ASTs is a dicey process,
4535   // and this approach is far more likely to get the corner cases right.
4536   if (CurContext->isDependentContext())
4537     BaseInit = Init;
4538 
4539   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4540                                           BaseSpec->isVirtual(),
4541                                           InitRange.getBegin(),
4542                                           BaseInit.getAs<Expr>(),
4543                                           InitRange.getEnd(), EllipsisLoc);
4544 }
4545 
4546 // Create a static_cast\<T&&>(expr).
4547 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4548   if (T.isNull()) T = E->getType();
4549   QualType TargetType = SemaRef.BuildReferenceType(
4550       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4551   SourceLocation ExprLoc = E->getBeginLoc();
4552   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4553       TargetType, ExprLoc);
4554 
4555   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4556                                    SourceRange(ExprLoc, ExprLoc),
4557                                    E->getSourceRange()).get();
4558 }
4559 
4560 /// ImplicitInitializerKind - How an implicit base or member initializer should
4561 /// initialize its base or member.
4562 enum ImplicitInitializerKind {
4563   IIK_Default,
4564   IIK_Copy,
4565   IIK_Move,
4566   IIK_Inherit
4567 };
4568 
4569 static bool
4570 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4571                              ImplicitInitializerKind ImplicitInitKind,
4572                              CXXBaseSpecifier *BaseSpec,
4573                              bool IsInheritedVirtualBase,
4574                              CXXCtorInitializer *&CXXBaseInit) {
4575   InitializedEntity InitEntity
4576     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4577                                         IsInheritedVirtualBase);
4578 
4579   ExprResult BaseInit;
4580 
4581   switch (ImplicitInitKind) {
4582   case IIK_Inherit:
4583   case IIK_Default: {
4584     InitializationKind InitKind
4585       = InitializationKind::CreateDefault(Constructor->getLocation());
4586     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4587     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4588     break;
4589   }
4590 
4591   case IIK_Move:
4592   case IIK_Copy: {
4593     bool Moving = ImplicitInitKind == IIK_Move;
4594     ParmVarDecl *Param = Constructor->getParamDecl(0);
4595     QualType ParamType = Param->getType().getNonReferenceType();
4596 
4597     Expr *CopyCtorArg =
4598       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4599                           SourceLocation(), Param, false,
4600                           Constructor->getLocation(), ParamType,
4601                           VK_LValue, nullptr);
4602 
4603     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4604 
4605     // Cast to the base class to avoid ambiguities.
4606     QualType ArgTy =
4607       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4608                                        ParamType.getQualifiers());
4609 
4610     if (Moving) {
4611       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4612     }
4613 
4614     CXXCastPath BasePath;
4615     BasePath.push_back(BaseSpec);
4616     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4617                                             CK_UncheckedDerivedToBase,
4618                                             Moving ? VK_XValue : VK_LValue,
4619                                             &BasePath).get();
4620 
4621     InitializationKind InitKind
4622       = InitializationKind::CreateDirect(Constructor->getLocation(),
4623                                          SourceLocation(), SourceLocation());
4624     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4625     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4626     break;
4627   }
4628   }
4629 
4630   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4631   if (BaseInit.isInvalid())
4632     return true;
4633 
4634   CXXBaseInit =
4635     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4636                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4637                                                         SourceLocation()),
4638                                              BaseSpec->isVirtual(),
4639                                              SourceLocation(),
4640                                              BaseInit.getAs<Expr>(),
4641                                              SourceLocation(),
4642                                              SourceLocation());
4643 
4644   return false;
4645 }
4646 
4647 static bool RefersToRValueRef(Expr *MemRef) {
4648   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4649   return Referenced->getType()->isRValueReferenceType();
4650 }
4651 
4652 static bool
4653 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4654                                ImplicitInitializerKind ImplicitInitKind,
4655                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4656                                CXXCtorInitializer *&CXXMemberInit) {
4657   if (Field->isInvalidDecl())
4658     return true;
4659 
4660   SourceLocation Loc = Constructor->getLocation();
4661 
4662   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4663     bool Moving = ImplicitInitKind == IIK_Move;
4664     ParmVarDecl *Param = Constructor->getParamDecl(0);
4665     QualType ParamType = Param->getType().getNonReferenceType();
4666 
4667     // Suppress copying zero-width bitfields.
4668     if (Field->isZeroLengthBitField(SemaRef.Context))
4669       return false;
4670 
4671     Expr *MemberExprBase =
4672       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4673                           SourceLocation(), Param, false,
4674                           Loc, ParamType, VK_LValue, nullptr);
4675 
4676     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4677 
4678     if (Moving) {
4679       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4680     }
4681 
4682     // Build a reference to this field within the parameter.
4683     CXXScopeSpec SS;
4684     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4685                               Sema::LookupMemberName);
4686     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4687                                   : cast<ValueDecl>(Field), AS_public);
4688     MemberLookup.resolveKind();
4689     ExprResult CtorArg
4690       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4691                                          ParamType, Loc,
4692                                          /*IsArrow=*/false,
4693                                          SS,
4694                                          /*TemplateKWLoc=*/SourceLocation(),
4695                                          /*FirstQualifierInScope=*/nullptr,
4696                                          MemberLookup,
4697                                          /*TemplateArgs=*/nullptr,
4698                                          /*S*/nullptr);
4699     if (CtorArg.isInvalid())
4700       return true;
4701 
4702     // C++11 [class.copy]p15:
4703     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4704     //     with static_cast<T&&>(x.m);
4705     if (RefersToRValueRef(CtorArg.get())) {
4706       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4707     }
4708 
4709     InitializedEntity Entity =
4710         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4711                                                        /*Implicit*/ true)
4712                  : InitializedEntity::InitializeMember(Field, nullptr,
4713                                                        /*Implicit*/ true);
4714 
4715     // Direct-initialize to use the copy constructor.
4716     InitializationKind InitKind =
4717       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4718 
4719     Expr *CtorArgE = CtorArg.getAs<Expr>();
4720     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4721     ExprResult MemberInit =
4722         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4723     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4724     if (MemberInit.isInvalid())
4725       return true;
4726 
4727     if (Indirect)
4728       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4729           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4730     else
4731       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4732           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4733     return false;
4734   }
4735 
4736   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4737          "Unhandled implicit init kind!");
4738 
4739   QualType FieldBaseElementType =
4740     SemaRef.Context.getBaseElementType(Field->getType());
4741 
4742   if (FieldBaseElementType->isRecordType()) {
4743     InitializedEntity InitEntity =
4744         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4745                                                        /*Implicit*/ true)
4746                  : InitializedEntity::InitializeMember(Field, nullptr,
4747                                                        /*Implicit*/ true);
4748     InitializationKind InitKind =
4749       InitializationKind::CreateDefault(Loc);
4750 
4751     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4752     ExprResult MemberInit =
4753       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4754 
4755     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4756     if (MemberInit.isInvalid())
4757       return true;
4758 
4759     if (Indirect)
4760       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4761                                                                Indirect, Loc,
4762                                                                Loc,
4763                                                                MemberInit.get(),
4764                                                                Loc);
4765     else
4766       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4767                                                                Field, Loc, Loc,
4768                                                                MemberInit.get(),
4769                                                                Loc);
4770     return false;
4771   }
4772 
4773   if (!Field->getParent()->isUnion()) {
4774     if (FieldBaseElementType->isReferenceType()) {
4775       SemaRef.Diag(Constructor->getLocation(),
4776                    diag::err_uninitialized_member_in_ctor)
4777       << (int)Constructor->isImplicit()
4778       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4779       << 0 << Field->getDeclName();
4780       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4781       return true;
4782     }
4783 
4784     if (FieldBaseElementType.isConstQualified()) {
4785       SemaRef.Diag(Constructor->getLocation(),
4786                    diag::err_uninitialized_member_in_ctor)
4787       << (int)Constructor->isImplicit()
4788       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4789       << 1 << Field->getDeclName();
4790       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4791       return true;
4792     }
4793   }
4794 
4795   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4796     // ARC and Weak:
4797     //   Default-initialize Objective-C pointers to NULL.
4798     CXXMemberInit
4799       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4800                                                  Loc, Loc,
4801                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4802                                                  Loc);
4803     return false;
4804   }
4805 
4806   // Nothing to initialize.
4807   CXXMemberInit = nullptr;
4808   return false;
4809 }
4810 
4811 namespace {
4812 struct BaseAndFieldInfo {
4813   Sema &S;
4814   CXXConstructorDecl *Ctor;
4815   bool AnyErrorsInInits;
4816   ImplicitInitializerKind IIK;
4817   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4818   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4819   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4820 
4821   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4822     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4823     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4824     if (Ctor->getInheritedConstructor())
4825       IIK = IIK_Inherit;
4826     else if (Generated && Ctor->isCopyConstructor())
4827       IIK = IIK_Copy;
4828     else if (Generated && Ctor->isMoveConstructor())
4829       IIK = IIK_Move;
4830     else
4831       IIK = IIK_Default;
4832   }
4833 
4834   bool isImplicitCopyOrMove() const {
4835     switch (IIK) {
4836     case IIK_Copy:
4837     case IIK_Move:
4838       return true;
4839 
4840     case IIK_Default:
4841     case IIK_Inherit:
4842       return false;
4843     }
4844 
4845     llvm_unreachable("Invalid ImplicitInitializerKind!");
4846   }
4847 
4848   bool addFieldInitializer(CXXCtorInitializer *Init) {
4849     AllToInit.push_back(Init);
4850 
4851     // Check whether this initializer makes the field "used".
4852     if (Init->getInit()->HasSideEffects(S.Context))
4853       S.UnusedPrivateFields.remove(Init->getAnyMember());
4854 
4855     return false;
4856   }
4857 
4858   bool isInactiveUnionMember(FieldDecl *Field) {
4859     RecordDecl *Record = Field->getParent();
4860     if (!Record->isUnion())
4861       return false;
4862 
4863     if (FieldDecl *Active =
4864             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4865       return Active != Field->getCanonicalDecl();
4866 
4867     // In an implicit copy or move constructor, ignore any in-class initializer.
4868     if (isImplicitCopyOrMove())
4869       return true;
4870 
4871     // If there's no explicit initialization, the field is active only if it
4872     // has an in-class initializer...
4873     if (Field->hasInClassInitializer())
4874       return false;
4875     // ... or it's an anonymous struct or union whose class has an in-class
4876     // initializer.
4877     if (!Field->isAnonymousStructOrUnion())
4878       return true;
4879     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4880     return !FieldRD->hasInClassInitializer();
4881   }
4882 
4883   /// Determine whether the given field is, or is within, a union member
4884   /// that is inactive (because there was an initializer given for a different
4885   /// member of the union, or because the union was not initialized at all).
4886   bool isWithinInactiveUnionMember(FieldDecl *Field,
4887                                    IndirectFieldDecl *Indirect) {
4888     if (!Indirect)
4889       return isInactiveUnionMember(Field);
4890 
4891     for (auto *C : Indirect->chain()) {
4892       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4893       if (Field && isInactiveUnionMember(Field))
4894         return true;
4895     }
4896     return false;
4897   }
4898 };
4899 }
4900 
4901 /// Determine whether the given type is an incomplete or zero-lenfgth
4902 /// array type.
4903 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4904   if (T->isIncompleteArrayType())
4905     return true;
4906 
4907   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4908     if (!ArrayT->getSize())
4909       return true;
4910 
4911     T = ArrayT->getElementType();
4912   }
4913 
4914   return false;
4915 }
4916 
4917 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4918                                     FieldDecl *Field,
4919                                     IndirectFieldDecl *Indirect = nullptr) {
4920   if (Field->isInvalidDecl())
4921     return false;
4922 
4923   // Overwhelmingly common case: we have a direct initializer for this field.
4924   if (CXXCtorInitializer *Init =
4925           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4926     return Info.addFieldInitializer(Init);
4927 
4928   // C++11 [class.base.init]p8:
4929   //   if the entity is a non-static data member that has a
4930   //   brace-or-equal-initializer and either
4931   //   -- the constructor's class is a union and no other variant member of that
4932   //      union is designated by a mem-initializer-id or
4933   //   -- the constructor's class is not a union, and, if the entity is a member
4934   //      of an anonymous union, no other member of that union is designated by
4935   //      a mem-initializer-id,
4936   //   the entity is initialized as specified in [dcl.init].
4937   //
4938   // We also apply the same rules to handle anonymous structs within anonymous
4939   // unions.
4940   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4941     return false;
4942 
4943   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4944     ExprResult DIE =
4945         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4946     if (DIE.isInvalid())
4947       return true;
4948 
4949     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4950     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4951 
4952     CXXCtorInitializer *Init;
4953     if (Indirect)
4954       Init = new (SemaRef.Context)
4955           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4956                              SourceLocation(), DIE.get(), SourceLocation());
4957     else
4958       Init = new (SemaRef.Context)
4959           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4960                              SourceLocation(), DIE.get(), SourceLocation());
4961     return Info.addFieldInitializer(Init);
4962   }
4963 
4964   // Don't initialize incomplete or zero-length arrays.
4965   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4966     return false;
4967 
4968   // Don't try to build an implicit initializer if there were semantic
4969   // errors in any of the initializers (and therefore we might be
4970   // missing some that the user actually wrote).
4971   if (Info.AnyErrorsInInits)
4972     return false;
4973 
4974   CXXCtorInitializer *Init = nullptr;
4975   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4976                                      Indirect, Init))
4977     return true;
4978 
4979   if (!Init)
4980     return false;
4981 
4982   return Info.addFieldInitializer(Init);
4983 }
4984 
4985 bool
4986 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4987                                CXXCtorInitializer *Initializer) {
4988   assert(Initializer->isDelegatingInitializer());
4989   Constructor->setNumCtorInitializers(1);
4990   CXXCtorInitializer **initializer =
4991     new (Context) CXXCtorInitializer*[1];
4992   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4993   Constructor->setCtorInitializers(initializer);
4994 
4995   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4996     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4997     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4998   }
4999 
5000   DelegatingCtorDecls.push_back(Constructor);
5001 
5002   DiagnoseUninitializedFields(*this, Constructor);
5003 
5004   return false;
5005 }
5006 
5007 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5008                                ArrayRef<CXXCtorInitializer *> Initializers) {
5009   if (Constructor->isDependentContext()) {
5010     // Just store the initializers as written, they will be checked during
5011     // instantiation.
5012     if (!Initializers.empty()) {
5013       Constructor->setNumCtorInitializers(Initializers.size());
5014       CXXCtorInitializer **baseOrMemberInitializers =
5015         new (Context) CXXCtorInitializer*[Initializers.size()];
5016       memcpy(baseOrMemberInitializers, Initializers.data(),
5017              Initializers.size() * sizeof(CXXCtorInitializer*));
5018       Constructor->setCtorInitializers(baseOrMemberInitializers);
5019     }
5020 
5021     // Let template instantiation know whether we had errors.
5022     if (AnyErrors)
5023       Constructor->setInvalidDecl();
5024 
5025     return false;
5026   }
5027 
5028   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5029 
5030   // We need to build the initializer AST according to order of construction
5031   // and not what user specified in the Initializers list.
5032   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5033   if (!ClassDecl)
5034     return true;
5035 
5036   bool HadError = false;
5037 
5038   for (unsigned i = 0; i < Initializers.size(); i++) {
5039     CXXCtorInitializer *Member = Initializers[i];
5040 
5041     if (Member->isBaseInitializer())
5042       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5043     else {
5044       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5045 
5046       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5047         for (auto *C : F->chain()) {
5048           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5049           if (FD && FD->getParent()->isUnion())
5050             Info.ActiveUnionMember.insert(std::make_pair(
5051                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5052         }
5053       } else if (FieldDecl *FD = Member->getMember()) {
5054         if (FD->getParent()->isUnion())
5055           Info.ActiveUnionMember.insert(std::make_pair(
5056               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5057       }
5058     }
5059   }
5060 
5061   // Keep track of the direct virtual bases.
5062   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5063   for (auto &I : ClassDecl->bases()) {
5064     if (I.isVirtual())
5065       DirectVBases.insert(&I);
5066   }
5067 
5068   // Push virtual bases before others.
5069   for (auto &VBase : ClassDecl->vbases()) {
5070     if (CXXCtorInitializer *Value
5071         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5072       // [class.base.init]p7, per DR257:
5073       //   A mem-initializer where the mem-initializer-id names a virtual base
5074       //   class is ignored during execution of a constructor of any class that
5075       //   is not the most derived class.
5076       if (ClassDecl->isAbstract()) {
5077         // FIXME: Provide a fixit to remove the base specifier. This requires
5078         // tracking the location of the associated comma for a base specifier.
5079         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5080           << VBase.getType() << ClassDecl;
5081         DiagnoseAbstractType(ClassDecl);
5082       }
5083 
5084       Info.AllToInit.push_back(Value);
5085     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5086       // [class.base.init]p8, per DR257:
5087       //   If a given [...] base class is not named by a mem-initializer-id
5088       //   [...] and the entity is not a virtual base class of an abstract
5089       //   class, then [...] the entity is default-initialized.
5090       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5091       CXXCtorInitializer *CXXBaseInit;
5092       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5093                                        &VBase, IsInheritedVirtualBase,
5094                                        CXXBaseInit)) {
5095         HadError = true;
5096         continue;
5097       }
5098 
5099       Info.AllToInit.push_back(CXXBaseInit);
5100     }
5101   }
5102 
5103   // Non-virtual bases.
5104   for (auto &Base : ClassDecl->bases()) {
5105     // Virtuals are in the virtual base list and already constructed.
5106     if (Base.isVirtual())
5107       continue;
5108 
5109     if (CXXCtorInitializer *Value
5110           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5111       Info.AllToInit.push_back(Value);
5112     } else if (!AnyErrors) {
5113       CXXCtorInitializer *CXXBaseInit;
5114       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5115                                        &Base, /*IsInheritedVirtualBase=*/false,
5116                                        CXXBaseInit)) {
5117         HadError = true;
5118         continue;
5119       }
5120 
5121       Info.AllToInit.push_back(CXXBaseInit);
5122     }
5123   }
5124 
5125   // Fields.
5126   for (auto *Mem : ClassDecl->decls()) {
5127     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5128       // C++ [class.bit]p2:
5129       //   A declaration for a bit-field that omits the identifier declares an
5130       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5131       //   initialized.
5132       if (F->isUnnamedBitfield())
5133         continue;
5134 
5135       // If we're not generating the implicit copy/move constructor, then we'll
5136       // handle anonymous struct/union fields based on their individual
5137       // indirect fields.
5138       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5139         continue;
5140 
5141       if (CollectFieldInitializer(*this, Info, F))
5142         HadError = true;
5143       continue;
5144     }
5145 
5146     // Beyond this point, we only consider default initialization.
5147     if (Info.isImplicitCopyOrMove())
5148       continue;
5149 
5150     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5151       if (F->getType()->isIncompleteArrayType()) {
5152         assert(ClassDecl->hasFlexibleArrayMember() &&
5153                "Incomplete array type is not valid");
5154         continue;
5155       }
5156 
5157       // Initialize each field of an anonymous struct individually.
5158       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5159         HadError = true;
5160 
5161       continue;
5162     }
5163   }
5164 
5165   unsigned NumInitializers = Info.AllToInit.size();
5166   if (NumInitializers > 0) {
5167     Constructor->setNumCtorInitializers(NumInitializers);
5168     CXXCtorInitializer **baseOrMemberInitializers =
5169       new (Context) CXXCtorInitializer*[NumInitializers];
5170     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5171            NumInitializers * sizeof(CXXCtorInitializer*));
5172     Constructor->setCtorInitializers(baseOrMemberInitializers);
5173 
5174     // Constructors implicitly reference the base and member
5175     // destructors.
5176     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5177                                            Constructor->getParent());
5178   }
5179 
5180   return HadError;
5181 }
5182 
5183 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5184   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5185     const RecordDecl *RD = RT->getDecl();
5186     if (RD->isAnonymousStructOrUnion()) {
5187       for (auto *Field : RD->fields())
5188         PopulateKeysForFields(Field, IdealInits);
5189       return;
5190     }
5191   }
5192   IdealInits.push_back(Field->getCanonicalDecl());
5193 }
5194 
5195 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5196   return Context.getCanonicalType(BaseType).getTypePtr();
5197 }
5198 
5199 static const void *GetKeyForMember(ASTContext &Context,
5200                                    CXXCtorInitializer *Member) {
5201   if (!Member->isAnyMemberInitializer())
5202     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5203 
5204   return Member->getAnyMember()->getCanonicalDecl();
5205 }
5206 
5207 static void DiagnoseBaseOrMemInitializerOrder(
5208     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5209     ArrayRef<CXXCtorInitializer *> Inits) {
5210   if (Constructor->getDeclContext()->isDependentContext())
5211     return;
5212 
5213   // Don't check initializers order unless the warning is enabled at the
5214   // location of at least one initializer.
5215   bool ShouldCheckOrder = false;
5216   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5217     CXXCtorInitializer *Init = Inits[InitIndex];
5218     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5219                                  Init->getSourceLocation())) {
5220       ShouldCheckOrder = true;
5221       break;
5222     }
5223   }
5224   if (!ShouldCheckOrder)
5225     return;
5226 
5227   // Build the list of bases and members in the order that they'll
5228   // actually be initialized.  The explicit initializers should be in
5229   // this same order but may be missing things.
5230   SmallVector<const void*, 32> IdealInitKeys;
5231 
5232   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5233 
5234   // 1. Virtual bases.
5235   for (const auto &VBase : ClassDecl->vbases())
5236     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5237 
5238   // 2. Non-virtual bases.
5239   for (const auto &Base : ClassDecl->bases()) {
5240     if (Base.isVirtual())
5241       continue;
5242     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5243   }
5244 
5245   // 3. Direct fields.
5246   for (auto *Field : ClassDecl->fields()) {
5247     if (Field->isUnnamedBitfield())
5248       continue;
5249 
5250     PopulateKeysForFields(Field, IdealInitKeys);
5251   }
5252 
5253   unsigned NumIdealInits = IdealInitKeys.size();
5254   unsigned IdealIndex = 0;
5255 
5256   CXXCtorInitializer *PrevInit = nullptr;
5257   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5258     CXXCtorInitializer *Init = Inits[InitIndex];
5259     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5260 
5261     // Scan forward to try to find this initializer in the idealized
5262     // initializers list.
5263     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5264       if (InitKey == IdealInitKeys[IdealIndex])
5265         break;
5266 
5267     // If we didn't find this initializer, it must be because we
5268     // scanned past it on a previous iteration.  That can only
5269     // happen if we're out of order;  emit a warning.
5270     if (IdealIndex == NumIdealInits && PrevInit) {
5271       Sema::SemaDiagnosticBuilder D =
5272         SemaRef.Diag(PrevInit->getSourceLocation(),
5273                      diag::warn_initializer_out_of_order);
5274 
5275       if (PrevInit->isAnyMemberInitializer())
5276         D << 0 << PrevInit->getAnyMember()->getDeclName();
5277       else
5278         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5279 
5280       if (Init->isAnyMemberInitializer())
5281         D << 0 << Init->getAnyMember()->getDeclName();
5282       else
5283         D << 1 << Init->getTypeSourceInfo()->getType();
5284 
5285       // Move back to the initializer's location in the ideal list.
5286       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5287         if (InitKey == IdealInitKeys[IdealIndex])
5288           break;
5289 
5290       assert(IdealIndex < NumIdealInits &&
5291              "initializer not found in initializer list");
5292     }
5293 
5294     PrevInit = Init;
5295   }
5296 }
5297 
5298 namespace {
5299 bool CheckRedundantInit(Sema &S,
5300                         CXXCtorInitializer *Init,
5301                         CXXCtorInitializer *&PrevInit) {
5302   if (!PrevInit) {
5303     PrevInit = Init;
5304     return false;
5305   }
5306 
5307   if (FieldDecl *Field = Init->getAnyMember())
5308     S.Diag(Init->getSourceLocation(),
5309            diag::err_multiple_mem_initialization)
5310       << Field->getDeclName()
5311       << Init->getSourceRange();
5312   else {
5313     const Type *BaseClass = Init->getBaseClass();
5314     assert(BaseClass && "neither field nor base");
5315     S.Diag(Init->getSourceLocation(),
5316            diag::err_multiple_base_initialization)
5317       << QualType(BaseClass, 0)
5318       << Init->getSourceRange();
5319   }
5320   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5321     << 0 << PrevInit->getSourceRange();
5322 
5323   return true;
5324 }
5325 
5326 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5327 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5328 
5329 bool CheckRedundantUnionInit(Sema &S,
5330                              CXXCtorInitializer *Init,
5331                              RedundantUnionMap &Unions) {
5332   FieldDecl *Field = Init->getAnyMember();
5333   RecordDecl *Parent = Field->getParent();
5334   NamedDecl *Child = Field;
5335 
5336   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5337     if (Parent->isUnion()) {
5338       UnionEntry &En = Unions[Parent];
5339       if (En.first && En.first != Child) {
5340         S.Diag(Init->getSourceLocation(),
5341                diag::err_multiple_mem_union_initialization)
5342           << Field->getDeclName()
5343           << Init->getSourceRange();
5344         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5345           << 0 << En.second->getSourceRange();
5346         return true;
5347       }
5348       if (!En.first) {
5349         En.first = Child;
5350         En.second = Init;
5351       }
5352       if (!Parent->isAnonymousStructOrUnion())
5353         return false;
5354     }
5355 
5356     Child = Parent;
5357     Parent = cast<RecordDecl>(Parent->getDeclContext());
5358   }
5359 
5360   return false;
5361 }
5362 }
5363 
5364 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5365 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5366                                 SourceLocation ColonLoc,
5367                                 ArrayRef<CXXCtorInitializer*> MemInits,
5368                                 bool AnyErrors) {
5369   if (!ConstructorDecl)
5370     return;
5371 
5372   AdjustDeclIfTemplate(ConstructorDecl);
5373 
5374   CXXConstructorDecl *Constructor
5375     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5376 
5377   if (!Constructor) {
5378     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5379     return;
5380   }
5381 
5382   // Mapping for the duplicate initializers check.
5383   // For member initializers, this is keyed with a FieldDecl*.
5384   // For base initializers, this is keyed with a Type*.
5385   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5386 
5387   // Mapping for the inconsistent anonymous-union initializers check.
5388   RedundantUnionMap MemberUnions;
5389 
5390   bool HadError = false;
5391   for (unsigned i = 0; i < MemInits.size(); i++) {
5392     CXXCtorInitializer *Init = MemInits[i];
5393 
5394     // Set the source order index.
5395     Init->setSourceOrder(i);
5396 
5397     if (Init->isAnyMemberInitializer()) {
5398       const void *Key = GetKeyForMember(Context, Init);
5399       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5400           CheckRedundantUnionInit(*this, Init, MemberUnions))
5401         HadError = true;
5402     } else if (Init->isBaseInitializer()) {
5403       const void *Key = GetKeyForMember(Context, Init);
5404       if (CheckRedundantInit(*this, Init, Members[Key]))
5405         HadError = true;
5406     } else {
5407       assert(Init->isDelegatingInitializer());
5408       // This must be the only initializer
5409       if (MemInits.size() != 1) {
5410         Diag(Init->getSourceLocation(),
5411              diag::err_delegating_initializer_alone)
5412           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5413         // We will treat this as being the only initializer.
5414       }
5415       SetDelegatingInitializer(Constructor, MemInits[i]);
5416       // Return immediately as the initializer is set.
5417       return;
5418     }
5419   }
5420 
5421   if (HadError)
5422     return;
5423 
5424   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5425 
5426   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5427 
5428   DiagnoseUninitializedFields(*this, Constructor);
5429 }
5430 
5431 void
5432 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5433                                              CXXRecordDecl *ClassDecl) {
5434   // Ignore dependent contexts. Also ignore unions, since their members never
5435   // have destructors implicitly called.
5436   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5437     return;
5438 
5439   // FIXME: all the access-control diagnostics are positioned on the
5440   // field/base declaration.  That's probably good; that said, the
5441   // user might reasonably want to know why the destructor is being
5442   // emitted, and we currently don't say.
5443 
5444   // Non-static data members.
5445   for (auto *Field : ClassDecl->fields()) {
5446     if (Field->isInvalidDecl())
5447       continue;
5448 
5449     // Don't destroy incomplete or zero-length arrays.
5450     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5451       continue;
5452 
5453     QualType FieldType = Context.getBaseElementType(Field->getType());
5454 
5455     const RecordType* RT = FieldType->getAs<RecordType>();
5456     if (!RT)
5457       continue;
5458 
5459     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5460     if (FieldClassDecl->isInvalidDecl())
5461       continue;
5462     if (FieldClassDecl->hasIrrelevantDestructor())
5463       continue;
5464     // The destructor for an implicit anonymous union member is never invoked.
5465     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5466       continue;
5467 
5468     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5469     assert(Dtor && "No dtor found for FieldClassDecl!");
5470     CheckDestructorAccess(Field->getLocation(), Dtor,
5471                           PDiag(diag::err_access_dtor_field)
5472                             << Field->getDeclName()
5473                             << FieldType);
5474 
5475     MarkFunctionReferenced(Location, Dtor);
5476     DiagnoseUseOfDecl(Dtor, Location);
5477   }
5478 
5479   // We only potentially invoke the destructors of potentially constructed
5480   // subobjects.
5481   bool VisitVirtualBases = !ClassDecl->isAbstract();
5482 
5483   // If the destructor exists and has already been marked used in the MS ABI,
5484   // then virtual base destructors have already been checked and marked used.
5485   // Skip checking them again to avoid duplicate diagnostics.
5486   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5487     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5488     if (Dtor && Dtor->isUsed())
5489       VisitVirtualBases = false;
5490   }
5491 
5492   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5493 
5494   // Bases.
5495   for (const auto &Base : ClassDecl->bases()) {
5496     // Bases are always records in a well-formed non-dependent class.
5497     const RecordType *RT = Base.getType()->getAs<RecordType>();
5498 
5499     // Remember direct virtual bases.
5500     if (Base.isVirtual()) {
5501       if (!VisitVirtualBases)
5502         continue;
5503       DirectVirtualBases.insert(RT);
5504     }
5505 
5506     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5507     // If our base class is invalid, we probably can't get its dtor anyway.
5508     if (BaseClassDecl->isInvalidDecl())
5509       continue;
5510     if (BaseClassDecl->hasIrrelevantDestructor())
5511       continue;
5512 
5513     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5514     assert(Dtor && "No dtor found for BaseClassDecl!");
5515 
5516     // FIXME: caret should be on the start of the class name
5517     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5518                           PDiag(diag::err_access_dtor_base)
5519                               << Base.getType() << Base.getSourceRange(),
5520                           Context.getTypeDeclType(ClassDecl));
5521 
5522     MarkFunctionReferenced(Location, Dtor);
5523     DiagnoseUseOfDecl(Dtor, Location);
5524   }
5525 
5526   if (VisitVirtualBases)
5527     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5528                                          &DirectVirtualBases);
5529 }
5530 
5531 void Sema::MarkVirtualBaseDestructorsReferenced(
5532     SourceLocation Location, CXXRecordDecl *ClassDecl,
5533     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5534   // Virtual bases.
5535   for (const auto &VBase : ClassDecl->vbases()) {
5536     // Bases are always records in a well-formed non-dependent class.
5537     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5538 
5539     // Ignore already visited direct virtual bases.
5540     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5541       continue;
5542 
5543     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5544     // If our base class is invalid, we probably can't get its dtor anyway.
5545     if (BaseClassDecl->isInvalidDecl())
5546       continue;
5547     if (BaseClassDecl->hasIrrelevantDestructor())
5548       continue;
5549 
5550     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5551     assert(Dtor && "No dtor found for BaseClassDecl!");
5552     if (CheckDestructorAccess(
5553             ClassDecl->getLocation(), Dtor,
5554             PDiag(diag::err_access_dtor_vbase)
5555                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5556             Context.getTypeDeclType(ClassDecl)) ==
5557         AR_accessible) {
5558       CheckDerivedToBaseConversion(
5559           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5560           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5561           SourceRange(), DeclarationName(), nullptr);
5562     }
5563 
5564     MarkFunctionReferenced(Location, Dtor);
5565     DiagnoseUseOfDecl(Dtor, Location);
5566   }
5567 }
5568 
5569 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5570   if (!CDtorDecl)
5571     return;
5572 
5573   if (CXXConstructorDecl *Constructor
5574       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5575     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5576     DiagnoseUninitializedFields(*this, Constructor);
5577   }
5578 }
5579 
5580 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5581   if (!getLangOpts().CPlusPlus)
5582     return false;
5583 
5584   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5585   if (!RD)
5586     return false;
5587 
5588   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5589   // class template specialization here, but doing so breaks a lot of code.
5590 
5591   // We can't answer whether something is abstract until it has a
5592   // definition. If it's currently being defined, we'll walk back
5593   // over all the declarations when we have a full definition.
5594   const CXXRecordDecl *Def = RD->getDefinition();
5595   if (!Def || Def->isBeingDefined())
5596     return false;
5597 
5598   return RD->isAbstract();
5599 }
5600 
5601 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5602                                   TypeDiagnoser &Diagnoser) {
5603   if (!isAbstractType(Loc, T))
5604     return false;
5605 
5606   T = Context.getBaseElementType(T);
5607   Diagnoser.diagnose(*this, Loc, T);
5608   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5609   return true;
5610 }
5611 
5612 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5613   // Check if we've already emitted the list of pure virtual functions
5614   // for this class.
5615   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5616     return;
5617 
5618   // If the diagnostic is suppressed, don't emit the notes. We're only
5619   // going to emit them once, so try to attach them to a diagnostic we're
5620   // actually going to show.
5621   if (Diags.isLastDiagnosticIgnored())
5622     return;
5623 
5624   CXXFinalOverriderMap FinalOverriders;
5625   RD->getFinalOverriders(FinalOverriders);
5626 
5627   // Keep a set of seen pure methods so we won't diagnose the same method
5628   // more than once.
5629   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5630 
5631   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5632                                    MEnd = FinalOverriders.end();
5633        M != MEnd;
5634        ++M) {
5635     for (OverridingMethods::iterator SO = M->second.begin(),
5636                                   SOEnd = M->second.end();
5637          SO != SOEnd; ++SO) {
5638       // C++ [class.abstract]p4:
5639       //   A class is abstract if it contains or inherits at least one
5640       //   pure virtual function for which the final overrider is pure
5641       //   virtual.
5642 
5643       //
5644       if (SO->second.size() != 1)
5645         continue;
5646 
5647       if (!SO->second.front().Method->isPure())
5648         continue;
5649 
5650       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5651         continue;
5652 
5653       Diag(SO->second.front().Method->getLocation(),
5654            diag::note_pure_virtual_function)
5655         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5656     }
5657   }
5658 
5659   if (!PureVirtualClassDiagSet)
5660     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5661   PureVirtualClassDiagSet->insert(RD);
5662 }
5663 
5664 namespace {
5665 struct AbstractUsageInfo {
5666   Sema &S;
5667   CXXRecordDecl *Record;
5668   CanQualType AbstractType;
5669   bool Invalid;
5670 
5671   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5672     : S(S), Record(Record),
5673       AbstractType(S.Context.getCanonicalType(
5674                    S.Context.getTypeDeclType(Record))),
5675       Invalid(false) {}
5676 
5677   void DiagnoseAbstractType() {
5678     if (Invalid) return;
5679     S.DiagnoseAbstractType(Record);
5680     Invalid = true;
5681   }
5682 
5683   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5684 };
5685 
5686 struct CheckAbstractUsage {
5687   AbstractUsageInfo &Info;
5688   const NamedDecl *Ctx;
5689 
5690   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5691     : Info(Info), Ctx(Ctx) {}
5692 
5693   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5694     switch (TL.getTypeLocClass()) {
5695 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5696 #define TYPELOC(CLASS, PARENT) \
5697     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5698 #include "clang/AST/TypeLocNodes.def"
5699     }
5700   }
5701 
5702   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5703     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5704     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5705       if (!TL.getParam(I))
5706         continue;
5707 
5708       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5709       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5710     }
5711   }
5712 
5713   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5714     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5715   }
5716 
5717   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5718     // Visit the type parameters from a permissive context.
5719     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5720       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5721       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5722         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5723           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5724       // TODO: other template argument types?
5725     }
5726   }
5727 
5728   // Visit pointee types from a permissive context.
5729 #define CheckPolymorphic(Type) \
5730   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5731     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5732   }
5733   CheckPolymorphic(PointerTypeLoc)
5734   CheckPolymorphic(ReferenceTypeLoc)
5735   CheckPolymorphic(MemberPointerTypeLoc)
5736   CheckPolymorphic(BlockPointerTypeLoc)
5737   CheckPolymorphic(AtomicTypeLoc)
5738 
5739   /// Handle all the types we haven't given a more specific
5740   /// implementation for above.
5741   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5742     // Every other kind of type that we haven't called out already
5743     // that has an inner type is either (1) sugar or (2) contains that
5744     // inner type in some way as a subobject.
5745     if (TypeLoc Next = TL.getNextTypeLoc())
5746       return Visit(Next, Sel);
5747 
5748     // If there's no inner type and we're in a permissive context,
5749     // don't diagnose.
5750     if (Sel == Sema::AbstractNone) return;
5751 
5752     // Check whether the type matches the abstract type.
5753     QualType T = TL.getType();
5754     if (T->isArrayType()) {
5755       Sel = Sema::AbstractArrayType;
5756       T = Info.S.Context.getBaseElementType(T);
5757     }
5758     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5759     if (CT != Info.AbstractType) return;
5760 
5761     // It matched; do some magic.
5762     if (Sel == Sema::AbstractArrayType) {
5763       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5764         << T << TL.getSourceRange();
5765     } else {
5766       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5767         << Sel << T << TL.getSourceRange();
5768     }
5769     Info.DiagnoseAbstractType();
5770   }
5771 };
5772 
5773 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5774                                   Sema::AbstractDiagSelID Sel) {
5775   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5776 }
5777 
5778 }
5779 
5780 /// Check for invalid uses of an abstract type in a method declaration.
5781 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5782                                     CXXMethodDecl *MD) {
5783   // No need to do the check on definitions, which require that
5784   // the return/param types be complete.
5785   if (MD->doesThisDeclarationHaveABody())
5786     return;
5787 
5788   // For safety's sake, just ignore it if we don't have type source
5789   // information.  This should never happen for non-implicit methods,
5790   // but...
5791   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5792     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5793 }
5794 
5795 /// Check for invalid uses of an abstract type within a class definition.
5796 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5797                                     CXXRecordDecl *RD) {
5798   for (auto *D : RD->decls()) {
5799     if (D->isImplicit()) continue;
5800 
5801     // Methods and method templates.
5802     if (isa<CXXMethodDecl>(D)) {
5803       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5804     } else if (isa<FunctionTemplateDecl>(D)) {
5805       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5806       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5807 
5808     // Fields and static variables.
5809     } else if (isa<FieldDecl>(D)) {
5810       FieldDecl *FD = cast<FieldDecl>(D);
5811       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5812         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5813     } else if (isa<VarDecl>(D)) {
5814       VarDecl *VD = cast<VarDecl>(D);
5815       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5816         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5817 
5818     // Nested classes and class templates.
5819     } else if (isa<CXXRecordDecl>(D)) {
5820       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5821     } else if (isa<ClassTemplateDecl>(D)) {
5822       CheckAbstractClassUsage(Info,
5823                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5824     }
5825   }
5826 }
5827 
5828 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5829   Attr *ClassAttr = getDLLAttr(Class);
5830   if (!ClassAttr)
5831     return;
5832 
5833   assert(ClassAttr->getKind() == attr::DLLExport);
5834 
5835   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5836 
5837   if (TSK == TSK_ExplicitInstantiationDeclaration)
5838     // Don't go any further if this is just an explicit instantiation
5839     // declaration.
5840     return;
5841 
5842   // Add a context note to explain how we got to any diagnostics produced below.
5843   struct MarkingClassDllexported {
5844     Sema &S;
5845     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5846                             SourceLocation AttrLoc)
5847         : S(S) {
5848       Sema::CodeSynthesisContext Ctx;
5849       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5850       Ctx.PointOfInstantiation = AttrLoc;
5851       Ctx.Entity = Class;
5852       S.pushCodeSynthesisContext(Ctx);
5853     }
5854     ~MarkingClassDllexported() {
5855       S.popCodeSynthesisContext();
5856     }
5857   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5858 
5859   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5860     S.MarkVTableUsed(Class->getLocation(), Class, true);
5861 
5862   for (Decl *Member : Class->decls()) {
5863     // Defined static variables that are members of an exported base
5864     // class must be marked export too.
5865     auto *VD = dyn_cast<VarDecl>(Member);
5866     if (VD && Member->getAttr<DLLExportAttr>() &&
5867         VD->getStorageClass() == SC_Static &&
5868         TSK == TSK_ImplicitInstantiation)
5869       S.MarkVariableReferenced(VD->getLocation(), VD);
5870 
5871     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5872     if (!MD)
5873       continue;
5874 
5875     if (Member->getAttr<DLLExportAttr>()) {
5876       if (MD->isUserProvided()) {
5877         // Instantiate non-default class member functions ...
5878 
5879         // .. except for certain kinds of template specializations.
5880         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5881           continue;
5882 
5883         S.MarkFunctionReferenced(Class->getLocation(), MD);
5884 
5885         // The function will be passed to the consumer when its definition is
5886         // encountered.
5887       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5888                  MD->isCopyAssignmentOperator() ||
5889                  MD->isMoveAssignmentOperator()) {
5890         // Synthesize and instantiate non-trivial implicit methods, explicitly
5891         // defaulted methods, and the copy and move assignment operators. The
5892         // latter are exported even if they are trivial, because the address of
5893         // an operator can be taken and should compare equal across libraries.
5894         S.MarkFunctionReferenced(Class->getLocation(), MD);
5895 
5896         // There is no later point when we will see the definition of this
5897         // function, so pass it to the consumer now.
5898         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5899       }
5900     }
5901   }
5902 }
5903 
5904 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5905                                                         CXXRecordDecl *Class) {
5906   // Only the MS ABI has default constructor closures, so we don't need to do
5907   // this semantic checking anywhere else.
5908   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5909     return;
5910 
5911   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5912   for (Decl *Member : Class->decls()) {
5913     // Look for exported default constructors.
5914     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5915     if (!CD || !CD->isDefaultConstructor())
5916       continue;
5917     auto *Attr = CD->getAttr<DLLExportAttr>();
5918     if (!Attr)
5919       continue;
5920 
5921     // If the class is non-dependent, mark the default arguments as ODR-used so
5922     // that we can properly codegen the constructor closure.
5923     if (!Class->isDependentContext()) {
5924       for (ParmVarDecl *PD : CD->parameters()) {
5925         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5926         S.DiscardCleanupsInEvaluationContext();
5927       }
5928     }
5929 
5930     if (LastExportedDefaultCtor) {
5931       S.Diag(LastExportedDefaultCtor->getLocation(),
5932              diag::err_attribute_dll_ambiguous_default_ctor)
5933           << Class;
5934       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5935           << CD->getDeclName();
5936       return;
5937     }
5938     LastExportedDefaultCtor = CD;
5939   }
5940 }
5941 
5942 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5943                                                        CXXRecordDecl *Class) {
5944   bool ErrorReported = false;
5945   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5946                                                      ClassTemplateDecl *TD) {
5947     if (ErrorReported)
5948       return;
5949     S.Diag(TD->getLocation(),
5950            diag::err_cuda_device_builtin_surftex_cls_template)
5951         << /*surface*/ 0 << TD;
5952     ErrorReported = true;
5953   };
5954 
5955   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5956   if (!TD) {
5957     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5958     if (!SD) {
5959       S.Diag(Class->getLocation(),
5960              diag::err_cuda_device_builtin_surftex_ref_decl)
5961           << /*surface*/ 0 << Class;
5962       S.Diag(Class->getLocation(),
5963              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5964           << Class;
5965       return;
5966     }
5967     TD = SD->getSpecializedTemplate();
5968   }
5969 
5970   TemplateParameterList *Params = TD->getTemplateParameters();
5971   unsigned N = Params->size();
5972 
5973   if (N != 2) {
5974     reportIllegalClassTemplate(S, TD);
5975     S.Diag(TD->getLocation(),
5976            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5977         << TD << 2;
5978   }
5979   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5980     reportIllegalClassTemplate(S, TD);
5981     S.Diag(TD->getLocation(),
5982            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5983         << TD << /*1st*/ 0 << /*type*/ 0;
5984   }
5985   if (N > 1) {
5986     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5987     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5988       reportIllegalClassTemplate(S, TD);
5989       S.Diag(TD->getLocation(),
5990              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5991           << TD << /*2nd*/ 1 << /*integer*/ 1;
5992     }
5993   }
5994 }
5995 
5996 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5997                                                        CXXRecordDecl *Class) {
5998   bool ErrorReported = false;
5999   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6000                                                      ClassTemplateDecl *TD) {
6001     if (ErrorReported)
6002       return;
6003     S.Diag(TD->getLocation(),
6004            diag::err_cuda_device_builtin_surftex_cls_template)
6005         << /*texture*/ 1 << TD;
6006     ErrorReported = true;
6007   };
6008 
6009   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6010   if (!TD) {
6011     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6012     if (!SD) {
6013       S.Diag(Class->getLocation(),
6014              diag::err_cuda_device_builtin_surftex_ref_decl)
6015           << /*texture*/ 1 << Class;
6016       S.Diag(Class->getLocation(),
6017              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6018           << Class;
6019       return;
6020     }
6021     TD = SD->getSpecializedTemplate();
6022   }
6023 
6024   TemplateParameterList *Params = TD->getTemplateParameters();
6025   unsigned N = Params->size();
6026 
6027   if (N != 3) {
6028     reportIllegalClassTemplate(S, TD);
6029     S.Diag(TD->getLocation(),
6030            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6031         << TD << 3;
6032   }
6033   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6034     reportIllegalClassTemplate(S, TD);
6035     S.Diag(TD->getLocation(),
6036            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6037         << TD << /*1st*/ 0 << /*type*/ 0;
6038   }
6039   if (N > 1) {
6040     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6041     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6042       reportIllegalClassTemplate(S, TD);
6043       S.Diag(TD->getLocation(),
6044              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6045           << TD << /*2nd*/ 1 << /*integer*/ 1;
6046     }
6047   }
6048   if (N > 2) {
6049     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6050     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6051       reportIllegalClassTemplate(S, TD);
6052       S.Diag(TD->getLocation(),
6053              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6054           << TD << /*3rd*/ 2 << /*integer*/ 1;
6055     }
6056   }
6057 }
6058 
6059 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6060   // Mark any compiler-generated routines with the implicit code_seg attribute.
6061   for (auto *Method : Class->methods()) {
6062     if (Method->isUserProvided())
6063       continue;
6064     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6065       Method->addAttr(A);
6066   }
6067 }
6068 
6069 /// Check class-level dllimport/dllexport attribute.
6070 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6071   Attr *ClassAttr = getDLLAttr(Class);
6072 
6073   // MSVC inherits DLL attributes to partial class template specializations.
6074   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6075        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) && !ClassAttr) {
6076     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6077       if (Attr *TemplateAttr =
6078               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6079         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6080         A->setInherited(true);
6081         ClassAttr = A;
6082       }
6083     }
6084   }
6085 
6086   if (!ClassAttr)
6087     return;
6088 
6089   if (!Class->isExternallyVisible()) {
6090     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6091         << Class << ClassAttr;
6092     return;
6093   }
6094 
6095   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6096        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
6097       !ClassAttr->isInherited()) {
6098     // Diagnose dll attributes on members of class with dll attribute.
6099     for (Decl *Member : Class->decls()) {
6100       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6101         continue;
6102       InheritableAttr *MemberAttr = getDLLAttr(Member);
6103       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6104         continue;
6105 
6106       Diag(MemberAttr->getLocation(),
6107              diag::err_attribute_dll_member_of_dll_class)
6108           << MemberAttr << ClassAttr;
6109       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6110       Member->setInvalidDecl();
6111     }
6112   }
6113 
6114   if (Class->getDescribedClassTemplate())
6115     // Don't inherit dll attribute until the template is instantiated.
6116     return;
6117 
6118   // The class is either imported or exported.
6119   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6120 
6121   // Check if this was a dllimport attribute propagated from a derived class to
6122   // a base class template specialization. We don't apply these attributes to
6123   // static data members.
6124   const bool PropagatedImport =
6125       !ClassExported &&
6126       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6127 
6128   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6129 
6130   // Ignore explicit dllexport on explicit class template instantiation
6131   // declarations, except in MinGW mode.
6132   if (ClassExported && !ClassAttr->isInherited() &&
6133       TSK == TSK_ExplicitInstantiationDeclaration &&
6134       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6135     Class->dropAttr<DLLExportAttr>();
6136     return;
6137   }
6138 
6139   // Force declaration of implicit members so they can inherit the attribute.
6140   ForceDeclarationOfImplicitMembers(Class);
6141 
6142   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6143   // seem to be true in practice?
6144 
6145   for (Decl *Member : Class->decls()) {
6146     VarDecl *VD = dyn_cast<VarDecl>(Member);
6147     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6148 
6149     // Only methods and static fields inherit the attributes.
6150     if (!VD && !MD)
6151       continue;
6152 
6153     if (MD) {
6154       // Don't process deleted methods.
6155       if (MD->isDeleted())
6156         continue;
6157 
6158       if (MD->isInlined()) {
6159         // MinGW does not import or export inline methods. But do it for
6160         // template instantiations.
6161         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6162             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6163             TSK != TSK_ExplicitInstantiationDeclaration &&
6164             TSK != TSK_ExplicitInstantiationDefinition)
6165           continue;
6166 
6167         // MSVC versions before 2015 don't export the move assignment operators
6168         // and move constructor, so don't attempt to import/export them if
6169         // we have a definition.
6170         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6171         if ((MD->isMoveAssignmentOperator() ||
6172              (Ctor && Ctor->isMoveConstructor())) &&
6173             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6174           continue;
6175 
6176         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6177         // operator is exported anyway.
6178         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6179             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6180           continue;
6181       }
6182     }
6183 
6184     // Don't apply dllimport attributes to static data members of class template
6185     // instantiations when the attribute is propagated from a derived class.
6186     if (VD && PropagatedImport)
6187       continue;
6188 
6189     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6190       continue;
6191 
6192     if (!getDLLAttr(Member)) {
6193       InheritableAttr *NewAttr = nullptr;
6194 
6195       // Do not export/import inline function when -fno-dllexport-inlines is
6196       // passed. But add attribute for later local static var check.
6197       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6198           TSK != TSK_ExplicitInstantiationDeclaration &&
6199           TSK != TSK_ExplicitInstantiationDefinition) {
6200         if (ClassExported) {
6201           NewAttr = ::new (getASTContext())
6202               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6203         } else {
6204           NewAttr = ::new (getASTContext())
6205               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6206         }
6207       } else {
6208         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6209       }
6210 
6211       NewAttr->setInherited(true);
6212       Member->addAttr(NewAttr);
6213 
6214       if (MD) {
6215         // Propagate DLLAttr to friend re-declarations of MD that have already
6216         // been constructed.
6217         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6218              FD = FD->getPreviousDecl()) {
6219           if (FD->getFriendObjectKind() == Decl::FOK_None)
6220             continue;
6221           assert(!getDLLAttr(FD) &&
6222                  "friend re-decl should not already have a DLLAttr");
6223           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6224           NewAttr->setInherited(true);
6225           FD->addAttr(NewAttr);
6226         }
6227       }
6228     }
6229   }
6230 
6231   if (ClassExported)
6232     DelayedDllExportClasses.push_back(Class);
6233 }
6234 
6235 /// Perform propagation of DLL attributes from a derived class to a
6236 /// templated base class for MS compatibility.
6237 void Sema::propagateDLLAttrToBaseClassTemplate(
6238     CXXRecordDecl *Class, Attr *ClassAttr,
6239     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6240   if (getDLLAttr(
6241           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6242     // If the base class template has a DLL attribute, don't try to change it.
6243     return;
6244   }
6245 
6246   auto TSK = BaseTemplateSpec->getSpecializationKind();
6247   if (!getDLLAttr(BaseTemplateSpec) &&
6248       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6249        TSK == TSK_ImplicitInstantiation)) {
6250     // The template hasn't been instantiated yet (or it has, but only as an
6251     // explicit instantiation declaration or implicit instantiation, which means
6252     // we haven't codegenned any members yet), so propagate the attribute.
6253     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6254     NewAttr->setInherited(true);
6255     BaseTemplateSpec->addAttr(NewAttr);
6256 
6257     // If this was an import, mark that we propagated it from a derived class to
6258     // a base class template specialization.
6259     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6260       ImportAttr->setPropagatedToBaseTemplate();
6261 
6262     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6263     // needs to be run again to work see the new attribute. Otherwise this will
6264     // get run whenever the template is instantiated.
6265     if (TSK != TSK_Undeclared)
6266       checkClassLevelDLLAttribute(BaseTemplateSpec);
6267 
6268     return;
6269   }
6270 
6271   if (getDLLAttr(BaseTemplateSpec)) {
6272     // The template has already been specialized or instantiated with an
6273     // attribute, explicitly or through propagation. We should not try to change
6274     // it.
6275     return;
6276   }
6277 
6278   // The template was previously instantiated or explicitly specialized without
6279   // a dll attribute, It's too late for us to add an attribute, so warn that
6280   // this is unsupported.
6281   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6282       << BaseTemplateSpec->isExplicitSpecialization();
6283   Diag(ClassAttr->getLocation(), diag::note_attribute);
6284   if (BaseTemplateSpec->isExplicitSpecialization()) {
6285     Diag(BaseTemplateSpec->getLocation(),
6286            diag::note_template_class_explicit_specialization_was_here)
6287         << BaseTemplateSpec;
6288   } else {
6289     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6290            diag::note_template_class_instantiation_was_here)
6291         << BaseTemplateSpec;
6292   }
6293 }
6294 
6295 /// Determine the kind of defaulting that would be done for a given function.
6296 ///
6297 /// If the function is both a default constructor and a copy / move constructor
6298 /// (due to having a default argument for the first parameter), this picks
6299 /// CXXDefaultConstructor.
6300 ///
6301 /// FIXME: Check that case is properly handled by all callers.
6302 Sema::DefaultedFunctionKind
6303 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6304   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6305     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6306       if (Ctor->isDefaultConstructor())
6307         return Sema::CXXDefaultConstructor;
6308 
6309       if (Ctor->isCopyConstructor())
6310         return Sema::CXXCopyConstructor;
6311 
6312       if (Ctor->isMoveConstructor())
6313         return Sema::CXXMoveConstructor;
6314     }
6315 
6316     if (MD->isCopyAssignmentOperator())
6317       return Sema::CXXCopyAssignment;
6318 
6319     if (MD->isMoveAssignmentOperator())
6320       return Sema::CXXMoveAssignment;
6321 
6322     if (isa<CXXDestructorDecl>(FD))
6323       return Sema::CXXDestructor;
6324   }
6325 
6326   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6327   case OO_EqualEqual:
6328     return DefaultedComparisonKind::Equal;
6329 
6330   case OO_ExclaimEqual:
6331     return DefaultedComparisonKind::NotEqual;
6332 
6333   case OO_Spaceship:
6334     // No point allowing this if <=> doesn't exist in the current language mode.
6335     if (!getLangOpts().CPlusPlus20)
6336       break;
6337     return DefaultedComparisonKind::ThreeWay;
6338 
6339   case OO_Less:
6340   case OO_LessEqual:
6341   case OO_Greater:
6342   case OO_GreaterEqual:
6343     // No point allowing this if <=> doesn't exist in the current language mode.
6344     if (!getLangOpts().CPlusPlus20)
6345       break;
6346     return DefaultedComparisonKind::Relational;
6347 
6348   default:
6349     break;
6350   }
6351 
6352   // Not defaultable.
6353   return DefaultedFunctionKind();
6354 }
6355 
6356 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6357                                     SourceLocation DefaultLoc) {
6358   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6359   if (DFK.isComparison())
6360     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6361 
6362   switch (DFK.asSpecialMember()) {
6363   case Sema::CXXDefaultConstructor:
6364     S.DefineImplicitDefaultConstructor(DefaultLoc,
6365                                        cast<CXXConstructorDecl>(FD));
6366     break;
6367   case Sema::CXXCopyConstructor:
6368     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6369     break;
6370   case Sema::CXXCopyAssignment:
6371     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6372     break;
6373   case Sema::CXXDestructor:
6374     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6375     break;
6376   case Sema::CXXMoveConstructor:
6377     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6378     break;
6379   case Sema::CXXMoveAssignment:
6380     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6381     break;
6382   case Sema::CXXInvalid:
6383     llvm_unreachable("Invalid special member.");
6384   }
6385 }
6386 
6387 /// Determine whether a type is permitted to be passed or returned in
6388 /// registers, per C++ [class.temporary]p3.
6389 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6390                                TargetInfo::CallingConvKind CCK) {
6391   if (D->isDependentType() || D->isInvalidDecl())
6392     return false;
6393 
6394   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6395   // The PS4 platform ABI follows the behavior of Clang 3.2.
6396   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6397     return !D->hasNonTrivialDestructorForCall() &&
6398            !D->hasNonTrivialCopyConstructorForCall();
6399 
6400   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6401     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6402     bool DtorIsTrivialForCall = false;
6403 
6404     // If a class has at least one non-deleted, trivial copy constructor, it
6405     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6406     //
6407     // Note: This permits classes with non-trivial copy or move ctors to be
6408     // passed in registers, so long as they *also* have a trivial copy ctor,
6409     // which is non-conforming.
6410     if (D->needsImplicitCopyConstructor()) {
6411       if (!D->defaultedCopyConstructorIsDeleted()) {
6412         if (D->hasTrivialCopyConstructor())
6413           CopyCtorIsTrivial = true;
6414         if (D->hasTrivialCopyConstructorForCall())
6415           CopyCtorIsTrivialForCall = true;
6416       }
6417     } else {
6418       for (const CXXConstructorDecl *CD : D->ctors()) {
6419         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6420           if (CD->isTrivial())
6421             CopyCtorIsTrivial = true;
6422           if (CD->isTrivialForCall())
6423             CopyCtorIsTrivialForCall = true;
6424         }
6425       }
6426     }
6427 
6428     if (D->needsImplicitDestructor()) {
6429       if (!D->defaultedDestructorIsDeleted() &&
6430           D->hasTrivialDestructorForCall())
6431         DtorIsTrivialForCall = true;
6432     } else if (const auto *DD = D->getDestructor()) {
6433       if (!DD->isDeleted() && DD->isTrivialForCall())
6434         DtorIsTrivialForCall = true;
6435     }
6436 
6437     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6438     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6439       return true;
6440 
6441     // If a class has a destructor, we'd really like to pass it indirectly
6442     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6443     // impossible for small types, which it will pass in a single register or
6444     // stack slot. Most objects with dtors are large-ish, so handle that early.
6445     // We can't call out all large objects as being indirect because there are
6446     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6447     // how we pass large POD types.
6448 
6449     // Note: This permits small classes with nontrivial destructors to be
6450     // passed in registers, which is non-conforming.
6451     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6452     uint64_t TypeSize = isAArch64 ? 128 : 64;
6453 
6454     if (CopyCtorIsTrivial &&
6455         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6456       return true;
6457     return false;
6458   }
6459 
6460   // Per C++ [class.temporary]p3, the relevant condition is:
6461   //   each copy constructor, move constructor, and destructor of X is
6462   //   either trivial or deleted, and X has at least one non-deleted copy
6463   //   or move constructor
6464   bool HasNonDeletedCopyOrMove = false;
6465 
6466   if (D->needsImplicitCopyConstructor() &&
6467       !D->defaultedCopyConstructorIsDeleted()) {
6468     if (!D->hasTrivialCopyConstructorForCall())
6469       return false;
6470     HasNonDeletedCopyOrMove = true;
6471   }
6472 
6473   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6474       !D->defaultedMoveConstructorIsDeleted()) {
6475     if (!D->hasTrivialMoveConstructorForCall())
6476       return false;
6477     HasNonDeletedCopyOrMove = true;
6478   }
6479 
6480   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6481       !D->hasTrivialDestructorForCall())
6482     return false;
6483 
6484   for (const CXXMethodDecl *MD : D->methods()) {
6485     if (MD->isDeleted())
6486       continue;
6487 
6488     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6489     if (CD && CD->isCopyOrMoveConstructor())
6490       HasNonDeletedCopyOrMove = true;
6491     else if (!isa<CXXDestructorDecl>(MD))
6492       continue;
6493 
6494     if (!MD->isTrivialForCall())
6495       return false;
6496   }
6497 
6498   return HasNonDeletedCopyOrMove;
6499 }
6500 
6501 /// Report an error regarding overriding, along with any relevant
6502 /// overridden methods.
6503 ///
6504 /// \param DiagID the primary error to report.
6505 /// \param MD the overriding method.
6506 static bool
6507 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6508                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6509   bool IssuedDiagnostic = false;
6510   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6511     if (Report(O)) {
6512       if (!IssuedDiagnostic) {
6513         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6514         IssuedDiagnostic = true;
6515       }
6516       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6517     }
6518   }
6519   return IssuedDiagnostic;
6520 }
6521 
6522 /// Perform semantic checks on a class definition that has been
6523 /// completing, introducing implicitly-declared members, checking for
6524 /// abstract types, etc.
6525 ///
6526 /// \param S The scope in which the class was parsed. Null if we didn't just
6527 ///        parse a class definition.
6528 /// \param Record The completed class.
6529 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6530   if (!Record)
6531     return;
6532 
6533   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6534     AbstractUsageInfo Info(*this, Record);
6535     CheckAbstractClassUsage(Info, Record);
6536   }
6537 
6538   // If this is not an aggregate type and has no user-declared constructor,
6539   // complain about any non-static data members of reference or const scalar
6540   // type, since they will never get initializers.
6541   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6542       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6543       !Record->isLambda()) {
6544     bool Complained = false;
6545     for (const auto *F : Record->fields()) {
6546       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6547         continue;
6548 
6549       if (F->getType()->isReferenceType() ||
6550           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6551         if (!Complained) {
6552           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6553             << Record->getTagKind() << Record;
6554           Complained = true;
6555         }
6556 
6557         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6558           << F->getType()->isReferenceType()
6559           << F->getDeclName();
6560       }
6561     }
6562   }
6563 
6564   if (Record->getIdentifier()) {
6565     // C++ [class.mem]p13:
6566     //   If T is the name of a class, then each of the following shall have a
6567     //   name different from T:
6568     //     - every member of every anonymous union that is a member of class T.
6569     //
6570     // C++ [class.mem]p14:
6571     //   In addition, if class T has a user-declared constructor (12.1), every
6572     //   non-static data member of class T shall have a name different from T.
6573     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6574     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6575          ++I) {
6576       NamedDecl *D = (*I)->getUnderlyingDecl();
6577       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6578            Record->hasUserDeclaredConstructor()) ||
6579           isa<IndirectFieldDecl>(D)) {
6580         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6581           << D->getDeclName();
6582         break;
6583       }
6584     }
6585   }
6586 
6587   // Warn if the class has virtual methods but non-virtual public destructor.
6588   if (Record->isPolymorphic() && !Record->isDependentType()) {
6589     CXXDestructorDecl *dtor = Record->getDestructor();
6590     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6591         !Record->hasAttr<FinalAttr>())
6592       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6593            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6594   }
6595 
6596   if (Record->isAbstract()) {
6597     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6598       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6599         << FA->isSpelledAsSealed();
6600       DiagnoseAbstractType(Record);
6601     }
6602   }
6603 
6604   // Warn if the class has a final destructor but is not itself marked final.
6605   if (!Record->hasAttr<FinalAttr>()) {
6606     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6607       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6608         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6609             << FA->isSpelledAsSealed()
6610             << FixItHint::CreateInsertion(
6611                    getLocForEndOfToken(Record->getLocation()),
6612                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6613         Diag(Record->getLocation(),
6614              diag::note_final_dtor_non_final_class_silence)
6615             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6616       }
6617     }
6618   }
6619 
6620   // See if trivial_abi has to be dropped.
6621   if (Record->hasAttr<TrivialABIAttr>())
6622     checkIllFormedTrivialABIStruct(*Record);
6623 
6624   // Set HasTrivialSpecialMemberForCall if the record has attribute
6625   // "trivial_abi".
6626   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6627 
6628   if (HasTrivialABI)
6629     Record->setHasTrivialSpecialMemberForCall();
6630 
6631   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6632   // We check these last because they can depend on the properties of the
6633   // primary comparison functions (==, <=>).
6634   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6635 
6636   // Perform checks that can't be done until we know all the properties of a
6637   // member function (whether it's defaulted, deleted, virtual, overriding,
6638   // ...).
6639   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6640     // A static function cannot override anything.
6641     if (MD->getStorageClass() == SC_Static) {
6642       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6643                           [](const CXXMethodDecl *) { return true; }))
6644         return;
6645     }
6646 
6647     // A deleted function cannot override a non-deleted function and vice
6648     // versa.
6649     if (ReportOverrides(*this,
6650                         MD->isDeleted() ? diag::err_deleted_override
6651                                         : diag::err_non_deleted_override,
6652                         MD, [&](const CXXMethodDecl *V) {
6653                           return MD->isDeleted() != V->isDeleted();
6654                         })) {
6655       if (MD->isDefaulted() && MD->isDeleted())
6656         // Explain why this defaulted function was deleted.
6657         DiagnoseDeletedDefaultedFunction(MD);
6658       return;
6659     }
6660 
6661     // A consteval function cannot override a non-consteval function and vice
6662     // versa.
6663     if (ReportOverrides(*this,
6664                         MD->isConsteval() ? diag::err_consteval_override
6665                                           : diag::err_non_consteval_override,
6666                         MD, [&](const CXXMethodDecl *V) {
6667                           return MD->isConsteval() != V->isConsteval();
6668                         })) {
6669       if (MD->isDefaulted() && MD->isDeleted())
6670         // Explain why this defaulted function was deleted.
6671         DiagnoseDeletedDefaultedFunction(MD);
6672       return;
6673     }
6674   };
6675 
6676   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6677     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6678       return false;
6679 
6680     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6681     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6682         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6683       DefaultedSecondaryComparisons.push_back(FD);
6684       return true;
6685     }
6686 
6687     CheckExplicitlyDefaultedFunction(S, FD);
6688     return false;
6689   };
6690 
6691   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6692     // Check whether the explicitly-defaulted members are valid.
6693     bool Incomplete = CheckForDefaultedFunction(M);
6694 
6695     // Skip the rest of the checks for a member of a dependent class.
6696     if (Record->isDependentType())
6697       return;
6698 
6699     // For an explicitly defaulted or deleted special member, we defer
6700     // determining triviality until the class is complete. That time is now!
6701     CXXSpecialMember CSM = getSpecialMember(M);
6702     if (!M->isImplicit() && !M->isUserProvided()) {
6703       if (CSM != CXXInvalid) {
6704         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6705         // Inform the class that we've finished declaring this member.
6706         Record->finishedDefaultedOrDeletedMember(M);
6707         M->setTrivialForCall(
6708             HasTrivialABI ||
6709             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6710         Record->setTrivialForCallFlags(M);
6711       }
6712     }
6713 
6714     // Set triviality for the purpose of calls if this is a user-provided
6715     // copy/move constructor or destructor.
6716     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6717          CSM == CXXDestructor) && M->isUserProvided()) {
6718       M->setTrivialForCall(HasTrivialABI);
6719       Record->setTrivialForCallFlags(M);
6720     }
6721 
6722     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6723         M->hasAttr<DLLExportAttr>()) {
6724       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6725           M->isTrivial() &&
6726           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6727            CSM == CXXDestructor))
6728         M->dropAttr<DLLExportAttr>();
6729 
6730       if (M->hasAttr<DLLExportAttr>()) {
6731         // Define after any fields with in-class initializers have been parsed.
6732         DelayedDllExportMemberFunctions.push_back(M);
6733       }
6734     }
6735 
6736     // Define defaulted constexpr virtual functions that override a base class
6737     // function right away.
6738     // FIXME: We can defer doing this until the vtable is marked as used.
6739     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6740       DefineDefaultedFunction(*this, M, M->getLocation());
6741 
6742     if (!Incomplete)
6743       CheckCompletedMemberFunction(M);
6744   };
6745 
6746   // Check the destructor before any other member function. We need to
6747   // determine whether it's trivial in order to determine whether the claas
6748   // type is a literal type, which is a prerequisite for determining whether
6749   // other special member functions are valid and whether they're implicitly
6750   // 'constexpr'.
6751   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6752     CompleteMemberFunction(Dtor);
6753 
6754   bool HasMethodWithOverrideControl = false,
6755        HasOverridingMethodWithoutOverrideControl = false;
6756   for (auto *D : Record->decls()) {
6757     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6758       // FIXME: We could do this check for dependent types with non-dependent
6759       // bases.
6760       if (!Record->isDependentType()) {
6761         // See if a method overloads virtual methods in a base
6762         // class without overriding any.
6763         if (!M->isStatic())
6764           DiagnoseHiddenVirtualMethods(M);
6765         if (M->hasAttr<OverrideAttr>())
6766           HasMethodWithOverrideControl = true;
6767         else if (M->size_overridden_methods() > 0)
6768           HasOverridingMethodWithoutOverrideControl = true;
6769       }
6770 
6771       if (!isa<CXXDestructorDecl>(M))
6772         CompleteMemberFunction(M);
6773     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6774       CheckForDefaultedFunction(
6775           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6776     }
6777   }
6778 
6779   if (HasOverridingMethodWithoutOverrideControl) {
6780     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6781     for (auto *M : Record->methods())
6782       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6783   }
6784 
6785   // Check the defaulted secondary comparisons after any other member functions.
6786   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6787     CheckExplicitlyDefaultedFunction(S, FD);
6788 
6789     // If this is a member function, we deferred checking it until now.
6790     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6791       CheckCompletedMemberFunction(MD);
6792   }
6793 
6794   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6795   // whether this class uses any C++ features that are implemented
6796   // completely differently in MSVC, and if so, emit a diagnostic.
6797   // That diagnostic defaults to an error, but we allow projects to
6798   // map it down to a warning (or ignore it).  It's a fairly common
6799   // practice among users of the ms_struct pragma to mass-annotate
6800   // headers, sweeping up a bunch of types that the project doesn't
6801   // really rely on MSVC-compatible layout for.  We must therefore
6802   // support "ms_struct except for C++ stuff" as a secondary ABI.
6803   // Don't emit this diagnostic if the feature was enabled as a
6804   // language option (as opposed to via a pragma or attribute), as
6805   // the option -mms-bitfields otherwise essentially makes it impossible
6806   // to build C++ code, unless this diagnostic is turned off.
6807   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6808       (Record->isPolymorphic() || Record->getNumBases())) {
6809     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6810   }
6811 
6812   checkClassLevelDLLAttribute(Record);
6813   checkClassLevelCodeSegAttribute(Record);
6814 
6815   bool ClangABICompat4 =
6816       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6817   TargetInfo::CallingConvKind CCK =
6818       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6819   bool CanPass = canPassInRegisters(*this, Record, CCK);
6820 
6821   // Do not change ArgPassingRestrictions if it has already been set to
6822   // APK_CanNeverPassInRegs.
6823   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6824     Record->setArgPassingRestrictions(CanPass
6825                                           ? RecordDecl::APK_CanPassInRegs
6826                                           : RecordDecl::APK_CannotPassInRegs);
6827 
6828   // If canPassInRegisters returns true despite the record having a non-trivial
6829   // destructor, the record is destructed in the callee. This happens only when
6830   // the record or one of its subobjects has a field annotated with trivial_abi
6831   // or a field qualified with ObjC __strong/__weak.
6832   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6833     Record->setParamDestroyedInCallee(true);
6834   else if (Record->hasNonTrivialDestructor())
6835     Record->setParamDestroyedInCallee(CanPass);
6836 
6837   if (getLangOpts().ForceEmitVTables) {
6838     // If we want to emit all the vtables, we need to mark it as used.  This
6839     // is especially required for cases like vtable assumption loads.
6840     MarkVTableUsed(Record->getInnerLocStart(), Record);
6841   }
6842 
6843   if (getLangOpts().CUDA) {
6844     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6845       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6846     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6847       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6848   }
6849 }
6850 
6851 /// Look up the special member function that would be called by a special
6852 /// member function for a subobject of class type.
6853 ///
6854 /// \param Class The class type of the subobject.
6855 /// \param CSM The kind of special member function.
6856 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6857 /// \param ConstRHS True if this is a copy operation with a const object
6858 ///        on its RHS, that is, if the argument to the outer special member
6859 ///        function is 'const' and this is not a field marked 'mutable'.
6860 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6861     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6862     unsigned FieldQuals, bool ConstRHS) {
6863   unsigned LHSQuals = 0;
6864   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6865     LHSQuals = FieldQuals;
6866 
6867   unsigned RHSQuals = FieldQuals;
6868   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6869     RHSQuals = 0;
6870   else if (ConstRHS)
6871     RHSQuals |= Qualifiers::Const;
6872 
6873   return S.LookupSpecialMember(Class, CSM,
6874                                RHSQuals & Qualifiers::Const,
6875                                RHSQuals & Qualifiers::Volatile,
6876                                false,
6877                                LHSQuals & Qualifiers::Const,
6878                                LHSQuals & Qualifiers::Volatile);
6879 }
6880 
6881 class Sema::InheritedConstructorInfo {
6882   Sema &S;
6883   SourceLocation UseLoc;
6884 
6885   /// A mapping from the base classes through which the constructor was
6886   /// inherited to the using shadow declaration in that base class (or a null
6887   /// pointer if the constructor was declared in that base class).
6888   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6889       InheritedFromBases;
6890 
6891 public:
6892   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6893                            ConstructorUsingShadowDecl *Shadow)
6894       : S(S), UseLoc(UseLoc) {
6895     bool DiagnosedMultipleConstructedBases = false;
6896     CXXRecordDecl *ConstructedBase = nullptr;
6897     UsingDecl *ConstructedBaseUsing = nullptr;
6898 
6899     // Find the set of such base class subobjects and check that there's a
6900     // unique constructed subobject.
6901     for (auto *D : Shadow->redecls()) {
6902       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6903       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6904       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6905 
6906       InheritedFromBases.insert(
6907           std::make_pair(DNominatedBase->getCanonicalDecl(),
6908                          DShadow->getNominatedBaseClassShadowDecl()));
6909       if (DShadow->constructsVirtualBase())
6910         InheritedFromBases.insert(
6911             std::make_pair(DConstructedBase->getCanonicalDecl(),
6912                            DShadow->getConstructedBaseClassShadowDecl()));
6913       else
6914         assert(DNominatedBase == DConstructedBase);
6915 
6916       // [class.inhctor.init]p2:
6917       //   If the constructor was inherited from multiple base class subobjects
6918       //   of type B, the program is ill-formed.
6919       if (!ConstructedBase) {
6920         ConstructedBase = DConstructedBase;
6921         ConstructedBaseUsing = D->getUsingDecl();
6922       } else if (ConstructedBase != DConstructedBase &&
6923                  !Shadow->isInvalidDecl()) {
6924         if (!DiagnosedMultipleConstructedBases) {
6925           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6926               << Shadow->getTargetDecl();
6927           S.Diag(ConstructedBaseUsing->getLocation(),
6928                diag::note_ambiguous_inherited_constructor_using)
6929               << ConstructedBase;
6930           DiagnosedMultipleConstructedBases = true;
6931         }
6932         S.Diag(D->getUsingDecl()->getLocation(),
6933                diag::note_ambiguous_inherited_constructor_using)
6934             << DConstructedBase;
6935       }
6936     }
6937 
6938     if (DiagnosedMultipleConstructedBases)
6939       Shadow->setInvalidDecl();
6940   }
6941 
6942   /// Find the constructor to use for inherited construction of a base class,
6943   /// and whether that base class constructor inherits the constructor from a
6944   /// virtual base class (in which case it won't actually invoke it).
6945   std::pair<CXXConstructorDecl *, bool>
6946   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6947     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6948     if (It == InheritedFromBases.end())
6949       return std::make_pair(nullptr, false);
6950 
6951     // This is an intermediary class.
6952     if (It->second)
6953       return std::make_pair(
6954           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6955           It->second->constructsVirtualBase());
6956 
6957     // This is the base class from which the constructor was inherited.
6958     return std::make_pair(Ctor, false);
6959   }
6960 };
6961 
6962 /// Is the special member function which would be selected to perform the
6963 /// specified operation on the specified class type a constexpr constructor?
6964 static bool
6965 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6966                          Sema::CXXSpecialMember CSM, unsigned Quals,
6967                          bool ConstRHS,
6968                          CXXConstructorDecl *InheritedCtor = nullptr,
6969                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6970   // If we're inheriting a constructor, see if we need to call it for this base
6971   // class.
6972   if (InheritedCtor) {
6973     assert(CSM == Sema::CXXDefaultConstructor);
6974     auto BaseCtor =
6975         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6976     if (BaseCtor)
6977       return BaseCtor->isConstexpr();
6978   }
6979 
6980   if (CSM == Sema::CXXDefaultConstructor)
6981     return ClassDecl->hasConstexprDefaultConstructor();
6982   if (CSM == Sema::CXXDestructor)
6983     return ClassDecl->hasConstexprDestructor();
6984 
6985   Sema::SpecialMemberOverloadResult SMOR =
6986       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6987   if (!SMOR.getMethod())
6988     // A constructor we wouldn't select can't be "involved in initializing"
6989     // anything.
6990     return true;
6991   return SMOR.getMethod()->isConstexpr();
6992 }
6993 
6994 /// Determine whether the specified special member function would be constexpr
6995 /// if it were implicitly defined.
6996 static bool defaultedSpecialMemberIsConstexpr(
6997     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6998     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6999     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7000   if (!S.getLangOpts().CPlusPlus11)
7001     return false;
7002 
7003   // C++11 [dcl.constexpr]p4:
7004   // In the definition of a constexpr constructor [...]
7005   bool Ctor = true;
7006   switch (CSM) {
7007   case Sema::CXXDefaultConstructor:
7008     if (Inherited)
7009       break;
7010     // Since default constructor lookup is essentially trivial (and cannot
7011     // involve, for instance, template instantiation), we compute whether a
7012     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7013     //
7014     // This is important for performance; we need to know whether the default
7015     // constructor is constexpr to determine whether the type is a literal type.
7016     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7017 
7018   case Sema::CXXCopyConstructor:
7019   case Sema::CXXMoveConstructor:
7020     // For copy or move constructors, we need to perform overload resolution.
7021     break;
7022 
7023   case Sema::CXXCopyAssignment:
7024   case Sema::CXXMoveAssignment:
7025     if (!S.getLangOpts().CPlusPlus14)
7026       return false;
7027     // In C++1y, we need to perform overload resolution.
7028     Ctor = false;
7029     break;
7030 
7031   case Sema::CXXDestructor:
7032     return ClassDecl->defaultedDestructorIsConstexpr();
7033 
7034   case Sema::CXXInvalid:
7035     return false;
7036   }
7037 
7038   //   -- if the class is a non-empty union, or for each non-empty anonymous
7039   //      union member of a non-union class, exactly one non-static data member
7040   //      shall be initialized; [DR1359]
7041   //
7042   // If we squint, this is guaranteed, since exactly one non-static data member
7043   // will be initialized (if the constructor isn't deleted), we just don't know
7044   // which one.
7045   if (Ctor && ClassDecl->isUnion())
7046     return CSM == Sema::CXXDefaultConstructor
7047                ? ClassDecl->hasInClassInitializer() ||
7048                      !ClassDecl->hasVariantMembers()
7049                : true;
7050 
7051   //   -- the class shall not have any virtual base classes;
7052   if (Ctor && ClassDecl->getNumVBases())
7053     return false;
7054 
7055   // C++1y [class.copy]p26:
7056   //   -- [the class] is a literal type, and
7057   if (!Ctor && !ClassDecl->isLiteral())
7058     return false;
7059 
7060   //   -- every constructor involved in initializing [...] base class
7061   //      sub-objects shall be a constexpr constructor;
7062   //   -- the assignment operator selected to copy/move each direct base
7063   //      class is a constexpr function, and
7064   for (const auto &B : ClassDecl->bases()) {
7065     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7066     if (!BaseType) continue;
7067 
7068     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7069     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7070                                   InheritedCtor, Inherited))
7071       return false;
7072   }
7073 
7074   //   -- every constructor involved in initializing non-static data members
7075   //      [...] shall be a constexpr constructor;
7076   //   -- every non-static data member and base class sub-object shall be
7077   //      initialized
7078   //   -- for each non-static data member of X that is of class type (or array
7079   //      thereof), the assignment operator selected to copy/move that member is
7080   //      a constexpr function
7081   for (const auto *F : ClassDecl->fields()) {
7082     if (F->isInvalidDecl())
7083       continue;
7084     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7085       continue;
7086     QualType BaseType = S.Context.getBaseElementType(F->getType());
7087     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7088       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7089       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7090                                     BaseType.getCVRQualifiers(),
7091                                     ConstArg && !F->isMutable()))
7092         return false;
7093     } else if (CSM == Sema::CXXDefaultConstructor) {
7094       return false;
7095     }
7096   }
7097 
7098   // All OK, it's constexpr!
7099   return true;
7100 }
7101 
7102 namespace {
7103 /// RAII object to register a defaulted function as having its exception
7104 /// specification computed.
7105 struct ComputingExceptionSpec {
7106   Sema &S;
7107 
7108   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7109       : S(S) {
7110     Sema::CodeSynthesisContext Ctx;
7111     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7112     Ctx.PointOfInstantiation = Loc;
7113     Ctx.Entity = FD;
7114     S.pushCodeSynthesisContext(Ctx);
7115   }
7116   ~ComputingExceptionSpec() {
7117     S.popCodeSynthesisContext();
7118   }
7119 };
7120 }
7121 
7122 static Sema::ImplicitExceptionSpecification
7123 ComputeDefaultedSpecialMemberExceptionSpec(
7124     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7125     Sema::InheritedConstructorInfo *ICI);
7126 
7127 static Sema::ImplicitExceptionSpecification
7128 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7129                                         FunctionDecl *FD,
7130                                         Sema::DefaultedComparisonKind DCK);
7131 
7132 static Sema::ImplicitExceptionSpecification
7133 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7134   auto DFK = S.getDefaultedFunctionKind(FD);
7135   if (DFK.isSpecialMember())
7136     return ComputeDefaultedSpecialMemberExceptionSpec(
7137         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7138   if (DFK.isComparison())
7139     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7140                                                    DFK.asComparison());
7141 
7142   auto *CD = cast<CXXConstructorDecl>(FD);
7143   assert(CD->getInheritedConstructor() &&
7144          "only defaulted functions and inherited constructors have implicit "
7145          "exception specs");
7146   Sema::InheritedConstructorInfo ICI(
7147       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7148   return ComputeDefaultedSpecialMemberExceptionSpec(
7149       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7150 }
7151 
7152 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7153                                                             CXXMethodDecl *MD) {
7154   FunctionProtoType::ExtProtoInfo EPI;
7155 
7156   // Build an exception specification pointing back at this member.
7157   EPI.ExceptionSpec.Type = EST_Unevaluated;
7158   EPI.ExceptionSpec.SourceDecl = MD;
7159 
7160   // Set the calling convention to the default for C++ instance methods.
7161   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7162       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7163                                             /*IsCXXMethod=*/true));
7164   return EPI;
7165 }
7166 
7167 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7168   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7169   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7170     return;
7171 
7172   // Evaluate the exception specification.
7173   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7174   auto ESI = IES.getExceptionSpec();
7175 
7176   // Update the type of the special member to use it.
7177   UpdateExceptionSpec(FD, ESI);
7178 }
7179 
7180 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7181   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7182 
7183   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7184   if (!DefKind) {
7185     assert(FD->getDeclContext()->isDependentContext());
7186     return;
7187   }
7188 
7189   if (DefKind.isSpecialMember()
7190           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7191                                                   DefKind.asSpecialMember())
7192           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7193     FD->setInvalidDecl();
7194 }
7195 
7196 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7197                                                  CXXSpecialMember CSM) {
7198   CXXRecordDecl *RD = MD->getParent();
7199 
7200   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7201          "not an explicitly-defaulted special member");
7202 
7203   // Defer all checking for special members of a dependent type.
7204   if (RD->isDependentType())
7205     return false;
7206 
7207   // Whether this was the first-declared instance of the constructor.
7208   // This affects whether we implicitly add an exception spec and constexpr.
7209   bool First = MD == MD->getCanonicalDecl();
7210 
7211   bool HadError = false;
7212 
7213   // C++11 [dcl.fct.def.default]p1:
7214   //   A function that is explicitly defaulted shall
7215   //     -- be a special member function [...] (checked elsewhere),
7216   //     -- have the same type (except for ref-qualifiers, and except that a
7217   //        copy operation can take a non-const reference) as an implicit
7218   //        declaration, and
7219   //     -- not have default arguments.
7220   // C++2a changes the second bullet to instead delete the function if it's
7221   // defaulted on its first declaration, unless it's "an assignment operator,
7222   // and its return type differs or its parameter type is not a reference".
7223   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7224   bool ShouldDeleteForTypeMismatch = false;
7225   unsigned ExpectedParams = 1;
7226   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7227     ExpectedParams = 0;
7228   if (MD->getNumParams() != ExpectedParams) {
7229     // This checks for default arguments: a copy or move constructor with a
7230     // default argument is classified as a default constructor, and assignment
7231     // operations and destructors can't have default arguments.
7232     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7233       << CSM << MD->getSourceRange();
7234     HadError = true;
7235   } else if (MD->isVariadic()) {
7236     if (DeleteOnTypeMismatch)
7237       ShouldDeleteForTypeMismatch = true;
7238     else {
7239       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7240         << CSM << MD->getSourceRange();
7241       HadError = true;
7242     }
7243   }
7244 
7245   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7246 
7247   bool CanHaveConstParam = false;
7248   if (CSM == CXXCopyConstructor)
7249     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7250   else if (CSM == CXXCopyAssignment)
7251     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7252 
7253   QualType ReturnType = Context.VoidTy;
7254   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7255     // Check for return type matching.
7256     ReturnType = Type->getReturnType();
7257 
7258     QualType DeclType = Context.getTypeDeclType(RD);
7259     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7260     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7261 
7262     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7263       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7264         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7265       HadError = true;
7266     }
7267 
7268     // A defaulted special member cannot have cv-qualifiers.
7269     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7270       if (DeleteOnTypeMismatch)
7271         ShouldDeleteForTypeMismatch = true;
7272       else {
7273         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7274           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7275         HadError = true;
7276       }
7277     }
7278   }
7279 
7280   // Check for parameter type matching.
7281   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7282   bool HasConstParam = false;
7283   if (ExpectedParams && ArgType->isReferenceType()) {
7284     // Argument must be reference to possibly-const T.
7285     QualType ReferentType = ArgType->getPointeeType();
7286     HasConstParam = ReferentType.isConstQualified();
7287 
7288     if (ReferentType.isVolatileQualified()) {
7289       if (DeleteOnTypeMismatch)
7290         ShouldDeleteForTypeMismatch = true;
7291       else {
7292         Diag(MD->getLocation(),
7293              diag::err_defaulted_special_member_volatile_param) << CSM;
7294         HadError = true;
7295       }
7296     }
7297 
7298     if (HasConstParam && !CanHaveConstParam) {
7299       if (DeleteOnTypeMismatch)
7300         ShouldDeleteForTypeMismatch = true;
7301       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7302         Diag(MD->getLocation(),
7303              diag::err_defaulted_special_member_copy_const_param)
7304           << (CSM == CXXCopyAssignment);
7305         // FIXME: Explain why this special member can't be const.
7306         HadError = true;
7307       } else {
7308         Diag(MD->getLocation(),
7309              diag::err_defaulted_special_member_move_const_param)
7310           << (CSM == CXXMoveAssignment);
7311         HadError = true;
7312       }
7313     }
7314   } else if (ExpectedParams) {
7315     // A copy assignment operator can take its argument by value, but a
7316     // defaulted one cannot.
7317     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7318     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7319     HadError = true;
7320   }
7321 
7322   // C++11 [dcl.fct.def.default]p2:
7323   //   An explicitly-defaulted function may be declared constexpr only if it
7324   //   would have been implicitly declared as constexpr,
7325   // Do not apply this rule to members of class templates, since core issue 1358
7326   // makes such functions always instantiate to constexpr functions. For
7327   // functions which cannot be constexpr (for non-constructors in C++11 and for
7328   // destructors in C++14 and C++17), this is checked elsewhere.
7329   //
7330   // FIXME: This should not apply if the member is deleted.
7331   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7332                                                      HasConstParam);
7333   if ((getLangOpts().CPlusPlus20 ||
7334        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7335                                   : isa<CXXConstructorDecl>(MD))) &&
7336       MD->isConstexpr() && !Constexpr &&
7337       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7338     Diag(MD->getBeginLoc(), MD->isConsteval()
7339                                 ? diag::err_incorrect_defaulted_consteval
7340                                 : diag::err_incorrect_defaulted_constexpr)
7341         << CSM;
7342     // FIXME: Explain why the special member can't be constexpr.
7343     HadError = true;
7344   }
7345 
7346   if (First) {
7347     // C++2a [dcl.fct.def.default]p3:
7348     //   If a function is explicitly defaulted on its first declaration, it is
7349     //   implicitly considered to be constexpr if the implicit declaration
7350     //   would be.
7351     MD->setConstexprKind(
7352         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7353                   : CSK_unspecified);
7354 
7355     if (!Type->hasExceptionSpec()) {
7356       // C++2a [except.spec]p3:
7357       //   If a declaration of a function does not have a noexcept-specifier
7358       //   [and] is defaulted on its first declaration, [...] the exception
7359       //   specification is as specified below
7360       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7361       EPI.ExceptionSpec.Type = EST_Unevaluated;
7362       EPI.ExceptionSpec.SourceDecl = MD;
7363       MD->setType(Context.getFunctionType(ReturnType,
7364                                           llvm::makeArrayRef(&ArgType,
7365                                                              ExpectedParams),
7366                                           EPI));
7367     }
7368   }
7369 
7370   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7371     if (First) {
7372       SetDeclDeleted(MD, MD->getLocation());
7373       if (!inTemplateInstantiation() && !HadError) {
7374         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7375         if (ShouldDeleteForTypeMismatch) {
7376           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7377         } else {
7378           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7379         }
7380       }
7381       if (ShouldDeleteForTypeMismatch && !HadError) {
7382         Diag(MD->getLocation(),
7383              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7384       }
7385     } else {
7386       // C++11 [dcl.fct.def.default]p4:
7387       //   [For a] user-provided explicitly-defaulted function [...] if such a
7388       //   function is implicitly defined as deleted, the program is ill-formed.
7389       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7390       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7391       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7392       HadError = true;
7393     }
7394   }
7395 
7396   return HadError;
7397 }
7398 
7399 namespace {
7400 /// Helper class for building and checking a defaulted comparison.
7401 ///
7402 /// Defaulted functions are built in two phases:
7403 ///
7404 ///  * First, the set of operations that the function will perform are
7405 ///    identified, and some of them are checked. If any of the checked
7406 ///    operations is invalid in certain ways, the comparison function is
7407 ///    defined as deleted and no body is built.
7408 ///  * Then, if the function is not defined as deleted, the body is built.
7409 ///
7410 /// This is accomplished by performing two visitation steps over the eventual
7411 /// body of the function.
7412 template<typename Derived, typename ResultList, typename Result,
7413          typename Subobject>
7414 class DefaultedComparisonVisitor {
7415 public:
7416   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7417 
7418   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7419                              DefaultedComparisonKind DCK)
7420       : S(S), RD(RD), FD(FD), DCK(DCK) {
7421     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7422       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7423       // UnresolvedSet to avoid this copy.
7424       Fns.assign(Info->getUnqualifiedLookups().begin(),
7425                  Info->getUnqualifiedLookups().end());
7426     }
7427   }
7428 
7429   ResultList visit() {
7430     // The type of an lvalue naming a parameter of this function.
7431     QualType ParamLvalType =
7432         FD->getParamDecl(0)->getType().getNonReferenceType();
7433 
7434     ResultList Results;
7435 
7436     switch (DCK) {
7437     case DefaultedComparisonKind::None:
7438       llvm_unreachable("not a defaulted comparison");
7439 
7440     case DefaultedComparisonKind::Equal:
7441     case DefaultedComparisonKind::ThreeWay:
7442       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7443       return Results;
7444 
7445     case DefaultedComparisonKind::NotEqual:
7446     case DefaultedComparisonKind::Relational:
7447       Results.add(getDerived().visitExpandedSubobject(
7448           ParamLvalType, getDerived().getCompleteObject()));
7449       return Results;
7450     }
7451     llvm_unreachable("");
7452   }
7453 
7454 protected:
7455   Derived &getDerived() { return static_cast<Derived&>(*this); }
7456 
7457   /// Visit the expanded list of subobjects of the given type, as specified in
7458   /// C++2a [class.compare.default].
7459   ///
7460   /// \return \c true if the ResultList object said we're done, \c false if not.
7461   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7462                        Qualifiers Quals) {
7463     // C++2a [class.compare.default]p4:
7464     //   The direct base class subobjects of C
7465     for (CXXBaseSpecifier &Base : Record->bases())
7466       if (Results.add(getDerived().visitSubobject(
7467               S.Context.getQualifiedType(Base.getType(), Quals),
7468               getDerived().getBase(&Base))))
7469         return true;
7470 
7471     //   followed by the non-static data members of C
7472     for (FieldDecl *Field : Record->fields()) {
7473       // Recursively expand anonymous structs.
7474       if (Field->isAnonymousStructOrUnion()) {
7475         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7476                             Quals))
7477           return true;
7478         continue;
7479       }
7480 
7481       // Figure out the type of an lvalue denoting this field.
7482       Qualifiers FieldQuals = Quals;
7483       if (Field->isMutable())
7484         FieldQuals.removeConst();
7485       QualType FieldType =
7486           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7487 
7488       if (Results.add(getDerived().visitSubobject(
7489               FieldType, getDerived().getField(Field))))
7490         return true;
7491     }
7492 
7493     //   form a list of subobjects.
7494     return false;
7495   }
7496 
7497   Result visitSubobject(QualType Type, Subobject Subobj) {
7498     //   In that list, any subobject of array type is recursively expanded
7499     const ArrayType *AT = S.Context.getAsArrayType(Type);
7500     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7501       return getDerived().visitSubobjectArray(CAT->getElementType(),
7502                                               CAT->getSize(), Subobj);
7503     return getDerived().visitExpandedSubobject(Type, Subobj);
7504   }
7505 
7506   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7507                              Subobject Subobj) {
7508     return getDerived().visitSubobject(Type, Subobj);
7509   }
7510 
7511 protected:
7512   Sema &S;
7513   CXXRecordDecl *RD;
7514   FunctionDecl *FD;
7515   DefaultedComparisonKind DCK;
7516   UnresolvedSet<16> Fns;
7517 };
7518 
7519 /// Information about a defaulted comparison, as determined by
7520 /// DefaultedComparisonAnalyzer.
7521 struct DefaultedComparisonInfo {
7522   bool Deleted = false;
7523   bool Constexpr = true;
7524   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7525 
7526   static DefaultedComparisonInfo deleted() {
7527     DefaultedComparisonInfo Deleted;
7528     Deleted.Deleted = true;
7529     return Deleted;
7530   }
7531 
7532   bool add(const DefaultedComparisonInfo &R) {
7533     Deleted |= R.Deleted;
7534     Constexpr &= R.Constexpr;
7535     Category = commonComparisonType(Category, R.Category);
7536     return Deleted;
7537   }
7538 };
7539 
7540 /// An element in the expanded list of subobjects of a defaulted comparison, as
7541 /// specified in C++2a [class.compare.default]p4.
7542 struct DefaultedComparisonSubobject {
7543   enum { CompleteObject, Member, Base } Kind;
7544   NamedDecl *Decl;
7545   SourceLocation Loc;
7546 };
7547 
7548 /// A visitor over the notional body of a defaulted comparison that determines
7549 /// whether that body would be deleted or constexpr.
7550 class DefaultedComparisonAnalyzer
7551     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7552                                         DefaultedComparisonInfo,
7553                                         DefaultedComparisonInfo,
7554                                         DefaultedComparisonSubobject> {
7555 public:
7556   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7557 
7558 private:
7559   DiagnosticKind Diagnose;
7560 
7561 public:
7562   using Base = DefaultedComparisonVisitor;
7563   using Result = DefaultedComparisonInfo;
7564   using Subobject = DefaultedComparisonSubobject;
7565 
7566   friend Base;
7567 
7568   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7569                               DefaultedComparisonKind DCK,
7570                               DiagnosticKind Diagnose = NoDiagnostics)
7571       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7572 
7573   Result visit() {
7574     if ((DCK == DefaultedComparisonKind::Equal ||
7575          DCK == DefaultedComparisonKind::ThreeWay) &&
7576         RD->hasVariantMembers()) {
7577       // C++2a [class.compare.default]p2 [P2002R0]:
7578       //   A defaulted comparison operator function for class C is defined as
7579       //   deleted if [...] C has variant members.
7580       if (Diagnose == ExplainDeleted) {
7581         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7582           << FD << RD->isUnion() << RD;
7583       }
7584       return Result::deleted();
7585     }
7586 
7587     return Base::visit();
7588   }
7589 
7590 private:
7591   Subobject getCompleteObject() {
7592     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7593   }
7594 
7595   Subobject getBase(CXXBaseSpecifier *Base) {
7596     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7597                      Base->getBaseTypeLoc()};
7598   }
7599 
7600   Subobject getField(FieldDecl *Field) {
7601     return Subobject{Subobject::Member, Field, Field->getLocation()};
7602   }
7603 
7604   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7605     // C++2a [class.compare.default]p2 [P2002R0]:
7606     //   A defaulted <=> or == operator function for class C is defined as
7607     //   deleted if any non-static data member of C is of reference type
7608     if (Type->isReferenceType()) {
7609       if (Diagnose == ExplainDeleted) {
7610         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7611             << FD << RD;
7612       }
7613       return Result::deleted();
7614     }
7615 
7616     // [...] Let xi be an lvalue denoting the ith element [...]
7617     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7618     Expr *Args[] = {&Xi, &Xi};
7619 
7620     // All operators start by trying to apply that same operator recursively.
7621     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7622     assert(OO != OO_None && "not an overloaded operator!");
7623     return visitBinaryOperator(OO, Args, Subobj);
7624   }
7625 
7626   Result
7627   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7628                       Subobject Subobj,
7629                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7630     // Note that there is no need to consider rewritten candidates here if
7631     // we've already found there is no viable 'operator<=>' candidate (and are
7632     // considering synthesizing a '<=>' from '==' and '<').
7633     OverloadCandidateSet CandidateSet(
7634         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7635         OverloadCandidateSet::OperatorRewriteInfo(
7636             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7637 
7638     /// C++2a [class.compare.default]p1 [P2002R0]:
7639     ///   [...] the defaulted function itself is never a candidate for overload
7640     ///   resolution [...]
7641     CandidateSet.exclude(FD);
7642 
7643     if (Args[0]->getType()->isOverloadableType())
7644       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7645     else {
7646       // FIXME: We determine whether this is a valid expression by checking to
7647       // see if there's a viable builtin operator candidate for it. That isn't
7648       // really what the rules ask us to do, but should give the right results.
7649       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7650     }
7651 
7652     Result R;
7653 
7654     OverloadCandidateSet::iterator Best;
7655     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7656     case OR_Success: {
7657       // C++2a [class.compare.secondary]p2 [P2002R0]:
7658       //   The operator function [...] is defined as deleted if [...] the
7659       //   candidate selected by overload resolution is not a rewritten
7660       //   candidate.
7661       if ((DCK == DefaultedComparisonKind::NotEqual ||
7662            DCK == DefaultedComparisonKind::Relational) &&
7663           !Best->RewriteKind) {
7664         if (Diagnose == ExplainDeleted) {
7665           S.Diag(Best->Function->getLocation(),
7666                  diag::note_defaulted_comparison_not_rewritten_callee)
7667               << FD;
7668         }
7669         return Result::deleted();
7670       }
7671 
7672       // Throughout C++2a [class.compare]: if overload resolution does not
7673       // result in a usable function, the candidate function is defined as
7674       // deleted. This requires that we selected an accessible function.
7675       //
7676       // Note that this only considers the access of the function when named
7677       // within the type of the subobject, and not the access path for any
7678       // derived-to-base conversion.
7679       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7680       if (ArgClass && Best->FoundDecl.getDecl() &&
7681           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7682         QualType ObjectType = Subobj.Kind == Subobject::Member
7683                                   ? Args[0]->getType()
7684                                   : S.Context.getRecordType(RD);
7685         if (!S.isMemberAccessibleForDeletion(
7686                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7687                 Diagnose == ExplainDeleted
7688                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7689                           << FD << Subobj.Kind << Subobj.Decl
7690                     : S.PDiag()))
7691           return Result::deleted();
7692       }
7693 
7694       // C++2a [class.compare.default]p3 [P2002R0]:
7695       //   A defaulted comparison function is constexpr-compatible if [...]
7696       //   no overlod resolution performed [...] results in a non-constexpr
7697       //   function.
7698       if (FunctionDecl *BestFD = Best->Function) {
7699         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7700         // If it's not constexpr, explain why not.
7701         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7702           if (Subobj.Kind != Subobject::CompleteObject)
7703             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7704               << Subobj.Kind << Subobj.Decl;
7705           S.Diag(BestFD->getLocation(),
7706                  diag::note_defaulted_comparison_not_constexpr_here);
7707           // Bail out after explaining; we don't want any more notes.
7708           return Result::deleted();
7709         }
7710         R.Constexpr &= BestFD->isConstexpr();
7711       }
7712 
7713       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7714         if (auto *BestFD = Best->Function) {
7715           // If any callee has an undeduced return type, deduce it now.
7716           // FIXME: It's not clear how a failure here should be handled. For
7717           // now, we produce an eager diagnostic, because that is forward
7718           // compatible with most (all?) other reasonable options.
7719           if (BestFD->getReturnType()->isUndeducedType() &&
7720               S.DeduceReturnType(BestFD, FD->getLocation(),
7721                                  /*Diagnose=*/false)) {
7722             // Don't produce a duplicate error when asked to explain why the
7723             // comparison is deleted: we diagnosed that when initially checking
7724             // the defaulted operator.
7725             if (Diagnose == NoDiagnostics) {
7726               S.Diag(
7727                   FD->getLocation(),
7728                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7729                   << Subobj.Kind << Subobj.Decl;
7730               S.Diag(
7731                   Subobj.Loc,
7732                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7733                   << Subobj.Kind << Subobj.Decl;
7734               S.Diag(BestFD->getLocation(),
7735                      diag::note_defaulted_comparison_cannot_deduce_callee)
7736                   << Subobj.Kind << Subobj.Decl;
7737             }
7738             return Result::deleted();
7739           }
7740           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7741               BestFD->getCallResultType())) {
7742             R.Category = Info->Kind;
7743           } else {
7744             if (Diagnose == ExplainDeleted) {
7745               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7746                   << Subobj.Kind << Subobj.Decl
7747                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7748               S.Diag(BestFD->getLocation(),
7749                      diag::note_defaulted_comparison_cannot_deduce_callee)
7750                   << Subobj.Kind << Subobj.Decl;
7751             }
7752             return Result::deleted();
7753           }
7754         } else {
7755           Optional<ComparisonCategoryType> Cat =
7756               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7757           assert(Cat && "no category for builtin comparison?");
7758           R.Category = *Cat;
7759         }
7760       }
7761 
7762       // Note that we might be rewriting to a different operator. That call is
7763       // not considered until we come to actually build the comparison function.
7764       break;
7765     }
7766 
7767     case OR_Ambiguous:
7768       if (Diagnose == ExplainDeleted) {
7769         unsigned Kind = 0;
7770         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7771           Kind = OO == OO_EqualEqual ? 1 : 2;
7772         CandidateSet.NoteCandidates(
7773             PartialDiagnosticAt(
7774                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7775                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7776             S, OCD_AmbiguousCandidates, Args);
7777       }
7778       R = Result::deleted();
7779       break;
7780 
7781     case OR_Deleted:
7782       if (Diagnose == ExplainDeleted) {
7783         if ((DCK == DefaultedComparisonKind::NotEqual ||
7784              DCK == DefaultedComparisonKind::Relational) &&
7785             !Best->RewriteKind) {
7786           S.Diag(Best->Function->getLocation(),
7787                  diag::note_defaulted_comparison_not_rewritten_callee)
7788               << FD;
7789         } else {
7790           S.Diag(Subobj.Loc,
7791                  diag::note_defaulted_comparison_calls_deleted)
7792               << FD << Subobj.Kind << Subobj.Decl;
7793           S.NoteDeletedFunction(Best->Function);
7794         }
7795       }
7796       R = Result::deleted();
7797       break;
7798 
7799     case OR_No_Viable_Function:
7800       // If there's no usable candidate, we're done unless we can rewrite a
7801       // '<=>' in terms of '==' and '<'.
7802       if (OO == OO_Spaceship &&
7803           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7804         // For any kind of comparison category return type, we need a usable
7805         // '==' and a usable '<'.
7806         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7807                                        &CandidateSet)))
7808           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7809         break;
7810       }
7811 
7812       if (Diagnose == ExplainDeleted) {
7813         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7814             << FD << Subobj.Kind << Subobj.Decl;
7815 
7816         // For a three-way comparison, list both the candidates for the
7817         // original operator and the candidates for the synthesized operator.
7818         if (SpaceshipCandidates) {
7819           SpaceshipCandidates->NoteCandidates(
7820               S, Args,
7821               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7822                                                       Args, FD->getLocation()));
7823           S.Diag(Subobj.Loc,
7824                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7825               << (OO == OO_EqualEqual ? 0 : 1);
7826         }
7827 
7828         CandidateSet.NoteCandidates(
7829             S, Args,
7830             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7831                                             FD->getLocation()));
7832       }
7833       R = Result::deleted();
7834       break;
7835     }
7836 
7837     return R;
7838   }
7839 };
7840 
7841 /// A list of statements.
7842 struct StmtListResult {
7843   bool IsInvalid = false;
7844   llvm::SmallVector<Stmt*, 16> Stmts;
7845 
7846   bool add(const StmtResult &S) {
7847     IsInvalid |= S.isInvalid();
7848     if (IsInvalid)
7849       return true;
7850     Stmts.push_back(S.get());
7851     return false;
7852   }
7853 };
7854 
7855 /// A visitor over the notional body of a defaulted comparison that synthesizes
7856 /// the actual body.
7857 class DefaultedComparisonSynthesizer
7858     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7859                                         StmtListResult, StmtResult,
7860                                         std::pair<ExprResult, ExprResult>> {
7861   SourceLocation Loc;
7862   unsigned ArrayDepth = 0;
7863 
7864 public:
7865   using Base = DefaultedComparisonVisitor;
7866   using ExprPair = std::pair<ExprResult, ExprResult>;
7867 
7868   friend Base;
7869 
7870   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7871                                  DefaultedComparisonKind DCK,
7872                                  SourceLocation BodyLoc)
7873       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7874 
7875   /// Build a suitable function body for this defaulted comparison operator.
7876   StmtResult build() {
7877     Sema::CompoundScopeRAII CompoundScope(S);
7878 
7879     StmtListResult Stmts = visit();
7880     if (Stmts.IsInvalid)
7881       return StmtError();
7882 
7883     ExprResult RetVal;
7884     switch (DCK) {
7885     case DefaultedComparisonKind::None:
7886       llvm_unreachable("not a defaulted comparison");
7887 
7888     case DefaultedComparisonKind::Equal: {
7889       // C++2a [class.eq]p3:
7890       //   [...] compar[e] the corresponding elements [...] until the first
7891       //   index i where xi == yi yields [...] false. If no such index exists,
7892       //   V is true. Otherwise, V is false.
7893       //
7894       // Join the comparisons with '&&'s and return the result. Use a right
7895       // fold (traversing the conditions right-to-left), because that
7896       // short-circuits more naturally.
7897       auto OldStmts = std::move(Stmts.Stmts);
7898       Stmts.Stmts.clear();
7899       ExprResult CmpSoFar;
7900       // Finish a particular comparison chain.
7901       auto FinishCmp = [&] {
7902         if (Expr *Prior = CmpSoFar.get()) {
7903           // Convert the last expression to 'return ...;'
7904           if (RetVal.isUnset() && Stmts.Stmts.empty())
7905             RetVal = CmpSoFar;
7906           // Convert any prior comparison to 'if (!(...)) return false;'
7907           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7908             return true;
7909           CmpSoFar = ExprResult();
7910         }
7911         return false;
7912       };
7913       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7914         Expr *E = dyn_cast<Expr>(EAsStmt);
7915         if (!E) {
7916           // Found an array comparison.
7917           if (FinishCmp() || Stmts.add(EAsStmt))
7918             return StmtError();
7919           continue;
7920         }
7921 
7922         if (CmpSoFar.isUnset()) {
7923           CmpSoFar = E;
7924           continue;
7925         }
7926         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7927         if (CmpSoFar.isInvalid())
7928           return StmtError();
7929       }
7930       if (FinishCmp())
7931         return StmtError();
7932       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7933       //   If no such index exists, V is true.
7934       if (RetVal.isUnset())
7935         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7936       break;
7937     }
7938 
7939     case DefaultedComparisonKind::ThreeWay: {
7940       // Per C++2a [class.spaceship]p3, as a fallback add:
7941       // return static_cast<R>(std::strong_ordering::equal);
7942       QualType StrongOrdering = S.CheckComparisonCategoryType(
7943           ComparisonCategoryType::StrongOrdering, Loc,
7944           Sema::ComparisonCategoryUsage::DefaultedOperator);
7945       if (StrongOrdering.isNull())
7946         return StmtError();
7947       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7948                              .getValueInfo(ComparisonCategoryResult::Equal)
7949                              ->VD;
7950       RetVal = getDecl(EqualVD);
7951       if (RetVal.isInvalid())
7952         return StmtError();
7953       RetVal = buildStaticCastToR(RetVal.get());
7954       break;
7955     }
7956 
7957     case DefaultedComparisonKind::NotEqual:
7958     case DefaultedComparisonKind::Relational:
7959       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7960       break;
7961     }
7962 
7963     // Build the final return statement.
7964     if (RetVal.isInvalid())
7965       return StmtError();
7966     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7967     if (ReturnStmt.isInvalid())
7968       return StmtError();
7969     Stmts.Stmts.push_back(ReturnStmt.get());
7970 
7971     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7972   }
7973 
7974 private:
7975   ExprResult getDecl(ValueDecl *VD) {
7976     return S.BuildDeclarationNameExpr(
7977         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7978   }
7979 
7980   ExprResult getParam(unsigned I) {
7981     ParmVarDecl *PD = FD->getParamDecl(I);
7982     return getDecl(PD);
7983   }
7984 
7985   ExprPair getCompleteObject() {
7986     unsigned Param = 0;
7987     ExprResult LHS;
7988     if (isa<CXXMethodDecl>(FD)) {
7989       // LHS is '*this'.
7990       LHS = S.ActOnCXXThis(Loc);
7991       if (!LHS.isInvalid())
7992         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7993     } else {
7994       LHS = getParam(Param++);
7995     }
7996     ExprResult RHS = getParam(Param++);
7997     assert(Param == FD->getNumParams());
7998     return {LHS, RHS};
7999   }
8000 
8001   ExprPair getBase(CXXBaseSpecifier *Base) {
8002     ExprPair Obj = getCompleteObject();
8003     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8004       return {ExprError(), ExprError()};
8005     CXXCastPath Path = {Base};
8006     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8007                                 CK_DerivedToBase, VK_LValue, &Path),
8008             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8009                                 CK_DerivedToBase, VK_LValue, &Path)};
8010   }
8011 
8012   ExprPair getField(FieldDecl *Field) {
8013     ExprPair Obj = getCompleteObject();
8014     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8015       return {ExprError(), ExprError()};
8016 
8017     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8018     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8019     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8020                                       CXXScopeSpec(), Field, Found, NameInfo),
8021             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8022                                       CXXScopeSpec(), Field, Found, NameInfo)};
8023   }
8024 
8025   // FIXME: When expanding a subobject, register a note in the code synthesis
8026   // stack to say which subobject we're comparing.
8027 
8028   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8029     if (Cond.isInvalid())
8030       return StmtError();
8031 
8032     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8033     if (NotCond.isInvalid())
8034       return StmtError();
8035 
8036     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8037     assert(!False.isInvalid() && "should never fail");
8038     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8039     if (ReturnFalse.isInvalid())
8040       return StmtError();
8041 
8042     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8043                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8044                                           Sema::ConditionKind::Boolean),
8045                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8046   }
8047 
8048   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8049                                  ExprPair Subobj) {
8050     QualType SizeType = S.Context.getSizeType();
8051     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8052 
8053     // Build 'size_t i$n = 0'.
8054     IdentifierInfo *IterationVarName = nullptr;
8055     {
8056       SmallString<8> Str;
8057       llvm::raw_svector_ostream OS(Str);
8058       OS << "i" << ArrayDepth;
8059       IterationVarName = &S.Context.Idents.get(OS.str());
8060     }
8061     VarDecl *IterationVar = VarDecl::Create(
8062         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8063         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8064     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8065     IterationVar->setInit(
8066         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8067     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8068 
8069     auto IterRef = [&] {
8070       ExprResult Ref = S.BuildDeclarationNameExpr(
8071           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8072           IterationVar);
8073       assert(!Ref.isInvalid() && "can't reference our own variable?");
8074       return Ref.get();
8075     };
8076 
8077     // Build 'i$n != Size'.
8078     ExprResult Cond = S.CreateBuiltinBinOp(
8079         Loc, BO_NE, IterRef(),
8080         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8081     assert(!Cond.isInvalid() && "should never fail");
8082 
8083     // Build '++i$n'.
8084     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8085     assert(!Inc.isInvalid() && "should never fail");
8086 
8087     // Build 'a[i$n]' and 'b[i$n]'.
8088     auto Index = [&](ExprResult E) {
8089       if (E.isInvalid())
8090         return ExprError();
8091       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8092     };
8093     Subobj.first = Index(Subobj.first);
8094     Subobj.second = Index(Subobj.second);
8095 
8096     // Compare the array elements.
8097     ++ArrayDepth;
8098     StmtResult Substmt = visitSubobject(Type, Subobj);
8099     --ArrayDepth;
8100 
8101     if (Substmt.isInvalid())
8102       return StmtError();
8103 
8104     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8105     // For outer levels or for an 'operator<=>' we already have a suitable
8106     // statement that returns as necessary.
8107     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8108       assert(DCK == DefaultedComparisonKind::Equal &&
8109              "should have non-expression statement");
8110       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8111       if (Substmt.isInvalid())
8112         return StmtError();
8113     }
8114 
8115     // Build 'for (...) ...'
8116     return S.ActOnForStmt(Loc, Loc, Init,
8117                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8118                                            Sema::ConditionKind::Boolean),
8119                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8120                           Substmt.get());
8121   }
8122 
8123   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8124     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8125       return StmtError();
8126 
8127     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8128     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8129     ExprResult Op;
8130     if (Type->isOverloadableType())
8131       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8132                                    Obj.second.get(), /*PerformADL=*/true,
8133                                    /*AllowRewrittenCandidates=*/true, FD);
8134     else
8135       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8136     if (Op.isInvalid())
8137       return StmtError();
8138 
8139     switch (DCK) {
8140     case DefaultedComparisonKind::None:
8141       llvm_unreachable("not a defaulted comparison");
8142 
8143     case DefaultedComparisonKind::Equal:
8144       // Per C++2a [class.eq]p2, each comparison is individually contextually
8145       // converted to bool.
8146       Op = S.PerformContextuallyConvertToBool(Op.get());
8147       if (Op.isInvalid())
8148         return StmtError();
8149       return Op.get();
8150 
8151     case DefaultedComparisonKind::ThreeWay: {
8152       // Per C++2a [class.spaceship]p3, form:
8153       //   if (R cmp = static_cast<R>(op); cmp != 0)
8154       //     return cmp;
8155       QualType R = FD->getReturnType();
8156       Op = buildStaticCastToR(Op.get());
8157       if (Op.isInvalid())
8158         return StmtError();
8159 
8160       // R cmp = ...;
8161       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8162       VarDecl *VD =
8163           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8164                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8165       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8166       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8167 
8168       // cmp != 0
8169       ExprResult VDRef = getDecl(VD);
8170       if (VDRef.isInvalid())
8171         return StmtError();
8172       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8173       Expr *Zero =
8174           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8175       ExprResult Comp;
8176       if (VDRef.get()->getType()->isOverloadableType())
8177         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8178                                        true, FD);
8179       else
8180         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8181       if (Comp.isInvalid())
8182         return StmtError();
8183       Sema::ConditionResult Cond = S.ActOnCondition(
8184           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8185       if (Cond.isInvalid())
8186         return StmtError();
8187 
8188       // return cmp;
8189       VDRef = getDecl(VD);
8190       if (VDRef.isInvalid())
8191         return StmtError();
8192       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8193       if (ReturnStmt.isInvalid())
8194         return StmtError();
8195 
8196       // if (...)
8197       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8198                            ReturnStmt.get(),
8199                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8200     }
8201 
8202     case DefaultedComparisonKind::NotEqual:
8203     case DefaultedComparisonKind::Relational:
8204       // C++2a [class.compare.secondary]p2:
8205       //   Otherwise, the operator function yields x @ y.
8206       return Op.get();
8207     }
8208     llvm_unreachable("");
8209   }
8210 
8211   /// Build "static_cast<R>(E)".
8212   ExprResult buildStaticCastToR(Expr *E) {
8213     QualType R = FD->getReturnType();
8214     assert(!R->isUndeducedType() && "type should have been deduced already");
8215 
8216     // Don't bother forming a no-op cast in the common case.
8217     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8218       return E;
8219     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8220                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8221                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8222   }
8223 };
8224 }
8225 
8226 /// Perform the unqualified lookups that might be needed to form a defaulted
8227 /// comparison function for the given operator.
8228 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8229                                                   UnresolvedSetImpl &Operators,
8230                                                   OverloadedOperatorKind Op) {
8231   auto Lookup = [&](OverloadedOperatorKind OO) {
8232     Self.LookupOverloadedOperatorName(OO, S, Operators);
8233   };
8234 
8235   // Every defaulted operator looks up itself.
8236   Lookup(Op);
8237   // ... and the rewritten form of itself, if any.
8238   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8239     Lookup(ExtraOp);
8240 
8241   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8242   // synthesize a three-way comparison from '<' and '=='. In a dependent
8243   // context, we also need to look up '==' in case we implicitly declare a
8244   // defaulted 'operator=='.
8245   if (Op == OO_Spaceship) {
8246     Lookup(OO_ExclaimEqual);
8247     Lookup(OO_Less);
8248     Lookup(OO_EqualEqual);
8249   }
8250 }
8251 
8252 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8253                                               DefaultedComparisonKind DCK) {
8254   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8255 
8256   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8257   assert(RD && "defaulted comparison is not defaulted in a class");
8258 
8259   // Perform any unqualified lookups we're going to need to default this
8260   // function.
8261   if (S) {
8262     UnresolvedSet<32> Operators;
8263     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8264                                           FD->getOverloadedOperator());
8265     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8266         Context, Operators.pairs()));
8267   }
8268 
8269   // C++2a [class.compare.default]p1:
8270   //   A defaulted comparison operator function for some class C shall be a
8271   //   non-template function declared in the member-specification of C that is
8272   //    -- a non-static const member of C having one parameter of type
8273   //       const C&, or
8274   //    -- a friend of C having two parameters of type const C& or two
8275   //       parameters of type C.
8276   QualType ExpectedParmType1 = Context.getRecordType(RD);
8277   QualType ExpectedParmType2 =
8278       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8279   if (isa<CXXMethodDecl>(FD))
8280     ExpectedParmType1 = ExpectedParmType2;
8281   for (const ParmVarDecl *Param : FD->parameters()) {
8282     if (!Param->getType()->isDependentType() &&
8283         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8284         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8285       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8286       // corresponding defaulted 'operator<=>' already.
8287       if (!FD->isImplicit()) {
8288         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8289             << (int)DCK << Param->getType() << ExpectedParmType1
8290             << !isa<CXXMethodDecl>(FD)
8291             << ExpectedParmType2 << Param->getSourceRange();
8292       }
8293       return true;
8294     }
8295   }
8296   if (FD->getNumParams() == 2 &&
8297       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8298                            FD->getParamDecl(1)->getType())) {
8299     if (!FD->isImplicit()) {
8300       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8301           << (int)DCK
8302           << FD->getParamDecl(0)->getType()
8303           << FD->getParamDecl(0)->getSourceRange()
8304           << FD->getParamDecl(1)->getType()
8305           << FD->getParamDecl(1)->getSourceRange();
8306     }
8307     return true;
8308   }
8309 
8310   // ... non-static const member ...
8311   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8312     assert(!MD->isStatic() && "comparison function cannot be a static member");
8313     if (!MD->isConst()) {
8314       SourceLocation InsertLoc;
8315       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8316         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8317       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8318       // corresponding defaulted 'operator<=>' already.
8319       if (!MD->isImplicit()) {
8320         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8321           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8322       }
8323 
8324       // Add the 'const' to the type to recover.
8325       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8326       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8327       EPI.TypeQuals.addConst();
8328       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8329                                           FPT->getParamTypes(), EPI));
8330     }
8331   } else {
8332     // A non-member function declared in a class must be a friend.
8333     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8334   }
8335 
8336   // C++2a [class.eq]p1, [class.rel]p1:
8337   //   A [defaulted comparison other than <=>] shall have a declared return
8338   //   type bool.
8339   if (DCK != DefaultedComparisonKind::ThreeWay &&
8340       !FD->getDeclaredReturnType()->isDependentType() &&
8341       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8342     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8343         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8344         << FD->getReturnTypeSourceRange();
8345     return true;
8346   }
8347   // C++2a [class.spaceship]p2 [P2002R0]:
8348   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8349   //   R shall not contain a placeholder type.
8350   if (DCK == DefaultedComparisonKind::ThreeWay &&
8351       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8352       !Context.hasSameType(FD->getDeclaredReturnType(),
8353                            Context.getAutoDeductType())) {
8354     Diag(FD->getLocation(),
8355          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8356         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8357         << FD->getReturnTypeSourceRange();
8358     return true;
8359   }
8360 
8361   // For a defaulted function in a dependent class, defer all remaining checks
8362   // until instantiation.
8363   if (RD->isDependentType())
8364     return false;
8365 
8366   // Determine whether the function should be defined as deleted.
8367   DefaultedComparisonInfo Info =
8368       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8369 
8370   bool First = FD == FD->getCanonicalDecl();
8371 
8372   // If we want to delete the function, then do so; there's nothing else to
8373   // check in that case.
8374   if (Info.Deleted) {
8375     if (!First) {
8376       // C++11 [dcl.fct.def.default]p4:
8377       //   [For a] user-provided explicitly-defaulted function [...] if such a
8378       //   function is implicitly defined as deleted, the program is ill-formed.
8379       //
8380       // This is really just a consequence of the general rule that you can
8381       // only delete a function on its first declaration.
8382       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8383           << FD->isImplicit() << (int)DCK;
8384       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8385                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8386           .visit();
8387       return true;
8388     }
8389 
8390     SetDeclDeleted(FD, FD->getLocation());
8391     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8392       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8393           << (int)DCK;
8394       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8395                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8396           .visit();
8397     }
8398     return false;
8399   }
8400 
8401   // C++2a [class.spaceship]p2:
8402   //   The return type is deduced as the common comparison type of R0, R1, ...
8403   if (DCK == DefaultedComparisonKind::ThreeWay &&
8404       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8405     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8406     if (RetLoc.isInvalid())
8407       RetLoc = FD->getBeginLoc();
8408     // FIXME: Should we really care whether we have the complete type and the
8409     // 'enumerator' constants here? A forward declaration seems sufficient.
8410     QualType Cat = CheckComparisonCategoryType(
8411         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8412     if (Cat.isNull())
8413       return true;
8414     Context.adjustDeducedFunctionResultType(
8415         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8416   }
8417 
8418   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8419   //   An explicitly-defaulted function that is not defined as deleted may be
8420   //   declared constexpr or consteval only if it is constexpr-compatible.
8421   // C++2a [class.compare.default]p3 [P2002R0]:
8422   //   A defaulted comparison function is constexpr-compatible if it satisfies
8423   //   the requirements for a constexpr function [...]
8424   // The only relevant requirements are that the parameter and return types are
8425   // literal types. The remaining conditions are checked by the analyzer.
8426   if (FD->isConstexpr()) {
8427     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8428         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8429         !Info.Constexpr) {
8430       Diag(FD->getBeginLoc(),
8431            diag::err_incorrect_defaulted_comparison_constexpr)
8432           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8433       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8434                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8435           .visit();
8436     }
8437   }
8438 
8439   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8440   //   If a constexpr-compatible function is explicitly defaulted on its first
8441   //   declaration, it is implicitly considered to be constexpr.
8442   // FIXME: Only applying this to the first declaration seems problematic, as
8443   // simple reorderings can affect the meaning of the program.
8444   if (First && !FD->isConstexpr() && Info.Constexpr)
8445     FD->setConstexprKind(CSK_constexpr);
8446 
8447   // C++2a [except.spec]p3:
8448   //   If a declaration of a function does not have a noexcept-specifier
8449   //   [and] is defaulted on its first declaration, [...] the exception
8450   //   specification is as specified below
8451   if (FD->getExceptionSpecType() == EST_None) {
8452     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8453     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8454     EPI.ExceptionSpec.Type = EST_Unevaluated;
8455     EPI.ExceptionSpec.SourceDecl = FD;
8456     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8457                                         FPT->getParamTypes(), EPI));
8458   }
8459 
8460   return false;
8461 }
8462 
8463 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8464                                              FunctionDecl *Spaceship) {
8465   Sema::CodeSynthesisContext Ctx;
8466   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8467   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8468   Ctx.Entity = Spaceship;
8469   pushCodeSynthesisContext(Ctx);
8470 
8471   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8472     EqualEqual->setImplicit();
8473 
8474   popCodeSynthesisContext();
8475 }
8476 
8477 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8478                                      DefaultedComparisonKind DCK) {
8479   assert(FD->isDefaulted() && !FD->isDeleted() &&
8480          !FD->doesThisDeclarationHaveABody());
8481   if (FD->willHaveBody() || FD->isInvalidDecl())
8482     return;
8483 
8484   SynthesizedFunctionScope Scope(*this, FD);
8485 
8486   // Add a context note for diagnostics produced after this point.
8487   Scope.addContextNote(UseLoc);
8488 
8489   {
8490     // Build and set up the function body.
8491     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8492     SourceLocation BodyLoc =
8493         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8494     StmtResult Body =
8495         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8496     if (Body.isInvalid()) {
8497       FD->setInvalidDecl();
8498       return;
8499     }
8500     FD->setBody(Body.get());
8501     FD->markUsed(Context);
8502   }
8503 
8504   // The exception specification is needed because we are defining the
8505   // function. Note that this will reuse the body we just built.
8506   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8507 
8508   if (ASTMutationListener *L = getASTMutationListener())
8509     L->CompletedImplicitDefinition(FD);
8510 }
8511 
8512 static Sema::ImplicitExceptionSpecification
8513 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8514                                         FunctionDecl *FD,
8515                                         Sema::DefaultedComparisonKind DCK) {
8516   ComputingExceptionSpec CES(S, FD, Loc);
8517   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8518 
8519   if (FD->isInvalidDecl())
8520     return ExceptSpec;
8521 
8522   // The common case is that we just defined the comparison function. In that
8523   // case, just look at whether the body can throw.
8524   if (FD->hasBody()) {
8525     ExceptSpec.CalledStmt(FD->getBody());
8526   } else {
8527     // Otherwise, build a body so we can check it. This should ideally only
8528     // happen when we're not actually marking the function referenced. (This is
8529     // only really important for efficiency: we don't want to build and throw
8530     // away bodies for comparison functions more than we strictly need to.)
8531 
8532     // Pretend to synthesize the function body in an unevaluated context.
8533     // Note that we can't actually just go ahead and define the function here:
8534     // we are not permitted to mark its callees as referenced.
8535     Sema::SynthesizedFunctionScope Scope(S, FD);
8536     EnterExpressionEvaluationContext Context(
8537         S, Sema::ExpressionEvaluationContext::Unevaluated);
8538 
8539     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8540     SourceLocation BodyLoc =
8541         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8542     StmtResult Body =
8543         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8544     if (!Body.isInvalid())
8545       ExceptSpec.CalledStmt(Body.get());
8546 
8547     // FIXME: Can we hold onto this body and just transform it to potentially
8548     // evaluated when we're asked to define the function rather than rebuilding
8549     // it? Either that, or we should only build the bits of the body that we
8550     // need (the expressions, not the statements).
8551   }
8552 
8553   return ExceptSpec;
8554 }
8555 
8556 void Sema::CheckDelayedMemberExceptionSpecs() {
8557   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8558   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8559 
8560   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8561   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8562 
8563   // Perform any deferred checking of exception specifications for virtual
8564   // destructors.
8565   for (auto &Check : Overriding)
8566     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8567 
8568   // Perform any deferred checking of exception specifications for befriended
8569   // special members.
8570   for (auto &Check : Equivalent)
8571     CheckEquivalentExceptionSpec(Check.second, Check.first);
8572 }
8573 
8574 namespace {
8575 /// CRTP base class for visiting operations performed by a special member
8576 /// function (or inherited constructor).
8577 template<typename Derived>
8578 struct SpecialMemberVisitor {
8579   Sema &S;
8580   CXXMethodDecl *MD;
8581   Sema::CXXSpecialMember CSM;
8582   Sema::InheritedConstructorInfo *ICI;
8583 
8584   // Properties of the special member, computed for convenience.
8585   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8586 
8587   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8588                        Sema::InheritedConstructorInfo *ICI)
8589       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8590     switch (CSM) {
8591     case Sema::CXXDefaultConstructor:
8592     case Sema::CXXCopyConstructor:
8593     case Sema::CXXMoveConstructor:
8594       IsConstructor = true;
8595       break;
8596     case Sema::CXXCopyAssignment:
8597     case Sema::CXXMoveAssignment:
8598       IsAssignment = true;
8599       break;
8600     case Sema::CXXDestructor:
8601       break;
8602     case Sema::CXXInvalid:
8603       llvm_unreachable("invalid special member kind");
8604     }
8605 
8606     if (MD->getNumParams()) {
8607       if (const ReferenceType *RT =
8608               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8609         ConstArg = RT->getPointeeType().isConstQualified();
8610     }
8611   }
8612 
8613   Derived &getDerived() { return static_cast<Derived&>(*this); }
8614 
8615   /// Is this a "move" special member?
8616   bool isMove() const {
8617     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8618   }
8619 
8620   /// Look up the corresponding special member in the given class.
8621   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8622                                              unsigned Quals, bool IsMutable) {
8623     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8624                                        ConstArg && !IsMutable);
8625   }
8626 
8627   /// Look up the constructor for the specified base class to see if it's
8628   /// overridden due to this being an inherited constructor.
8629   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8630     if (!ICI)
8631       return {};
8632     assert(CSM == Sema::CXXDefaultConstructor);
8633     auto *BaseCtor =
8634       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8635     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8636       return MD;
8637     return {};
8638   }
8639 
8640   /// A base or member subobject.
8641   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8642 
8643   /// Get the location to use for a subobject in diagnostics.
8644   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8645     // FIXME: For an indirect virtual base, the direct base leading to
8646     // the indirect virtual base would be a more useful choice.
8647     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8648       return B->getBaseTypeLoc();
8649     else
8650       return Subobj.get<FieldDecl*>()->getLocation();
8651   }
8652 
8653   enum BasesToVisit {
8654     /// Visit all non-virtual (direct) bases.
8655     VisitNonVirtualBases,
8656     /// Visit all direct bases, virtual or not.
8657     VisitDirectBases,
8658     /// Visit all non-virtual bases, and all virtual bases if the class
8659     /// is not abstract.
8660     VisitPotentiallyConstructedBases,
8661     /// Visit all direct or virtual bases.
8662     VisitAllBases
8663   };
8664 
8665   // Visit the bases and members of the class.
8666   bool visit(BasesToVisit Bases) {
8667     CXXRecordDecl *RD = MD->getParent();
8668 
8669     if (Bases == VisitPotentiallyConstructedBases)
8670       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8671 
8672     for (auto &B : RD->bases())
8673       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8674           getDerived().visitBase(&B))
8675         return true;
8676 
8677     if (Bases == VisitAllBases)
8678       for (auto &B : RD->vbases())
8679         if (getDerived().visitBase(&B))
8680           return true;
8681 
8682     for (auto *F : RD->fields())
8683       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8684           getDerived().visitField(F))
8685         return true;
8686 
8687     return false;
8688   }
8689 };
8690 }
8691 
8692 namespace {
8693 struct SpecialMemberDeletionInfo
8694     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8695   bool Diagnose;
8696 
8697   SourceLocation Loc;
8698 
8699   bool AllFieldsAreConst;
8700 
8701   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8702                             Sema::CXXSpecialMember CSM,
8703                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8704       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8705         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8706 
8707   bool inUnion() const { return MD->getParent()->isUnion(); }
8708 
8709   Sema::CXXSpecialMember getEffectiveCSM() {
8710     return ICI ? Sema::CXXInvalid : CSM;
8711   }
8712 
8713   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8714 
8715   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8716   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8717 
8718   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8719   bool shouldDeleteForField(FieldDecl *FD);
8720   bool shouldDeleteForAllConstMembers();
8721 
8722   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8723                                      unsigned Quals);
8724   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8725                                     Sema::SpecialMemberOverloadResult SMOR,
8726                                     bool IsDtorCallInCtor);
8727 
8728   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8729 };
8730 }
8731 
8732 /// Is the given special member inaccessible when used on the given
8733 /// sub-object.
8734 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8735                                              CXXMethodDecl *target) {
8736   /// If we're operating on a base class, the object type is the
8737   /// type of this special member.
8738   QualType objectTy;
8739   AccessSpecifier access = target->getAccess();
8740   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8741     objectTy = S.Context.getTypeDeclType(MD->getParent());
8742     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8743 
8744   // If we're operating on a field, the object type is the type of the field.
8745   } else {
8746     objectTy = S.Context.getTypeDeclType(target->getParent());
8747   }
8748 
8749   return S.isMemberAccessibleForDeletion(
8750       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8751 }
8752 
8753 /// Check whether we should delete a special member due to the implicit
8754 /// definition containing a call to a special member of a subobject.
8755 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8756     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8757     bool IsDtorCallInCtor) {
8758   CXXMethodDecl *Decl = SMOR.getMethod();
8759   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8760 
8761   int DiagKind = -1;
8762 
8763   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8764     DiagKind = !Decl ? 0 : 1;
8765   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8766     DiagKind = 2;
8767   else if (!isAccessible(Subobj, Decl))
8768     DiagKind = 3;
8769   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8770            !Decl->isTrivial()) {
8771     // A member of a union must have a trivial corresponding special member.
8772     // As a weird special case, a destructor call from a union's constructor
8773     // must be accessible and non-deleted, but need not be trivial. Such a
8774     // destructor is never actually called, but is semantically checked as
8775     // if it were.
8776     DiagKind = 4;
8777   }
8778 
8779   if (DiagKind == -1)
8780     return false;
8781 
8782   if (Diagnose) {
8783     if (Field) {
8784       S.Diag(Field->getLocation(),
8785              diag::note_deleted_special_member_class_subobject)
8786         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8787         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8788     } else {
8789       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8790       S.Diag(Base->getBeginLoc(),
8791              diag::note_deleted_special_member_class_subobject)
8792           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8793           << Base->getType() << DiagKind << IsDtorCallInCtor
8794           << /*IsObjCPtr*/false;
8795     }
8796 
8797     if (DiagKind == 1)
8798       S.NoteDeletedFunction(Decl);
8799     // FIXME: Explain inaccessibility if DiagKind == 3.
8800   }
8801 
8802   return true;
8803 }
8804 
8805 /// Check whether we should delete a special member function due to having a
8806 /// direct or virtual base class or non-static data member of class type M.
8807 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8808     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8809   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8810   bool IsMutable = Field && Field->isMutable();
8811 
8812   // C++11 [class.ctor]p5:
8813   // -- any direct or virtual base class, or non-static data member with no
8814   //    brace-or-equal-initializer, has class type M (or array thereof) and
8815   //    either M has no default constructor or overload resolution as applied
8816   //    to M's default constructor results in an ambiguity or in a function
8817   //    that is deleted or inaccessible
8818   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8819   // -- a direct or virtual base class B that cannot be copied/moved because
8820   //    overload resolution, as applied to B's corresponding special member,
8821   //    results in an ambiguity or a function that is deleted or inaccessible
8822   //    from the defaulted special member
8823   // C++11 [class.dtor]p5:
8824   // -- any direct or virtual base class [...] has a type with a destructor
8825   //    that is deleted or inaccessible
8826   if (!(CSM == Sema::CXXDefaultConstructor &&
8827         Field && Field->hasInClassInitializer()) &&
8828       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8829                                    false))
8830     return true;
8831 
8832   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8833   // -- any direct or virtual base class or non-static data member has a
8834   //    type with a destructor that is deleted or inaccessible
8835   if (IsConstructor) {
8836     Sema::SpecialMemberOverloadResult SMOR =
8837         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8838                               false, false, false, false, false);
8839     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8840       return true;
8841   }
8842 
8843   return false;
8844 }
8845 
8846 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8847     FieldDecl *FD, QualType FieldType) {
8848   // The defaulted special functions are defined as deleted if this is a variant
8849   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8850   // type under ARC.
8851   if (!FieldType.hasNonTrivialObjCLifetime())
8852     return false;
8853 
8854   // Don't make the defaulted default constructor defined as deleted if the
8855   // member has an in-class initializer.
8856   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8857     return false;
8858 
8859   if (Diagnose) {
8860     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8861     S.Diag(FD->getLocation(),
8862            diag::note_deleted_special_member_class_subobject)
8863         << getEffectiveCSM() << ParentClass << /*IsField*/true
8864         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8865   }
8866 
8867   return true;
8868 }
8869 
8870 /// Check whether we should delete a special member function due to the class
8871 /// having a particular direct or virtual base class.
8872 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8873   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8874   // If program is correct, BaseClass cannot be null, but if it is, the error
8875   // must be reported elsewhere.
8876   if (!BaseClass)
8877     return false;
8878   // If we have an inheriting constructor, check whether we're calling an
8879   // inherited constructor instead of a default constructor.
8880   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8881   if (auto *BaseCtor = SMOR.getMethod()) {
8882     // Note that we do not check access along this path; other than that,
8883     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8884     // FIXME: Check that the base has a usable destructor! Sink this into
8885     // shouldDeleteForClassSubobject.
8886     if (BaseCtor->isDeleted() && Diagnose) {
8887       S.Diag(Base->getBeginLoc(),
8888              diag::note_deleted_special_member_class_subobject)
8889           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8890           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8891           << /*IsObjCPtr*/false;
8892       S.NoteDeletedFunction(BaseCtor);
8893     }
8894     return BaseCtor->isDeleted();
8895   }
8896   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8897 }
8898 
8899 /// Check whether we should delete a special member function due to the class
8900 /// having a particular non-static data member.
8901 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8902   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8903   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8904 
8905   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8906     return true;
8907 
8908   if (CSM == Sema::CXXDefaultConstructor) {
8909     // For a default constructor, all references must be initialized in-class
8910     // and, if a union, it must have a non-const member.
8911     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8912       if (Diagnose)
8913         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8914           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8915       return true;
8916     }
8917     // C++11 [class.ctor]p5: any non-variant non-static data member of
8918     // const-qualified type (or array thereof) with no
8919     // brace-or-equal-initializer does not have a user-provided default
8920     // constructor.
8921     if (!inUnion() && FieldType.isConstQualified() &&
8922         !FD->hasInClassInitializer() &&
8923         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8924       if (Diagnose)
8925         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8926           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8927       return true;
8928     }
8929 
8930     if (inUnion() && !FieldType.isConstQualified())
8931       AllFieldsAreConst = false;
8932   } else if (CSM == Sema::CXXCopyConstructor) {
8933     // For a copy constructor, data members must not be of rvalue reference
8934     // type.
8935     if (FieldType->isRValueReferenceType()) {
8936       if (Diagnose)
8937         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8938           << MD->getParent() << FD << FieldType;
8939       return true;
8940     }
8941   } else if (IsAssignment) {
8942     // For an assignment operator, data members must not be of reference type.
8943     if (FieldType->isReferenceType()) {
8944       if (Diagnose)
8945         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8946           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8947       return true;
8948     }
8949     if (!FieldRecord && FieldType.isConstQualified()) {
8950       // C++11 [class.copy]p23:
8951       // -- a non-static data member of const non-class type (or array thereof)
8952       if (Diagnose)
8953         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8954           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8955       return true;
8956     }
8957   }
8958 
8959   if (FieldRecord) {
8960     // Some additional restrictions exist on the variant members.
8961     if (!inUnion() && FieldRecord->isUnion() &&
8962         FieldRecord->isAnonymousStructOrUnion()) {
8963       bool AllVariantFieldsAreConst = true;
8964 
8965       // FIXME: Handle anonymous unions declared within anonymous unions.
8966       for (auto *UI : FieldRecord->fields()) {
8967         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8968 
8969         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8970           return true;
8971 
8972         if (!UnionFieldType.isConstQualified())
8973           AllVariantFieldsAreConst = false;
8974 
8975         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8976         if (UnionFieldRecord &&
8977             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8978                                           UnionFieldType.getCVRQualifiers()))
8979           return true;
8980       }
8981 
8982       // At least one member in each anonymous union must be non-const
8983       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8984           !FieldRecord->field_empty()) {
8985         if (Diagnose)
8986           S.Diag(FieldRecord->getLocation(),
8987                  diag::note_deleted_default_ctor_all_const)
8988             << !!ICI << MD->getParent() << /*anonymous union*/1;
8989         return true;
8990       }
8991 
8992       // Don't check the implicit member of the anonymous union type.
8993       // This is technically non-conformant, but sanity demands it.
8994       return false;
8995     }
8996 
8997     if (shouldDeleteForClassSubobject(FieldRecord, FD,
8998                                       FieldType.getCVRQualifiers()))
8999       return true;
9000   }
9001 
9002   return false;
9003 }
9004 
9005 /// C++11 [class.ctor] p5:
9006 ///   A defaulted default constructor for a class X is defined as deleted if
9007 /// X is a union and all of its variant members are of const-qualified type.
9008 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9009   // This is a silly definition, because it gives an empty union a deleted
9010   // default constructor. Don't do that.
9011   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9012     bool AnyFields = false;
9013     for (auto *F : MD->getParent()->fields())
9014       if ((AnyFields = !F->isUnnamedBitfield()))
9015         break;
9016     if (!AnyFields)
9017       return false;
9018     if (Diagnose)
9019       S.Diag(MD->getParent()->getLocation(),
9020              diag::note_deleted_default_ctor_all_const)
9021         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9022     return true;
9023   }
9024   return false;
9025 }
9026 
9027 /// Determine whether a defaulted special member function should be defined as
9028 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9029 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9030 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9031                                      InheritedConstructorInfo *ICI,
9032                                      bool Diagnose) {
9033   if (MD->isInvalidDecl())
9034     return false;
9035   CXXRecordDecl *RD = MD->getParent();
9036   assert(!RD->isDependentType() && "do deletion after instantiation");
9037   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9038     return false;
9039 
9040   // C++11 [expr.lambda.prim]p19:
9041   //   The closure type associated with a lambda-expression has a
9042   //   deleted (8.4.3) default constructor and a deleted copy
9043   //   assignment operator.
9044   // C++2a adds back these operators if the lambda has no lambda-capture.
9045   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9046       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9047     if (Diagnose)
9048       Diag(RD->getLocation(), diag::note_lambda_decl);
9049     return true;
9050   }
9051 
9052   // For an anonymous struct or union, the copy and assignment special members
9053   // will never be used, so skip the check. For an anonymous union declared at
9054   // namespace scope, the constructor and destructor are used.
9055   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9056       RD->isAnonymousStructOrUnion())
9057     return false;
9058 
9059   // C++11 [class.copy]p7, p18:
9060   //   If the class definition declares a move constructor or move assignment
9061   //   operator, an implicitly declared copy constructor or copy assignment
9062   //   operator is defined as deleted.
9063   if (MD->isImplicit() &&
9064       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9065     CXXMethodDecl *UserDeclaredMove = nullptr;
9066 
9067     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9068     // deletion of the corresponding copy operation, not both copy operations.
9069     // MSVC 2015 has adopted the standards conforming behavior.
9070     bool DeletesOnlyMatchingCopy =
9071         getLangOpts().MSVCCompat &&
9072         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9073 
9074     if (RD->hasUserDeclaredMoveConstructor() &&
9075         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9076       if (!Diagnose) return true;
9077 
9078       // Find any user-declared move constructor.
9079       for (auto *I : RD->ctors()) {
9080         if (I->isMoveConstructor()) {
9081           UserDeclaredMove = I;
9082           break;
9083         }
9084       }
9085       assert(UserDeclaredMove);
9086     } else if (RD->hasUserDeclaredMoveAssignment() &&
9087                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9088       if (!Diagnose) return true;
9089 
9090       // Find any user-declared move assignment operator.
9091       for (auto *I : RD->methods()) {
9092         if (I->isMoveAssignmentOperator()) {
9093           UserDeclaredMove = I;
9094           break;
9095         }
9096       }
9097       assert(UserDeclaredMove);
9098     }
9099 
9100     if (UserDeclaredMove) {
9101       Diag(UserDeclaredMove->getLocation(),
9102            diag::note_deleted_copy_user_declared_move)
9103         << (CSM == CXXCopyAssignment) << RD
9104         << UserDeclaredMove->isMoveAssignmentOperator();
9105       return true;
9106     }
9107   }
9108 
9109   // Do access control from the special member function
9110   ContextRAII MethodContext(*this, MD);
9111 
9112   // C++11 [class.dtor]p5:
9113   // -- for a virtual destructor, lookup of the non-array deallocation function
9114   //    results in an ambiguity or in a function that is deleted or inaccessible
9115   if (CSM == CXXDestructor && MD->isVirtual()) {
9116     FunctionDecl *OperatorDelete = nullptr;
9117     DeclarationName Name =
9118       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9119     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9120                                  OperatorDelete, /*Diagnose*/false)) {
9121       if (Diagnose)
9122         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9123       return true;
9124     }
9125   }
9126 
9127   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9128 
9129   // Per DR1611, do not consider virtual bases of constructors of abstract
9130   // classes, since we are not going to construct them.
9131   // Per DR1658, do not consider virtual bases of destructors of abstract
9132   // classes either.
9133   // Per DR2180, for assignment operators we only assign (and thus only
9134   // consider) direct bases.
9135   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9136                                  : SMI.VisitPotentiallyConstructedBases))
9137     return true;
9138 
9139   if (SMI.shouldDeleteForAllConstMembers())
9140     return true;
9141 
9142   if (getLangOpts().CUDA) {
9143     // We should delete the special member in CUDA mode if target inference
9144     // failed.
9145     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9146     // is treated as certain special member, which may not reflect what special
9147     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9148     // expects CSM to match MD, therefore recalculate CSM.
9149     assert(ICI || CSM == getSpecialMember(MD));
9150     auto RealCSM = CSM;
9151     if (ICI)
9152       RealCSM = getSpecialMember(MD);
9153 
9154     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9155                                                    SMI.ConstArg, Diagnose);
9156   }
9157 
9158   return false;
9159 }
9160 
9161 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9162   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9163   assert(DFK && "not a defaultable function");
9164   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9165 
9166   if (DFK.isSpecialMember()) {
9167     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9168                               nullptr, /*Diagnose=*/true);
9169   } else {
9170     DefaultedComparisonAnalyzer(
9171         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9172         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9173         .visit();
9174   }
9175 }
9176 
9177 /// Perform lookup for a special member of the specified kind, and determine
9178 /// whether it is trivial. If the triviality can be determined without the
9179 /// lookup, skip it. This is intended for use when determining whether a
9180 /// special member of a containing object is trivial, and thus does not ever
9181 /// perform overload resolution for default constructors.
9182 ///
9183 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9184 /// member that was most likely to be intended to be trivial, if any.
9185 ///
9186 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9187 /// determine whether the special member is trivial.
9188 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9189                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9190                                      bool ConstRHS,
9191                                      Sema::TrivialABIHandling TAH,
9192                                      CXXMethodDecl **Selected) {
9193   if (Selected)
9194     *Selected = nullptr;
9195 
9196   switch (CSM) {
9197   case Sema::CXXInvalid:
9198     llvm_unreachable("not a special member");
9199 
9200   case Sema::CXXDefaultConstructor:
9201     // C++11 [class.ctor]p5:
9202     //   A default constructor is trivial if:
9203     //    - all the [direct subobjects] have trivial default constructors
9204     //
9205     // Note, no overload resolution is performed in this case.
9206     if (RD->hasTrivialDefaultConstructor())
9207       return true;
9208 
9209     if (Selected) {
9210       // If there's a default constructor which could have been trivial, dig it
9211       // out. Otherwise, if there's any user-provided default constructor, point
9212       // to that as an example of why there's not a trivial one.
9213       CXXConstructorDecl *DefCtor = nullptr;
9214       if (RD->needsImplicitDefaultConstructor())
9215         S.DeclareImplicitDefaultConstructor(RD);
9216       for (auto *CI : RD->ctors()) {
9217         if (!CI->isDefaultConstructor())
9218           continue;
9219         DefCtor = CI;
9220         if (!DefCtor->isUserProvided())
9221           break;
9222       }
9223 
9224       *Selected = DefCtor;
9225     }
9226 
9227     return false;
9228 
9229   case Sema::CXXDestructor:
9230     // C++11 [class.dtor]p5:
9231     //   A destructor is trivial if:
9232     //    - all the direct [subobjects] have trivial destructors
9233     if (RD->hasTrivialDestructor() ||
9234         (TAH == Sema::TAH_ConsiderTrivialABI &&
9235          RD->hasTrivialDestructorForCall()))
9236       return true;
9237 
9238     if (Selected) {
9239       if (RD->needsImplicitDestructor())
9240         S.DeclareImplicitDestructor(RD);
9241       *Selected = RD->getDestructor();
9242     }
9243 
9244     return false;
9245 
9246   case Sema::CXXCopyConstructor:
9247     // C++11 [class.copy]p12:
9248     //   A copy constructor is trivial if:
9249     //    - the constructor selected to copy each direct [subobject] is trivial
9250     if (RD->hasTrivialCopyConstructor() ||
9251         (TAH == Sema::TAH_ConsiderTrivialABI &&
9252          RD->hasTrivialCopyConstructorForCall())) {
9253       if (Quals == Qualifiers::Const)
9254         // We must either select the trivial copy constructor or reach an
9255         // ambiguity; no need to actually perform overload resolution.
9256         return true;
9257     } else if (!Selected) {
9258       return false;
9259     }
9260     // In C++98, we are not supposed to perform overload resolution here, but we
9261     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9262     // cases like B as having a non-trivial copy constructor:
9263     //   struct A { template<typename T> A(T&); };
9264     //   struct B { mutable A a; };
9265     goto NeedOverloadResolution;
9266 
9267   case Sema::CXXCopyAssignment:
9268     // C++11 [class.copy]p25:
9269     //   A copy assignment operator is trivial if:
9270     //    - the assignment operator selected to copy each direct [subobject] is
9271     //      trivial
9272     if (RD->hasTrivialCopyAssignment()) {
9273       if (Quals == Qualifiers::Const)
9274         return true;
9275     } else if (!Selected) {
9276       return false;
9277     }
9278     // In C++98, we are not supposed to perform overload resolution here, but we
9279     // treat that as a language defect.
9280     goto NeedOverloadResolution;
9281 
9282   case Sema::CXXMoveConstructor:
9283   case Sema::CXXMoveAssignment:
9284   NeedOverloadResolution:
9285     Sema::SpecialMemberOverloadResult SMOR =
9286         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9287 
9288     // The standard doesn't describe how to behave if the lookup is ambiguous.
9289     // We treat it as not making the member non-trivial, just like the standard
9290     // mandates for the default constructor. This should rarely matter, because
9291     // the member will also be deleted.
9292     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9293       return true;
9294 
9295     if (!SMOR.getMethod()) {
9296       assert(SMOR.getKind() ==
9297              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9298       return false;
9299     }
9300 
9301     // We deliberately don't check if we found a deleted special member. We're
9302     // not supposed to!
9303     if (Selected)
9304       *Selected = SMOR.getMethod();
9305 
9306     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9307         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9308       return SMOR.getMethod()->isTrivialForCall();
9309     return SMOR.getMethod()->isTrivial();
9310   }
9311 
9312   llvm_unreachable("unknown special method kind");
9313 }
9314 
9315 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9316   for (auto *CI : RD->ctors())
9317     if (!CI->isImplicit())
9318       return CI;
9319 
9320   // Look for constructor templates.
9321   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9322   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9323     if (CXXConstructorDecl *CD =
9324           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9325       return CD;
9326   }
9327 
9328   return nullptr;
9329 }
9330 
9331 /// The kind of subobject we are checking for triviality. The values of this
9332 /// enumeration are used in diagnostics.
9333 enum TrivialSubobjectKind {
9334   /// The subobject is a base class.
9335   TSK_BaseClass,
9336   /// The subobject is a non-static data member.
9337   TSK_Field,
9338   /// The object is actually the complete object.
9339   TSK_CompleteObject
9340 };
9341 
9342 /// Check whether the special member selected for a given type would be trivial.
9343 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9344                                       QualType SubType, bool ConstRHS,
9345                                       Sema::CXXSpecialMember CSM,
9346                                       TrivialSubobjectKind Kind,
9347                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9348   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9349   if (!SubRD)
9350     return true;
9351 
9352   CXXMethodDecl *Selected;
9353   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9354                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9355     return true;
9356 
9357   if (Diagnose) {
9358     if (ConstRHS)
9359       SubType.addConst();
9360 
9361     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9362       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9363         << Kind << SubType.getUnqualifiedType();
9364       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9365         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9366     } else if (!Selected)
9367       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9368         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9369     else if (Selected->isUserProvided()) {
9370       if (Kind == TSK_CompleteObject)
9371         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9372           << Kind << SubType.getUnqualifiedType() << CSM;
9373       else {
9374         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9375           << Kind << SubType.getUnqualifiedType() << CSM;
9376         S.Diag(Selected->getLocation(), diag::note_declared_at);
9377       }
9378     } else {
9379       if (Kind != TSK_CompleteObject)
9380         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9381           << Kind << SubType.getUnqualifiedType() << CSM;
9382 
9383       // Explain why the defaulted or deleted special member isn't trivial.
9384       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9385                                Diagnose);
9386     }
9387   }
9388 
9389   return false;
9390 }
9391 
9392 /// Check whether the members of a class type allow a special member to be
9393 /// trivial.
9394 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9395                                      Sema::CXXSpecialMember CSM,
9396                                      bool ConstArg,
9397                                      Sema::TrivialABIHandling TAH,
9398                                      bool Diagnose) {
9399   for (const auto *FI : RD->fields()) {
9400     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9401       continue;
9402 
9403     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9404 
9405     // Pretend anonymous struct or union members are members of this class.
9406     if (FI->isAnonymousStructOrUnion()) {
9407       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9408                                     CSM, ConstArg, TAH, Diagnose))
9409         return false;
9410       continue;
9411     }
9412 
9413     // C++11 [class.ctor]p5:
9414     //   A default constructor is trivial if [...]
9415     //    -- no non-static data member of its class has a
9416     //       brace-or-equal-initializer
9417     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9418       if (Diagnose)
9419         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9420             << FI;
9421       return false;
9422     }
9423 
9424     // Objective C ARC 4.3.5:
9425     //   [...] nontrivally ownership-qualified types are [...] not trivially
9426     //   default constructible, copy constructible, move constructible, copy
9427     //   assignable, move assignable, or destructible [...]
9428     if (FieldType.hasNonTrivialObjCLifetime()) {
9429       if (Diagnose)
9430         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9431           << RD << FieldType.getObjCLifetime();
9432       return false;
9433     }
9434 
9435     bool ConstRHS = ConstArg && !FI->isMutable();
9436     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9437                                    CSM, TSK_Field, TAH, Diagnose))
9438       return false;
9439   }
9440 
9441   return true;
9442 }
9443 
9444 /// Diagnose why the specified class does not have a trivial special member of
9445 /// the given kind.
9446 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9447   QualType Ty = Context.getRecordType(RD);
9448 
9449   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9450   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9451                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9452                             /*Diagnose*/true);
9453 }
9454 
9455 /// Determine whether a defaulted or deleted special member function is trivial,
9456 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9457 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9458 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9459                                   TrivialABIHandling TAH, bool Diagnose) {
9460   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9461 
9462   CXXRecordDecl *RD = MD->getParent();
9463 
9464   bool ConstArg = false;
9465 
9466   // C++11 [class.copy]p12, p25: [DR1593]
9467   //   A [special member] is trivial if [...] its parameter-type-list is
9468   //   equivalent to the parameter-type-list of an implicit declaration [...]
9469   switch (CSM) {
9470   case CXXDefaultConstructor:
9471   case CXXDestructor:
9472     // Trivial default constructors and destructors cannot have parameters.
9473     break;
9474 
9475   case CXXCopyConstructor:
9476   case CXXCopyAssignment: {
9477     // Trivial copy operations always have const, non-volatile parameter types.
9478     ConstArg = true;
9479     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9480     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9481     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9482       if (Diagnose)
9483         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9484           << Param0->getSourceRange() << Param0->getType()
9485           << Context.getLValueReferenceType(
9486                Context.getRecordType(RD).withConst());
9487       return false;
9488     }
9489     break;
9490   }
9491 
9492   case CXXMoveConstructor:
9493   case CXXMoveAssignment: {
9494     // Trivial move operations always have non-cv-qualified parameters.
9495     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9496     const RValueReferenceType *RT =
9497       Param0->getType()->getAs<RValueReferenceType>();
9498     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9499       if (Diagnose)
9500         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9501           << Param0->getSourceRange() << Param0->getType()
9502           << Context.getRValueReferenceType(Context.getRecordType(RD));
9503       return false;
9504     }
9505     break;
9506   }
9507 
9508   case CXXInvalid:
9509     llvm_unreachable("not a special member");
9510   }
9511 
9512   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9513     if (Diagnose)
9514       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9515            diag::note_nontrivial_default_arg)
9516         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9517     return false;
9518   }
9519   if (MD->isVariadic()) {
9520     if (Diagnose)
9521       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9522     return false;
9523   }
9524 
9525   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9526   //   A copy/move [constructor or assignment operator] is trivial if
9527   //    -- the [member] selected to copy/move each direct base class subobject
9528   //       is trivial
9529   //
9530   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9531   //   A [default constructor or destructor] is trivial if
9532   //    -- all the direct base classes have trivial [default constructors or
9533   //       destructors]
9534   for (const auto &BI : RD->bases())
9535     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9536                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9537       return false;
9538 
9539   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9540   //   A copy/move [constructor or assignment operator] for a class X is
9541   //   trivial if
9542   //    -- for each non-static data member of X that is of class type (or array
9543   //       thereof), the constructor selected to copy/move that member is
9544   //       trivial
9545   //
9546   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9547   //   A [default constructor or destructor] is trivial if
9548   //    -- for all of the non-static data members of its class that are of class
9549   //       type (or array thereof), each such class has a trivial [default
9550   //       constructor or destructor]
9551   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9552     return false;
9553 
9554   // C++11 [class.dtor]p5:
9555   //   A destructor is trivial if [...]
9556   //    -- the destructor is not virtual
9557   if (CSM == CXXDestructor && MD->isVirtual()) {
9558     if (Diagnose)
9559       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9560     return false;
9561   }
9562 
9563   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9564   //   A [special member] for class X is trivial if [...]
9565   //    -- class X has no virtual functions and no virtual base classes
9566   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9567     if (!Diagnose)
9568       return false;
9569 
9570     if (RD->getNumVBases()) {
9571       // Check for virtual bases. We already know that the corresponding
9572       // member in all bases is trivial, so vbases must all be direct.
9573       CXXBaseSpecifier &BS = *RD->vbases_begin();
9574       assert(BS.isVirtual());
9575       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9576       return false;
9577     }
9578 
9579     // Must have a virtual method.
9580     for (const auto *MI : RD->methods()) {
9581       if (MI->isVirtual()) {
9582         SourceLocation MLoc = MI->getBeginLoc();
9583         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9584         return false;
9585       }
9586     }
9587 
9588     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9589   }
9590 
9591   // Looks like it's trivial!
9592   return true;
9593 }
9594 
9595 namespace {
9596 struct FindHiddenVirtualMethod {
9597   Sema *S;
9598   CXXMethodDecl *Method;
9599   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9600   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9601 
9602 private:
9603   /// Check whether any most overridden method from MD in Methods
9604   static bool CheckMostOverridenMethods(
9605       const CXXMethodDecl *MD,
9606       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9607     if (MD->size_overridden_methods() == 0)
9608       return Methods.count(MD->getCanonicalDecl());
9609     for (const CXXMethodDecl *O : MD->overridden_methods())
9610       if (CheckMostOverridenMethods(O, Methods))
9611         return true;
9612     return false;
9613   }
9614 
9615 public:
9616   /// Member lookup function that determines whether a given C++
9617   /// method overloads virtual methods in a base class without overriding any,
9618   /// to be used with CXXRecordDecl::lookupInBases().
9619   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9620     RecordDecl *BaseRecord =
9621         Specifier->getType()->castAs<RecordType>()->getDecl();
9622 
9623     DeclarationName Name = Method->getDeclName();
9624     assert(Name.getNameKind() == DeclarationName::Identifier);
9625 
9626     bool foundSameNameMethod = false;
9627     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9628     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9629          Path.Decls = Path.Decls.slice(1)) {
9630       NamedDecl *D = Path.Decls.front();
9631       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9632         MD = MD->getCanonicalDecl();
9633         foundSameNameMethod = true;
9634         // Interested only in hidden virtual methods.
9635         if (!MD->isVirtual())
9636           continue;
9637         // If the method we are checking overrides a method from its base
9638         // don't warn about the other overloaded methods. Clang deviates from
9639         // GCC by only diagnosing overloads of inherited virtual functions that
9640         // do not override any other virtual functions in the base. GCC's
9641         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9642         // function from a base class. These cases may be better served by a
9643         // warning (not specific to virtual functions) on call sites when the
9644         // call would select a different function from the base class, were it
9645         // visible.
9646         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9647         if (!S->IsOverload(Method, MD, false))
9648           return true;
9649         // Collect the overload only if its hidden.
9650         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9651           overloadedMethods.push_back(MD);
9652       }
9653     }
9654 
9655     if (foundSameNameMethod)
9656       OverloadedMethods.append(overloadedMethods.begin(),
9657                                overloadedMethods.end());
9658     return foundSameNameMethod;
9659   }
9660 };
9661 } // end anonymous namespace
9662 
9663 /// Add the most overriden methods from MD to Methods
9664 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9665                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9666   if (MD->size_overridden_methods() == 0)
9667     Methods.insert(MD->getCanonicalDecl());
9668   else
9669     for (const CXXMethodDecl *O : MD->overridden_methods())
9670       AddMostOverridenMethods(O, Methods);
9671 }
9672 
9673 /// Check if a method overloads virtual methods in a base class without
9674 /// overriding any.
9675 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9676                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9677   if (!MD->getDeclName().isIdentifier())
9678     return;
9679 
9680   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9681                      /*bool RecordPaths=*/false,
9682                      /*bool DetectVirtual=*/false);
9683   FindHiddenVirtualMethod FHVM;
9684   FHVM.Method = MD;
9685   FHVM.S = this;
9686 
9687   // Keep the base methods that were overridden or introduced in the subclass
9688   // by 'using' in a set. A base method not in this set is hidden.
9689   CXXRecordDecl *DC = MD->getParent();
9690   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9691   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9692     NamedDecl *ND = *I;
9693     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9694       ND = shad->getTargetDecl();
9695     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9696       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9697   }
9698 
9699   if (DC->lookupInBases(FHVM, Paths))
9700     OverloadedMethods = FHVM.OverloadedMethods;
9701 }
9702 
9703 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9704                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9705   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9706     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9707     PartialDiagnostic PD = PDiag(
9708          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9709     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9710     Diag(overloadedMD->getLocation(), PD);
9711   }
9712 }
9713 
9714 /// Diagnose methods which overload virtual methods in a base class
9715 /// without overriding any.
9716 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9717   if (MD->isInvalidDecl())
9718     return;
9719 
9720   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9721     return;
9722 
9723   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9724   FindHiddenVirtualMethods(MD, OverloadedMethods);
9725   if (!OverloadedMethods.empty()) {
9726     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9727       << MD << (OverloadedMethods.size() > 1);
9728 
9729     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9730   }
9731 }
9732 
9733 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9734   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9735     // No diagnostics if this is a template instantiation.
9736     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9737       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9738            diag::ext_cannot_use_trivial_abi) << &RD;
9739       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9740            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9741     }
9742     RD.dropAttr<TrivialABIAttr>();
9743   };
9744 
9745   // Ill-formed if the copy and move constructors are deleted.
9746   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9747     // If the type is dependent, then assume it might have
9748     // implicit copy or move ctor because we won't know yet at this point.
9749     if (RD.isDependentType())
9750       return true;
9751     if (RD.needsImplicitCopyConstructor() &&
9752         !RD.defaultedCopyConstructorIsDeleted())
9753       return true;
9754     if (RD.needsImplicitMoveConstructor() &&
9755         !RD.defaultedMoveConstructorIsDeleted())
9756       return true;
9757     for (const CXXConstructorDecl *CD : RD.ctors())
9758       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9759         return true;
9760     return false;
9761   };
9762 
9763   if (!HasNonDeletedCopyOrMoveConstructor()) {
9764     PrintDiagAndRemoveAttr(0);
9765     return;
9766   }
9767 
9768   // Ill-formed if the struct has virtual functions.
9769   if (RD.isPolymorphic()) {
9770     PrintDiagAndRemoveAttr(1);
9771     return;
9772   }
9773 
9774   for (const auto &B : RD.bases()) {
9775     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9776     // virtual base.
9777     if (!B.getType()->isDependentType() &&
9778         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9779       PrintDiagAndRemoveAttr(2);
9780       return;
9781     }
9782 
9783     if (B.isVirtual()) {
9784       PrintDiagAndRemoveAttr(3);
9785       return;
9786     }
9787   }
9788 
9789   for (const auto *FD : RD.fields()) {
9790     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9791     // non-trivial for the purpose of calls.
9792     QualType FT = FD->getType();
9793     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9794       PrintDiagAndRemoveAttr(4);
9795       return;
9796     }
9797 
9798     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9799       if (!RT->isDependentType() &&
9800           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9801         PrintDiagAndRemoveAttr(5);
9802         return;
9803       }
9804   }
9805 }
9806 
9807 void Sema::ActOnFinishCXXMemberSpecification(
9808     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9809     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9810   if (!TagDecl)
9811     return;
9812 
9813   AdjustDeclIfTemplate(TagDecl);
9814 
9815   for (const ParsedAttr &AL : AttrList) {
9816     if (AL.getKind() != ParsedAttr::AT_Visibility)
9817       continue;
9818     AL.setInvalid();
9819     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9820   }
9821 
9822   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9823               // strict aliasing violation!
9824               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9825               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9826 
9827   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9828 }
9829 
9830 /// Find the equality comparison functions that should be implicitly declared
9831 /// in a given class definition, per C++2a [class.compare.default]p3.
9832 static void findImplicitlyDeclaredEqualityComparisons(
9833     ASTContext &Ctx, CXXRecordDecl *RD,
9834     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9835   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9836   if (!RD->lookup(EqEq).empty())
9837     // Member operator== explicitly declared: no implicit operator==s.
9838     return;
9839 
9840   // Traverse friends looking for an '==' or a '<=>'.
9841   for (FriendDecl *Friend : RD->friends()) {
9842     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9843     if (!FD) continue;
9844 
9845     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9846       // Friend operator== explicitly declared: no implicit operator==s.
9847       Spaceships.clear();
9848       return;
9849     }
9850 
9851     if (FD->getOverloadedOperator() == OO_Spaceship &&
9852         FD->isExplicitlyDefaulted())
9853       Spaceships.push_back(FD);
9854   }
9855 
9856   // Look for members named 'operator<=>'.
9857   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9858   for (NamedDecl *ND : RD->lookup(Cmp)) {
9859     // Note that we could find a non-function here (either a function template
9860     // or a using-declaration). Neither case results in an implicit
9861     // 'operator=='.
9862     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9863       if (FD->isExplicitlyDefaulted())
9864         Spaceships.push_back(FD);
9865   }
9866 }
9867 
9868 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9869 /// special functions, such as the default constructor, copy
9870 /// constructor, or destructor, to the given C++ class (C++
9871 /// [special]p1).  This routine can only be executed just before the
9872 /// definition of the class is complete.
9873 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9874   // Don't add implicit special members to templated classes.
9875   // FIXME: This means unqualified lookups for 'operator=' within a class
9876   // template don't work properly.
9877   if (!ClassDecl->isDependentType()) {
9878     if (ClassDecl->needsImplicitDefaultConstructor()) {
9879       ++getASTContext().NumImplicitDefaultConstructors;
9880 
9881       if (ClassDecl->hasInheritedConstructor())
9882         DeclareImplicitDefaultConstructor(ClassDecl);
9883     }
9884 
9885     if (ClassDecl->needsImplicitCopyConstructor()) {
9886       ++getASTContext().NumImplicitCopyConstructors;
9887 
9888       // If the properties or semantics of the copy constructor couldn't be
9889       // determined while the class was being declared, force a declaration
9890       // of it now.
9891       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9892           ClassDecl->hasInheritedConstructor())
9893         DeclareImplicitCopyConstructor(ClassDecl);
9894       // For the MS ABI we need to know whether the copy ctor is deleted. A
9895       // prerequisite for deleting the implicit copy ctor is that the class has
9896       // a move ctor or move assignment that is either user-declared or whose
9897       // semantics are inherited from a subobject. FIXME: We should provide a
9898       // more direct way for CodeGen to ask whether the constructor was deleted.
9899       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9900                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9901                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9902                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9903                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9904         DeclareImplicitCopyConstructor(ClassDecl);
9905     }
9906 
9907     if (getLangOpts().CPlusPlus11 &&
9908         ClassDecl->needsImplicitMoveConstructor()) {
9909       ++getASTContext().NumImplicitMoveConstructors;
9910 
9911       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9912           ClassDecl->hasInheritedConstructor())
9913         DeclareImplicitMoveConstructor(ClassDecl);
9914     }
9915 
9916     if (ClassDecl->needsImplicitCopyAssignment()) {
9917       ++getASTContext().NumImplicitCopyAssignmentOperators;
9918 
9919       // If we have a dynamic class, then the copy assignment operator may be
9920       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9921       // it shows up in the right place in the vtable and that we diagnose
9922       // problems with the implicit exception specification.
9923       if (ClassDecl->isDynamicClass() ||
9924           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9925           ClassDecl->hasInheritedAssignment())
9926         DeclareImplicitCopyAssignment(ClassDecl);
9927     }
9928 
9929     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9930       ++getASTContext().NumImplicitMoveAssignmentOperators;
9931 
9932       // Likewise for the move assignment operator.
9933       if (ClassDecl->isDynamicClass() ||
9934           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9935           ClassDecl->hasInheritedAssignment())
9936         DeclareImplicitMoveAssignment(ClassDecl);
9937     }
9938 
9939     if (ClassDecl->needsImplicitDestructor()) {
9940       ++getASTContext().NumImplicitDestructors;
9941 
9942       // If we have a dynamic class, then the destructor may be virtual, so we
9943       // have to declare the destructor immediately. This ensures that, e.g., it
9944       // shows up in the right place in the vtable and that we diagnose problems
9945       // with the implicit exception specification.
9946       if (ClassDecl->isDynamicClass() ||
9947           ClassDecl->needsOverloadResolutionForDestructor())
9948         DeclareImplicitDestructor(ClassDecl);
9949     }
9950   }
9951 
9952   // C++2a [class.compare.default]p3:
9953   //   If the member-specification does not explicitly declare any member or
9954   //   friend named operator==, an == operator function is declared implicitly
9955   //   for each defaulted three-way comparison operator function defined in
9956   //   the member-specification
9957   // FIXME: Consider doing this lazily.
9958   // We do this during the initial parse for a class template, not during
9959   // instantiation, so that we can handle unqualified lookups for 'operator=='
9960   // when parsing the template.
9961   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9962     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9963     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9964                                               DefaultedSpaceships);
9965     for (auto *FD : DefaultedSpaceships)
9966       DeclareImplicitEqualityComparison(ClassDecl, FD);
9967   }
9968 }
9969 
9970 unsigned
9971 Sema::ActOnReenterTemplateScope(Decl *D,
9972                                 llvm::function_ref<Scope *()> EnterScope) {
9973   if (!D)
9974     return 0;
9975   AdjustDeclIfTemplate(D);
9976 
9977   // In order to get name lookup right, reenter template scopes in order from
9978   // outermost to innermost.
9979   SmallVector<TemplateParameterList *, 4> ParameterLists;
9980   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9981 
9982   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9983     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9984       ParameterLists.push_back(DD->getTemplateParameterList(i));
9985 
9986     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9987       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9988         ParameterLists.push_back(FTD->getTemplateParameters());
9989     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
9990       LookupDC = VD->getDeclContext();
9991 
9992       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
9993         ParameterLists.push_back(VTD->getTemplateParameters());
9994       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
9995         ParameterLists.push_back(PSD->getTemplateParameters());
9996     }
9997   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9998     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9999       ParameterLists.push_back(TD->getTemplateParameterList(i));
10000 
10001     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10002       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10003         ParameterLists.push_back(CTD->getTemplateParameters());
10004       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10005         ParameterLists.push_back(PSD->getTemplateParameters());
10006     }
10007   }
10008   // FIXME: Alias declarations and concepts.
10009 
10010   unsigned Count = 0;
10011   Scope *InnermostTemplateScope = nullptr;
10012   for (TemplateParameterList *Params : ParameterLists) {
10013     // Ignore explicit specializations; they don't contribute to the template
10014     // depth.
10015     if (Params->size() == 0)
10016       continue;
10017 
10018     InnermostTemplateScope = EnterScope();
10019     for (NamedDecl *Param : *Params) {
10020       if (Param->getDeclName()) {
10021         InnermostTemplateScope->AddDecl(Param);
10022         IdResolver.AddDecl(Param);
10023       }
10024     }
10025     ++Count;
10026   }
10027 
10028   // Associate the new template scopes with the corresponding entities.
10029   if (InnermostTemplateScope) {
10030     assert(LookupDC && "no enclosing DeclContext for template lookup");
10031     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10032   }
10033 
10034   return Count;
10035 }
10036 
10037 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10038   if (!RecordD) return;
10039   AdjustDeclIfTemplate(RecordD);
10040   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10041   PushDeclContext(S, Record);
10042 }
10043 
10044 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10045   if (!RecordD) return;
10046   PopDeclContext();
10047 }
10048 
10049 /// This is used to implement the constant expression evaluation part of the
10050 /// attribute enable_if extension. There is nothing in standard C++ which would
10051 /// require reentering parameters.
10052 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10053   if (!Param)
10054     return;
10055 
10056   S->AddDecl(Param);
10057   if (Param->getDeclName())
10058     IdResolver.AddDecl(Param);
10059 }
10060 
10061 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10062 /// parsing a top-level (non-nested) C++ class, and we are now
10063 /// parsing those parts of the given Method declaration that could
10064 /// not be parsed earlier (C++ [class.mem]p2), such as default
10065 /// arguments. This action should enter the scope of the given
10066 /// Method declaration as if we had just parsed the qualified method
10067 /// name. However, it should not bring the parameters into scope;
10068 /// that will be performed by ActOnDelayedCXXMethodParameter.
10069 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10070 }
10071 
10072 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10073 /// C++ method declaration. We're (re-)introducing the given
10074 /// function parameter into scope for use in parsing later parts of
10075 /// the method declaration. For example, we could see an
10076 /// ActOnParamDefaultArgument event for this parameter.
10077 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10078   if (!ParamD)
10079     return;
10080 
10081   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10082 
10083   S->AddDecl(Param);
10084   if (Param->getDeclName())
10085     IdResolver.AddDecl(Param);
10086 }
10087 
10088 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10089 /// processing the delayed method declaration for Method. The method
10090 /// declaration is now considered finished. There may be a separate
10091 /// ActOnStartOfFunctionDef action later (not necessarily
10092 /// immediately!) for this method, if it was also defined inside the
10093 /// class body.
10094 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10095   if (!MethodD)
10096     return;
10097 
10098   AdjustDeclIfTemplate(MethodD);
10099 
10100   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10101 
10102   // Now that we have our default arguments, check the constructor
10103   // again. It could produce additional diagnostics or affect whether
10104   // the class has implicitly-declared destructors, among other
10105   // things.
10106   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10107     CheckConstructor(Constructor);
10108 
10109   // Check the default arguments, which we may have added.
10110   if (!Method->isInvalidDecl())
10111     CheckCXXDefaultArguments(Method);
10112 }
10113 
10114 // Emit the given diagnostic for each non-address-space qualifier.
10115 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10116 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10117   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10118   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10119     bool DiagOccured = false;
10120     FTI.MethodQualifiers->forEachQualifier(
10121         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10122                                    SourceLocation SL) {
10123           // This diagnostic should be emitted on any qualifier except an addr
10124           // space qualifier. However, forEachQualifier currently doesn't visit
10125           // addr space qualifiers, so there's no way to write this condition
10126           // right now; we just diagnose on everything.
10127           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10128           DiagOccured = true;
10129         });
10130     if (DiagOccured)
10131       D.setInvalidType();
10132   }
10133 }
10134 
10135 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10136 /// the well-formedness of the constructor declarator @p D with type @p
10137 /// R. If there are any errors in the declarator, this routine will
10138 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10139 /// will be updated to reflect a well-formed type for the constructor and
10140 /// returned.
10141 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10142                                           StorageClass &SC) {
10143   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10144 
10145   // C++ [class.ctor]p3:
10146   //   A constructor shall not be virtual (10.3) or static (9.4). A
10147   //   constructor can be invoked for a const, volatile or const
10148   //   volatile object. A constructor shall not be declared const,
10149   //   volatile, or const volatile (9.3.2).
10150   if (isVirtual) {
10151     if (!D.isInvalidType())
10152       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10153         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10154         << SourceRange(D.getIdentifierLoc());
10155     D.setInvalidType();
10156   }
10157   if (SC == SC_Static) {
10158     if (!D.isInvalidType())
10159       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10160         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10161         << SourceRange(D.getIdentifierLoc());
10162     D.setInvalidType();
10163     SC = SC_None;
10164   }
10165 
10166   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10167     diagnoseIgnoredQualifiers(
10168         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10169         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10170         D.getDeclSpec().getRestrictSpecLoc(),
10171         D.getDeclSpec().getAtomicSpecLoc());
10172     D.setInvalidType();
10173   }
10174 
10175   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10176 
10177   // C++0x [class.ctor]p4:
10178   //   A constructor shall not be declared with a ref-qualifier.
10179   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10180   if (FTI.hasRefQualifier()) {
10181     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10182       << FTI.RefQualifierIsLValueRef
10183       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10184     D.setInvalidType();
10185   }
10186 
10187   // Rebuild the function type "R" without any type qualifiers (in
10188   // case any of the errors above fired) and with "void" as the
10189   // return type, since constructors don't have return types.
10190   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10191   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10192     return R;
10193 
10194   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10195   EPI.TypeQuals = Qualifiers();
10196   EPI.RefQualifier = RQ_None;
10197 
10198   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10199 }
10200 
10201 /// CheckConstructor - Checks a fully-formed constructor for
10202 /// well-formedness, issuing any diagnostics required. Returns true if
10203 /// the constructor declarator is invalid.
10204 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10205   CXXRecordDecl *ClassDecl
10206     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10207   if (!ClassDecl)
10208     return Constructor->setInvalidDecl();
10209 
10210   // C++ [class.copy]p3:
10211   //   A declaration of a constructor for a class X is ill-formed if
10212   //   its first parameter is of type (optionally cv-qualified) X and
10213   //   either there are no other parameters or else all other
10214   //   parameters have default arguments.
10215   if (!Constructor->isInvalidDecl() &&
10216       Constructor->hasOneParamOrDefaultArgs() &&
10217       Constructor->getTemplateSpecializationKind() !=
10218           TSK_ImplicitInstantiation) {
10219     QualType ParamType = Constructor->getParamDecl(0)->getType();
10220     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10221     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10222       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10223       const char *ConstRef
10224         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10225                                                         : " const &";
10226       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10227         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10228 
10229       // FIXME: Rather that making the constructor invalid, we should endeavor
10230       // to fix the type.
10231       Constructor->setInvalidDecl();
10232     }
10233   }
10234 }
10235 
10236 /// CheckDestructor - Checks a fully-formed destructor definition for
10237 /// well-formedness, issuing any diagnostics required.  Returns true
10238 /// on error.
10239 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10240   CXXRecordDecl *RD = Destructor->getParent();
10241 
10242   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10243     SourceLocation Loc;
10244 
10245     if (!Destructor->isImplicit())
10246       Loc = Destructor->getLocation();
10247     else
10248       Loc = RD->getLocation();
10249 
10250     // If we have a virtual destructor, look up the deallocation function
10251     if (FunctionDecl *OperatorDelete =
10252             FindDeallocationFunctionForDestructor(Loc, RD)) {
10253       Expr *ThisArg = nullptr;
10254 
10255       // If the notional 'delete this' expression requires a non-trivial
10256       // conversion from 'this' to the type of a destroying operator delete's
10257       // first parameter, perform that conversion now.
10258       if (OperatorDelete->isDestroyingOperatorDelete()) {
10259         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10260         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10261           // C++ [class.dtor]p13:
10262           //   ... as if for the expression 'delete this' appearing in a
10263           //   non-virtual destructor of the destructor's class.
10264           ContextRAII SwitchContext(*this, Destructor);
10265           ExprResult This =
10266               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10267           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10268           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10269           if (This.isInvalid()) {
10270             // FIXME: Register this as a context note so that it comes out
10271             // in the right order.
10272             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10273             return true;
10274           }
10275           ThisArg = This.get();
10276         }
10277       }
10278 
10279       DiagnoseUseOfDecl(OperatorDelete, Loc);
10280       MarkFunctionReferenced(Loc, OperatorDelete);
10281       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10282     }
10283   }
10284 
10285   return false;
10286 }
10287 
10288 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10289 /// the well-formednes of the destructor declarator @p D with type @p
10290 /// R. If there are any errors in the declarator, this routine will
10291 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10292 /// will be updated to reflect a well-formed type for the destructor and
10293 /// returned.
10294 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10295                                          StorageClass& SC) {
10296   // C++ [class.dtor]p1:
10297   //   [...] A typedef-name that names a class is a class-name
10298   //   (7.1.3); however, a typedef-name that names a class shall not
10299   //   be used as the identifier in the declarator for a destructor
10300   //   declaration.
10301   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10302   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10303     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10304       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10305   else if (const TemplateSpecializationType *TST =
10306              DeclaratorType->getAs<TemplateSpecializationType>())
10307     if (TST->isTypeAlias())
10308       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10309         << DeclaratorType << 1;
10310 
10311   // C++ [class.dtor]p2:
10312   //   A destructor is used to destroy objects of its class type. A
10313   //   destructor takes no parameters, and no return type can be
10314   //   specified for it (not even void). The address of a destructor
10315   //   shall not be taken. A destructor shall not be static. A
10316   //   destructor can be invoked for a const, volatile or const
10317   //   volatile object. A destructor shall not be declared const,
10318   //   volatile or const volatile (9.3.2).
10319   if (SC == SC_Static) {
10320     if (!D.isInvalidType())
10321       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10322         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10323         << SourceRange(D.getIdentifierLoc())
10324         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10325 
10326     SC = SC_None;
10327   }
10328   if (!D.isInvalidType()) {
10329     // Destructors don't have return types, but the parser will
10330     // happily parse something like:
10331     //
10332     //   class X {
10333     //     float ~X();
10334     //   };
10335     //
10336     // The return type will be eliminated later.
10337     if (D.getDeclSpec().hasTypeSpecifier())
10338       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10339         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10340         << SourceRange(D.getIdentifierLoc());
10341     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10342       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10343                                 SourceLocation(),
10344                                 D.getDeclSpec().getConstSpecLoc(),
10345                                 D.getDeclSpec().getVolatileSpecLoc(),
10346                                 D.getDeclSpec().getRestrictSpecLoc(),
10347                                 D.getDeclSpec().getAtomicSpecLoc());
10348       D.setInvalidType();
10349     }
10350   }
10351 
10352   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10353 
10354   // C++0x [class.dtor]p2:
10355   //   A destructor shall not be declared with a ref-qualifier.
10356   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10357   if (FTI.hasRefQualifier()) {
10358     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10359       << FTI.RefQualifierIsLValueRef
10360       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10361     D.setInvalidType();
10362   }
10363 
10364   // Make sure we don't have any parameters.
10365   if (FTIHasNonVoidParameters(FTI)) {
10366     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10367 
10368     // Delete the parameters.
10369     FTI.freeParams();
10370     D.setInvalidType();
10371   }
10372 
10373   // Make sure the destructor isn't variadic.
10374   if (FTI.isVariadic) {
10375     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10376     D.setInvalidType();
10377   }
10378 
10379   // Rebuild the function type "R" without any type qualifiers or
10380   // parameters (in case any of the errors above fired) and with
10381   // "void" as the return type, since destructors don't have return
10382   // types.
10383   if (!D.isInvalidType())
10384     return R;
10385 
10386   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10387   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10388   EPI.Variadic = false;
10389   EPI.TypeQuals = Qualifiers();
10390   EPI.RefQualifier = RQ_None;
10391   return Context.getFunctionType(Context.VoidTy, None, EPI);
10392 }
10393 
10394 static void extendLeft(SourceRange &R, SourceRange Before) {
10395   if (Before.isInvalid())
10396     return;
10397   R.setBegin(Before.getBegin());
10398   if (R.getEnd().isInvalid())
10399     R.setEnd(Before.getEnd());
10400 }
10401 
10402 static void extendRight(SourceRange &R, SourceRange After) {
10403   if (After.isInvalid())
10404     return;
10405   if (R.getBegin().isInvalid())
10406     R.setBegin(After.getBegin());
10407   R.setEnd(After.getEnd());
10408 }
10409 
10410 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10411 /// well-formednes of the conversion function declarator @p D with
10412 /// type @p R. If there are any errors in the declarator, this routine
10413 /// will emit diagnostics and return true. Otherwise, it will return
10414 /// false. Either way, the type @p R will be updated to reflect a
10415 /// well-formed type for the conversion operator.
10416 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10417                                      StorageClass& SC) {
10418   // C++ [class.conv.fct]p1:
10419   //   Neither parameter types nor return type can be specified. The
10420   //   type of a conversion function (8.3.5) is "function taking no
10421   //   parameter returning conversion-type-id."
10422   if (SC == SC_Static) {
10423     if (!D.isInvalidType())
10424       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10425         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10426         << D.getName().getSourceRange();
10427     D.setInvalidType();
10428     SC = SC_None;
10429   }
10430 
10431   TypeSourceInfo *ConvTSI = nullptr;
10432   QualType ConvType =
10433       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10434 
10435   const DeclSpec &DS = D.getDeclSpec();
10436   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10437     // Conversion functions don't have return types, but the parser will
10438     // happily parse something like:
10439     //
10440     //   class X {
10441     //     float operator bool();
10442     //   };
10443     //
10444     // The return type will be changed later anyway.
10445     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10446       << SourceRange(DS.getTypeSpecTypeLoc())
10447       << SourceRange(D.getIdentifierLoc());
10448     D.setInvalidType();
10449   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10450     // It's also plausible that the user writes type qualifiers in the wrong
10451     // place, such as:
10452     //   struct S { const operator int(); };
10453     // FIXME: we could provide a fixit to move the qualifiers onto the
10454     // conversion type.
10455     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10456         << SourceRange(D.getIdentifierLoc()) << 0;
10457     D.setInvalidType();
10458   }
10459 
10460   const auto *Proto = R->castAs<FunctionProtoType>();
10461 
10462   // Make sure we don't have any parameters.
10463   if (Proto->getNumParams() > 0) {
10464     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10465 
10466     // Delete the parameters.
10467     D.getFunctionTypeInfo().freeParams();
10468     D.setInvalidType();
10469   } else if (Proto->isVariadic()) {
10470     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10471     D.setInvalidType();
10472   }
10473 
10474   // Diagnose "&operator bool()" and other such nonsense.  This
10475   // is actually a gcc extension which we don't support.
10476   if (Proto->getReturnType() != ConvType) {
10477     bool NeedsTypedef = false;
10478     SourceRange Before, After;
10479 
10480     // Walk the chunks and extract information on them for our diagnostic.
10481     bool PastFunctionChunk = false;
10482     for (auto &Chunk : D.type_objects()) {
10483       switch (Chunk.Kind) {
10484       case DeclaratorChunk::Function:
10485         if (!PastFunctionChunk) {
10486           if (Chunk.Fun.HasTrailingReturnType) {
10487             TypeSourceInfo *TRT = nullptr;
10488             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10489             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10490           }
10491           PastFunctionChunk = true;
10492           break;
10493         }
10494         LLVM_FALLTHROUGH;
10495       case DeclaratorChunk::Array:
10496         NeedsTypedef = true;
10497         extendRight(After, Chunk.getSourceRange());
10498         break;
10499 
10500       case DeclaratorChunk::Pointer:
10501       case DeclaratorChunk::BlockPointer:
10502       case DeclaratorChunk::Reference:
10503       case DeclaratorChunk::MemberPointer:
10504       case DeclaratorChunk::Pipe:
10505         extendLeft(Before, Chunk.getSourceRange());
10506         break;
10507 
10508       case DeclaratorChunk::Paren:
10509         extendLeft(Before, Chunk.Loc);
10510         extendRight(After, Chunk.EndLoc);
10511         break;
10512       }
10513     }
10514 
10515     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10516                          After.isValid()  ? After.getBegin() :
10517                                             D.getIdentifierLoc();
10518     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10519     DB << Before << After;
10520 
10521     if (!NeedsTypedef) {
10522       DB << /*don't need a typedef*/0;
10523 
10524       // If we can provide a correct fix-it hint, do so.
10525       if (After.isInvalid() && ConvTSI) {
10526         SourceLocation InsertLoc =
10527             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10528         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10529            << FixItHint::CreateInsertionFromRange(
10530                   InsertLoc, CharSourceRange::getTokenRange(Before))
10531            << FixItHint::CreateRemoval(Before);
10532       }
10533     } else if (!Proto->getReturnType()->isDependentType()) {
10534       DB << /*typedef*/1 << Proto->getReturnType();
10535     } else if (getLangOpts().CPlusPlus11) {
10536       DB << /*alias template*/2 << Proto->getReturnType();
10537     } else {
10538       DB << /*might not be fixable*/3;
10539     }
10540 
10541     // Recover by incorporating the other type chunks into the result type.
10542     // Note, this does *not* change the name of the function. This is compatible
10543     // with the GCC extension:
10544     //   struct S { &operator int(); } s;
10545     //   int &r = s.operator int(); // ok in GCC
10546     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10547     ConvType = Proto->getReturnType();
10548   }
10549 
10550   // C++ [class.conv.fct]p4:
10551   //   The conversion-type-id shall not represent a function type nor
10552   //   an array type.
10553   if (ConvType->isArrayType()) {
10554     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10555     ConvType = Context.getPointerType(ConvType);
10556     D.setInvalidType();
10557   } else if (ConvType->isFunctionType()) {
10558     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10559     ConvType = Context.getPointerType(ConvType);
10560     D.setInvalidType();
10561   }
10562 
10563   // Rebuild the function type "R" without any parameters (in case any
10564   // of the errors above fired) and with the conversion type as the
10565   // return type.
10566   if (D.isInvalidType())
10567     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10568 
10569   // C++0x explicit conversion operators.
10570   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10571     Diag(DS.getExplicitSpecLoc(),
10572          getLangOpts().CPlusPlus11
10573              ? diag::warn_cxx98_compat_explicit_conversion_functions
10574              : diag::ext_explicit_conversion_functions)
10575         << SourceRange(DS.getExplicitSpecRange());
10576 }
10577 
10578 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10579 /// the declaration of the given C++ conversion function. This routine
10580 /// is responsible for recording the conversion function in the C++
10581 /// class, if possible.
10582 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10583   assert(Conversion && "Expected to receive a conversion function declaration");
10584 
10585   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10586 
10587   // Make sure we aren't redeclaring the conversion function.
10588   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10589   // C++ [class.conv.fct]p1:
10590   //   [...] A conversion function is never used to convert a
10591   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10592   //   same object type (or a reference to it), to a (possibly
10593   //   cv-qualified) base class of that type (or a reference to it),
10594   //   or to (possibly cv-qualified) void.
10595   QualType ClassType
10596     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10597   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10598     ConvType = ConvTypeRef->getPointeeType();
10599   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10600       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10601     /* Suppress diagnostics for instantiations. */;
10602   else if (Conversion->size_overridden_methods() != 0)
10603     /* Suppress diagnostics for overriding virtual function in a base class. */;
10604   else if (ConvType->isRecordType()) {
10605     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10606     if (ConvType == ClassType)
10607       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10608         << ClassType;
10609     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10610       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10611         <<  ClassType << ConvType;
10612   } else if (ConvType->isVoidType()) {
10613     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10614       << ClassType << ConvType;
10615   }
10616 
10617   if (FunctionTemplateDecl *ConversionTemplate
10618                                 = Conversion->getDescribedFunctionTemplate())
10619     return ConversionTemplate;
10620 
10621   return Conversion;
10622 }
10623 
10624 namespace {
10625 /// Utility class to accumulate and print a diagnostic listing the invalid
10626 /// specifier(s) on a declaration.
10627 struct BadSpecifierDiagnoser {
10628   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10629       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10630   ~BadSpecifierDiagnoser() {
10631     Diagnostic << Specifiers;
10632   }
10633 
10634   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10635     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10636   }
10637   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10638     return check(SpecLoc,
10639                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10640   }
10641   void check(SourceLocation SpecLoc, const char *Spec) {
10642     if (SpecLoc.isInvalid()) return;
10643     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10644     if (!Specifiers.empty()) Specifiers += " ";
10645     Specifiers += Spec;
10646   }
10647 
10648   Sema &S;
10649   Sema::SemaDiagnosticBuilder Diagnostic;
10650   std::string Specifiers;
10651 };
10652 }
10653 
10654 /// Check the validity of a declarator that we parsed for a deduction-guide.
10655 /// These aren't actually declarators in the grammar, so we need to check that
10656 /// the user didn't specify any pieces that are not part of the deduction-guide
10657 /// grammar.
10658 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10659                                          StorageClass &SC) {
10660   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10661   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10662   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10663 
10664   // C++ [temp.deduct.guide]p3:
10665   //   A deduction-gide shall be declared in the same scope as the
10666   //   corresponding class template.
10667   if (!CurContext->getRedeclContext()->Equals(
10668           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10669     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10670       << GuidedTemplateDecl;
10671     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10672   }
10673 
10674   auto &DS = D.getMutableDeclSpec();
10675   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10676   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10677       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10678       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10679     BadSpecifierDiagnoser Diagnoser(
10680         *this, D.getIdentifierLoc(),
10681         diag::err_deduction_guide_invalid_specifier);
10682 
10683     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10684     DS.ClearStorageClassSpecs();
10685     SC = SC_None;
10686 
10687     // 'explicit' is permitted.
10688     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10689     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10690     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10691     DS.ClearConstexprSpec();
10692 
10693     Diagnoser.check(DS.getConstSpecLoc(), "const");
10694     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10695     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10696     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10697     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10698     DS.ClearTypeQualifiers();
10699 
10700     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10701     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10702     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10703     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10704     DS.ClearTypeSpecType();
10705   }
10706 
10707   if (D.isInvalidType())
10708     return;
10709 
10710   // Check the declarator is simple enough.
10711   bool FoundFunction = false;
10712   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10713     if (Chunk.Kind == DeclaratorChunk::Paren)
10714       continue;
10715     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10716       Diag(D.getDeclSpec().getBeginLoc(),
10717            diag::err_deduction_guide_with_complex_decl)
10718           << D.getSourceRange();
10719       break;
10720     }
10721     if (!Chunk.Fun.hasTrailingReturnType()) {
10722       Diag(D.getName().getBeginLoc(),
10723            diag::err_deduction_guide_no_trailing_return_type);
10724       break;
10725     }
10726 
10727     // Check that the return type is written as a specialization of
10728     // the template specified as the deduction-guide's name.
10729     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10730     TypeSourceInfo *TSI = nullptr;
10731     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10732     assert(TSI && "deduction guide has valid type but invalid return type?");
10733     bool AcceptableReturnType = false;
10734     bool MightInstantiateToSpecialization = false;
10735     if (auto RetTST =
10736             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10737       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10738       bool TemplateMatches =
10739           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10740       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10741         AcceptableReturnType = true;
10742       else {
10743         // This could still instantiate to the right type, unless we know it
10744         // names the wrong class template.
10745         auto *TD = SpecifiedName.getAsTemplateDecl();
10746         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10747                                              !TemplateMatches);
10748       }
10749     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10750       MightInstantiateToSpecialization = true;
10751     }
10752 
10753     if (!AcceptableReturnType) {
10754       Diag(TSI->getTypeLoc().getBeginLoc(),
10755            diag::err_deduction_guide_bad_trailing_return_type)
10756           << GuidedTemplate << TSI->getType()
10757           << MightInstantiateToSpecialization
10758           << TSI->getTypeLoc().getSourceRange();
10759     }
10760 
10761     // Keep going to check that we don't have any inner declarator pieces (we
10762     // could still have a function returning a pointer to a function).
10763     FoundFunction = true;
10764   }
10765 
10766   if (D.isFunctionDefinition())
10767     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10768 }
10769 
10770 //===----------------------------------------------------------------------===//
10771 // Namespace Handling
10772 //===----------------------------------------------------------------------===//
10773 
10774 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10775 /// reopened.
10776 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10777                                             SourceLocation Loc,
10778                                             IdentifierInfo *II, bool *IsInline,
10779                                             NamespaceDecl *PrevNS) {
10780   assert(*IsInline != PrevNS->isInline());
10781 
10782   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10783   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10784   // inline namespaces, with the intention of bringing names into namespace std.
10785   //
10786   // We support this just well enough to get that case working; this is not
10787   // sufficient to support reopening namespaces as inline in general.
10788   if (*IsInline && II && II->getName().startswith("__atomic") &&
10789       S.getSourceManager().isInSystemHeader(Loc)) {
10790     // Mark all prior declarations of the namespace as inline.
10791     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10792          NS = NS->getPreviousDecl())
10793       NS->setInline(*IsInline);
10794     // Patch up the lookup table for the containing namespace. This isn't really
10795     // correct, but it's good enough for this particular case.
10796     for (auto *I : PrevNS->decls())
10797       if (auto *ND = dyn_cast<NamedDecl>(I))
10798         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10799     return;
10800   }
10801 
10802   if (PrevNS->isInline())
10803     // The user probably just forgot the 'inline', so suggest that it
10804     // be added back.
10805     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10806       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10807   else
10808     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10809 
10810   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10811   *IsInline = PrevNS->isInline();
10812 }
10813 
10814 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10815 /// definition.
10816 Decl *Sema::ActOnStartNamespaceDef(
10817     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10818     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10819     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10820   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10821   // For anonymous namespace, take the location of the left brace.
10822   SourceLocation Loc = II ? IdentLoc : LBrace;
10823   bool IsInline = InlineLoc.isValid();
10824   bool IsInvalid = false;
10825   bool IsStd = false;
10826   bool AddToKnown = false;
10827   Scope *DeclRegionScope = NamespcScope->getParent();
10828 
10829   NamespaceDecl *PrevNS = nullptr;
10830   if (II) {
10831     // C++ [namespace.def]p2:
10832     //   The identifier in an original-namespace-definition shall not
10833     //   have been previously defined in the declarative region in
10834     //   which the original-namespace-definition appears. The
10835     //   identifier in an original-namespace-definition is the name of
10836     //   the namespace. Subsequently in that declarative region, it is
10837     //   treated as an original-namespace-name.
10838     //
10839     // Since namespace names are unique in their scope, and we don't
10840     // look through using directives, just look for any ordinary names
10841     // as if by qualified name lookup.
10842     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10843                    ForExternalRedeclaration);
10844     LookupQualifiedName(R, CurContext->getRedeclContext());
10845     NamedDecl *PrevDecl =
10846         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10847     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10848 
10849     if (PrevNS) {
10850       // This is an extended namespace definition.
10851       if (IsInline != PrevNS->isInline())
10852         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10853                                         &IsInline, PrevNS);
10854     } else if (PrevDecl) {
10855       // This is an invalid name redefinition.
10856       Diag(Loc, diag::err_redefinition_different_kind)
10857         << II;
10858       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10859       IsInvalid = true;
10860       // Continue on to push Namespc as current DeclContext and return it.
10861     } else if (II->isStr("std") &&
10862                CurContext->getRedeclContext()->isTranslationUnit()) {
10863       // This is the first "real" definition of the namespace "std", so update
10864       // our cache of the "std" namespace to point at this definition.
10865       PrevNS = getStdNamespace();
10866       IsStd = true;
10867       AddToKnown = !IsInline;
10868     } else {
10869       // We've seen this namespace for the first time.
10870       AddToKnown = !IsInline;
10871     }
10872   } else {
10873     // Anonymous namespaces.
10874 
10875     // Determine whether the parent already has an anonymous namespace.
10876     DeclContext *Parent = CurContext->getRedeclContext();
10877     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10878       PrevNS = TU->getAnonymousNamespace();
10879     } else {
10880       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10881       PrevNS = ND->getAnonymousNamespace();
10882     }
10883 
10884     if (PrevNS && IsInline != PrevNS->isInline())
10885       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10886                                       &IsInline, PrevNS);
10887   }
10888 
10889   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10890                                                  StartLoc, Loc, II, PrevNS);
10891   if (IsInvalid)
10892     Namespc->setInvalidDecl();
10893 
10894   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10895   AddPragmaAttributes(DeclRegionScope, Namespc);
10896 
10897   // FIXME: Should we be merging attributes?
10898   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10899     PushNamespaceVisibilityAttr(Attr, Loc);
10900 
10901   if (IsStd)
10902     StdNamespace = Namespc;
10903   if (AddToKnown)
10904     KnownNamespaces[Namespc] = false;
10905 
10906   if (II) {
10907     PushOnScopeChains(Namespc, DeclRegionScope);
10908   } else {
10909     // Link the anonymous namespace into its parent.
10910     DeclContext *Parent = CurContext->getRedeclContext();
10911     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10912       TU->setAnonymousNamespace(Namespc);
10913     } else {
10914       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10915     }
10916 
10917     CurContext->addDecl(Namespc);
10918 
10919     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10920     //   behaves as if it were replaced by
10921     //     namespace unique { /* empty body */ }
10922     //     using namespace unique;
10923     //     namespace unique { namespace-body }
10924     //   where all occurrences of 'unique' in a translation unit are
10925     //   replaced by the same identifier and this identifier differs
10926     //   from all other identifiers in the entire program.
10927 
10928     // We just create the namespace with an empty name and then add an
10929     // implicit using declaration, just like the standard suggests.
10930     //
10931     // CodeGen enforces the "universally unique" aspect by giving all
10932     // declarations semantically contained within an anonymous
10933     // namespace internal linkage.
10934 
10935     if (!PrevNS) {
10936       UD = UsingDirectiveDecl::Create(Context, Parent,
10937                                       /* 'using' */ LBrace,
10938                                       /* 'namespace' */ SourceLocation(),
10939                                       /* qualifier */ NestedNameSpecifierLoc(),
10940                                       /* identifier */ SourceLocation(),
10941                                       Namespc,
10942                                       /* Ancestor */ Parent);
10943       UD->setImplicit();
10944       Parent->addDecl(UD);
10945     }
10946   }
10947 
10948   ActOnDocumentableDecl(Namespc);
10949 
10950   // Although we could have an invalid decl (i.e. the namespace name is a
10951   // redefinition), push it as current DeclContext and try to continue parsing.
10952   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10953   // for the namespace has the declarations that showed up in that particular
10954   // namespace definition.
10955   PushDeclContext(NamespcScope, Namespc);
10956   return Namespc;
10957 }
10958 
10959 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10960 /// is a namespace alias, returns the namespace it points to.
10961 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10962   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10963     return AD->getNamespace();
10964   return dyn_cast_or_null<NamespaceDecl>(D);
10965 }
10966 
10967 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10968 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10969 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10970   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10971   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10972   Namespc->setRBraceLoc(RBrace);
10973   PopDeclContext();
10974   if (Namespc->hasAttr<VisibilityAttr>())
10975     PopPragmaVisibility(true, RBrace);
10976   // If this namespace contains an export-declaration, export it now.
10977   if (DeferredExportedNamespaces.erase(Namespc))
10978     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10979 }
10980 
10981 CXXRecordDecl *Sema::getStdBadAlloc() const {
10982   return cast_or_null<CXXRecordDecl>(
10983                                   StdBadAlloc.get(Context.getExternalSource()));
10984 }
10985 
10986 EnumDecl *Sema::getStdAlignValT() const {
10987   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10988 }
10989 
10990 NamespaceDecl *Sema::getStdNamespace() const {
10991   return cast_or_null<NamespaceDecl>(
10992                                  StdNamespace.get(Context.getExternalSource()));
10993 }
10994 
10995 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10996   if (!StdExperimentalNamespaceCache) {
10997     if (auto Std = getStdNamespace()) {
10998       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10999                           SourceLocation(), LookupNamespaceName);
11000       if (!LookupQualifiedName(Result, Std) ||
11001           !(StdExperimentalNamespaceCache =
11002                 Result.getAsSingle<NamespaceDecl>()))
11003         Result.suppressDiagnostics();
11004     }
11005   }
11006   return StdExperimentalNamespaceCache;
11007 }
11008 
11009 namespace {
11010 
11011 enum UnsupportedSTLSelect {
11012   USS_InvalidMember,
11013   USS_MissingMember,
11014   USS_NonTrivial,
11015   USS_Other
11016 };
11017 
11018 struct InvalidSTLDiagnoser {
11019   Sema &S;
11020   SourceLocation Loc;
11021   QualType TyForDiags;
11022 
11023   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11024                       const VarDecl *VD = nullptr) {
11025     {
11026       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11027                << TyForDiags << ((int)Sel);
11028       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11029         assert(!Name.empty());
11030         D << Name;
11031       }
11032     }
11033     if (Sel == USS_InvalidMember) {
11034       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11035           << VD << VD->getSourceRange();
11036     }
11037     return QualType();
11038   }
11039 };
11040 } // namespace
11041 
11042 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11043                                            SourceLocation Loc,
11044                                            ComparisonCategoryUsage Usage) {
11045   assert(getLangOpts().CPlusPlus &&
11046          "Looking for comparison category type outside of C++.");
11047 
11048   // Use an elaborated type for diagnostics which has a name containing the
11049   // prepended 'std' namespace but not any inline namespace names.
11050   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11051     auto *NNS =
11052         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11053     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11054   };
11055 
11056   // Check if we've already successfully checked the comparison category type
11057   // before. If so, skip checking it again.
11058   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11059   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11060     // The only thing we need to check is that the type has a reachable
11061     // definition in the current context.
11062     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11063       return QualType();
11064 
11065     return Info->getType();
11066   }
11067 
11068   // If lookup failed
11069   if (!Info) {
11070     std::string NameForDiags = "std::";
11071     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11072     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11073         << NameForDiags << (int)Usage;
11074     return QualType();
11075   }
11076 
11077   assert(Info->Kind == Kind);
11078   assert(Info->Record);
11079 
11080   // Update the Record decl in case we encountered a forward declaration on our
11081   // first pass. FIXME: This is a bit of a hack.
11082   if (Info->Record->hasDefinition())
11083     Info->Record = Info->Record->getDefinition();
11084 
11085   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11086     return QualType();
11087 
11088   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11089 
11090   if (!Info->Record->isTriviallyCopyable())
11091     return UnsupportedSTLError(USS_NonTrivial);
11092 
11093   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11094     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11095     // Tolerate empty base classes.
11096     if (Base->isEmpty())
11097       continue;
11098     // Reject STL implementations which have at least one non-empty base.
11099     return UnsupportedSTLError();
11100   }
11101 
11102   // Check that the STL has implemented the types using a single integer field.
11103   // This expectation allows better codegen for builtin operators. We require:
11104   //   (1) The class has exactly one field.
11105   //   (2) The field is an integral or enumeration type.
11106   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11107   if (std::distance(FIt, FEnd) != 1 ||
11108       !FIt->getType()->isIntegralOrEnumerationType()) {
11109     return UnsupportedSTLError();
11110   }
11111 
11112   // Build each of the require values and store them in Info.
11113   for (ComparisonCategoryResult CCR :
11114        ComparisonCategories::getPossibleResultsForType(Kind)) {
11115     StringRef MemName = ComparisonCategories::getResultString(CCR);
11116     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11117 
11118     if (!ValInfo)
11119       return UnsupportedSTLError(USS_MissingMember, MemName);
11120 
11121     VarDecl *VD = ValInfo->VD;
11122     assert(VD && "should not be null!");
11123 
11124     // Attempt to diagnose reasons why the STL definition of this type
11125     // might be foobar, including it failing to be a constant expression.
11126     // TODO Handle more ways the lookup or result can be invalid.
11127     if (!VD->isStaticDataMember() ||
11128         !VD->isUsableInConstantExpressions(Context))
11129       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11130 
11131     // Attempt to evaluate the var decl as a constant expression and extract
11132     // the value of its first field as a ICE. If this fails, the STL
11133     // implementation is not supported.
11134     if (!ValInfo->hasValidIntValue())
11135       return UnsupportedSTLError();
11136 
11137     MarkVariableReferenced(Loc, VD);
11138   }
11139 
11140   // We've successfully built the required types and expressions. Update
11141   // the cache and return the newly cached value.
11142   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11143   return Info->getType();
11144 }
11145 
11146 /// Retrieve the special "std" namespace, which may require us to
11147 /// implicitly define the namespace.
11148 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11149   if (!StdNamespace) {
11150     // The "std" namespace has not yet been defined, so build one implicitly.
11151     StdNamespace = NamespaceDecl::Create(Context,
11152                                          Context.getTranslationUnitDecl(),
11153                                          /*Inline=*/false,
11154                                          SourceLocation(), SourceLocation(),
11155                                          &PP.getIdentifierTable().get("std"),
11156                                          /*PrevDecl=*/nullptr);
11157     getStdNamespace()->setImplicit(true);
11158   }
11159 
11160   return getStdNamespace();
11161 }
11162 
11163 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11164   assert(getLangOpts().CPlusPlus &&
11165          "Looking for std::initializer_list outside of C++.");
11166 
11167   // We're looking for implicit instantiations of
11168   // template <typename E> class std::initializer_list.
11169 
11170   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11171     return false;
11172 
11173   ClassTemplateDecl *Template = nullptr;
11174   const TemplateArgument *Arguments = nullptr;
11175 
11176   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11177 
11178     ClassTemplateSpecializationDecl *Specialization =
11179         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11180     if (!Specialization)
11181       return false;
11182 
11183     Template = Specialization->getSpecializedTemplate();
11184     Arguments = Specialization->getTemplateArgs().data();
11185   } else if (const TemplateSpecializationType *TST =
11186                  Ty->getAs<TemplateSpecializationType>()) {
11187     Template = dyn_cast_or_null<ClassTemplateDecl>(
11188         TST->getTemplateName().getAsTemplateDecl());
11189     Arguments = TST->getArgs();
11190   }
11191   if (!Template)
11192     return false;
11193 
11194   if (!StdInitializerList) {
11195     // Haven't recognized std::initializer_list yet, maybe this is it.
11196     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11197     if (TemplateClass->getIdentifier() !=
11198             &PP.getIdentifierTable().get("initializer_list") ||
11199         !getStdNamespace()->InEnclosingNamespaceSetOf(
11200             TemplateClass->getDeclContext()))
11201       return false;
11202     // This is a template called std::initializer_list, but is it the right
11203     // template?
11204     TemplateParameterList *Params = Template->getTemplateParameters();
11205     if (Params->getMinRequiredArguments() != 1)
11206       return false;
11207     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11208       return false;
11209 
11210     // It's the right template.
11211     StdInitializerList = Template;
11212   }
11213 
11214   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11215     return false;
11216 
11217   // This is an instance of std::initializer_list. Find the argument type.
11218   if (Element)
11219     *Element = Arguments[0].getAsType();
11220   return true;
11221 }
11222 
11223 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11224   NamespaceDecl *Std = S.getStdNamespace();
11225   if (!Std) {
11226     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11227     return nullptr;
11228   }
11229 
11230   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11231                       Loc, Sema::LookupOrdinaryName);
11232   if (!S.LookupQualifiedName(Result, Std)) {
11233     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11234     return nullptr;
11235   }
11236   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11237   if (!Template) {
11238     Result.suppressDiagnostics();
11239     // We found something weird. Complain about the first thing we found.
11240     NamedDecl *Found = *Result.begin();
11241     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11242     return nullptr;
11243   }
11244 
11245   // We found some template called std::initializer_list. Now verify that it's
11246   // correct.
11247   TemplateParameterList *Params = Template->getTemplateParameters();
11248   if (Params->getMinRequiredArguments() != 1 ||
11249       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11250     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11251     return nullptr;
11252   }
11253 
11254   return Template;
11255 }
11256 
11257 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11258   if (!StdInitializerList) {
11259     StdInitializerList = LookupStdInitializerList(*this, Loc);
11260     if (!StdInitializerList)
11261       return QualType();
11262   }
11263 
11264   TemplateArgumentListInfo Args(Loc, Loc);
11265   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11266                                        Context.getTrivialTypeSourceInfo(Element,
11267                                                                         Loc)));
11268   return Context.getCanonicalType(
11269       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11270 }
11271 
11272 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11273   // C++ [dcl.init.list]p2:
11274   //   A constructor is an initializer-list constructor if its first parameter
11275   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11276   //   std::initializer_list<E> for some type E, and either there are no other
11277   //   parameters or else all other parameters have default arguments.
11278   if (!Ctor->hasOneParamOrDefaultArgs())
11279     return false;
11280 
11281   QualType ArgType = Ctor->getParamDecl(0)->getType();
11282   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11283     ArgType = RT->getPointeeType().getUnqualifiedType();
11284 
11285   return isStdInitializerList(ArgType, nullptr);
11286 }
11287 
11288 /// Determine whether a using statement is in a context where it will be
11289 /// apply in all contexts.
11290 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11291   switch (CurContext->getDeclKind()) {
11292     case Decl::TranslationUnit:
11293       return true;
11294     case Decl::LinkageSpec:
11295       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11296     default:
11297       return false;
11298   }
11299 }
11300 
11301 namespace {
11302 
11303 // Callback to only accept typo corrections that are namespaces.
11304 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11305 public:
11306   bool ValidateCandidate(const TypoCorrection &candidate) override {
11307     if (NamedDecl *ND = candidate.getCorrectionDecl())
11308       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11309     return false;
11310   }
11311 
11312   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11313     return std::make_unique<NamespaceValidatorCCC>(*this);
11314   }
11315 };
11316 
11317 }
11318 
11319 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11320                                        CXXScopeSpec &SS,
11321                                        SourceLocation IdentLoc,
11322                                        IdentifierInfo *Ident) {
11323   R.clear();
11324   NamespaceValidatorCCC CCC{};
11325   if (TypoCorrection Corrected =
11326           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11327                         Sema::CTK_ErrorRecovery)) {
11328     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11329       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11330       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11331                               Ident->getName().equals(CorrectedStr);
11332       S.diagnoseTypo(Corrected,
11333                      S.PDiag(diag::err_using_directive_member_suggest)
11334                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11335                      S.PDiag(diag::note_namespace_defined_here));
11336     } else {
11337       S.diagnoseTypo(Corrected,
11338                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11339                      S.PDiag(diag::note_namespace_defined_here));
11340     }
11341     R.addDecl(Corrected.getFoundDecl());
11342     return true;
11343   }
11344   return false;
11345 }
11346 
11347 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11348                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11349                                 SourceLocation IdentLoc,
11350                                 IdentifierInfo *NamespcName,
11351                                 const ParsedAttributesView &AttrList) {
11352   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11353   assert(NamespcName && "Invalid NamespcName.");
11354   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11355 
11356   // This can only happen along a recovery path.
11357   while (S->isTemplateParamScope())
11358     S = S->getParent();
11359   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11360 
11361   UsingDirectiveDecl *UDir = nullptr;
11362   NestedNameSpecifier *Qualifier = nullptr;
11363   if (SS.isSet())
11364     Qualifier = SS.getScopeRep();
11365 
11366   // Lookup namespace name.
11367   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11368   LookupParsedName(R, S, &SS);
11369   if (R.isAmbiguous())
11370     return nullptr;
11371 
11372   if (R.empty()) {
11373     R.clear();
11374     // Allow "using namespace std;" or "using namespace ::std;" even if
11375     // "std" hasn't been defined yet, for GCC compatibility.
11376     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11377         NamespcName->isStr("std")) {
11378       Diag(IdentLoc, diag::ext_using_undefined_std);
11379       R.addDecl(getOrCreateStdNamespace());
11380       R.resolveKind();
11381     }
11382     // Otherwise, attempt typo correction.
11383     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11384   }
11385 
11386   if (!R.empty()) {
11387     NamedDecl *Named = R.getRepresentativeDecl();
11388     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11389     assert(NS && "expected namespace decl");
11390 
11391     // The use of a nested name specifier may trigger deprecation warnings.
11392     DiagnoseUseOfDecl(Named, IdentLoc);
11393 
11394     // C++ [namespace.udir]p1:
11395     //   A using-directive specifies that the names in the nominated
11396     //   namespace can be used in the scope in which the
11397     //   using-directive appears after the using-directive. During
11398     //   unqualified name lookup (3.4.1), the names appear as if they
11399     //   were declared in the nearest enclosing namespace which
11400     //   contains both the using-directive and the nominated
11401     //   namespace. [Note: in this context, "contains" means "contains
11402     //   directly or indirectly". ]
11403 
11404     // Find enclosing context containing both using-directive and
11405     // nominated namespace.
11406     DeclContext *CommonAncestor = NS;
11407     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11408       CommonAncestor = CommonAncestor->getParent();
11409 
11410     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11411                                       SS.getWithLocInContext(Context),
11412                                       IdentLoc, Named, CommonAncestor);
11413 
11414     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11415         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11416       Diag(IdentLoc, diag::warn_using_directive_in_header);
11417     }
11418 
11419     PushUsingDirective(S, UDir);
11420   } else {
11421     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11422   }
11423 
11424   if (UDir)
11425     ProcessDeclAttributeList(S, UDir, AttrList);
11426 
11427   return UDir;
11428 }
11429 
11430 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11431   // If the scope has an associated entity and the using directive is at
11432   // namespace or translation unit scope, add the UsingDirectiveDecl into
11433   // its lookup structure so qualified name lookup can find it.
11434   DeclContext *Ctx = S->getEntity();
11435   if (Ctx && !Ctx->isFunctionOrMethod())
11436     Ctx->addDecl(UDir);
11437   else
11438     // Otherwise, it is at block scope. The using-directives will affect lookup
11439     // only to the end of the scope.
11440     S->PushUsingDirective(UDir);
11441 }
11442 
11443 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11444                                   SourceLocation UsingLoc,
11445                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11446                                   UnqualifiedId &Name,
11447                                   SourceLocation EllipsisLoc,
11448                                   const ParsedAttributesView &AttrList) {
11449   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11450 
11451   if (SS.isEmpty()) {
11452     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11453     return nullptr;
11454   }
11455 
11456   switch (Name.getKind()) {
11457   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11458   case UnqualifiedIdKind::IK_Identifier:
11459   case UnqualifiedIdKind::IK_OperatorFunctionId:
11460   case UnqualifiedIdKind::IK_LiteralOperatorId:
11461   case UnqualifiedIdKind::IK_ConversionFunctionId:
11462     break;
11463 
11464   case UnqualifiedIdKind::IK_ConstructorName:
11465   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11466     // C++11 inheriting constructors.
11467     Diag(Name.getBeginLoc(),
11468          getLangOpts().CPlusPlus11
11469              ? diag::warn_cxx98_compat_using_decl_constructor
11470              : diag::err_using_decl_constructor)
11471         << SS.getRange();
11472 
11473     if (getLangOpts().CPlusPlus11) break;
11474 
11475     return nullptr;
11476 
11477   case UnqualifiedIdKind::IK_DestructorName:
11478     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11479     return nullptr;
11480 
11481   case UnqualifiedIdKind::IK_TemplateId:
11482     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11483         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11484     return nullptr;
11485 
11486   case UnqualifiedIdKind::IK_DeductionGuideName:
11487     llvm_unreachable("cannot parse qualified deduction guide name");
11488   }
11489 
11490   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11491   DeclarationName TargetName = TargetNameInfo.getName();
11492   if (!TargetName)
11493     return nullptr;
11494 
11495   // Warn about access declarations.
11496   if (UsingLoc.isInvalid()) {
11497     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11498                                  ? diag::err_access_decl
11499                                  : diag::warn_access_decl_deprecated)
11500         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11501   }
11502 
11503   if (EllipsisLoc.isInvalid()) {
11504     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11505         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11506       return nullptr;
11507   } else {
11508     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11509         !TargetNameInfo.containsUnexpandedParameterPack()) {
11510       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11511         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11512       EllipsisLoc = SourceLocation();
11513     }
11514   }
11515 
11516   NamedDecl *UD =
11517       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11518                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11519                             /*IsInstantiation*/false);
11520   if (UD)
11521     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11522 
11523   return UD;
11524 }
11525 
11526 /// Determine whether a using declaration considers the given
11527 /// declarations as "equivalent", e.g., if they are redeclarations of
11528 /// the same entity or are both typedefs of the same type.
11529 static bool
11530 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11531   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11532     return true;
11533 
11534   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11535     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11536       return Context.hasSameType(TD1->getUnderlyingType(),
11537                                  TD2->getUnderlyingType());
11538 
11539   return false;
11540 }
11541 
11542 
11543 /// Determines whether to create a using shadow decl for a particular
11544 /// decl, given the set of decls existing prior to this using lookup.
11545 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11546                                 const LookupResult &Previous,
11547                                 UsingShadowDecl *&PrevShadow) {
11548   // Diagnose finding a decl which is not from a base class of the
11549   // current class.  We do this now because there are cases where this
11550   // function will silently decide not to build a shadow decl, which
11551   // will pre-empt further diagnostics.
11552   //
11553   // We don't need to do this in C++11 because we do the check once on
11554   // the qualifier.
11555   //
11556   // FIXME: diagnose the following if we care enough:
11557   //   struct A { int foo; };
11558   //   struct B : A { using A::foo; };
11559   //   template <class T> struct C : A {};
11560   //   template <class T> struct D : C<T> { using B::foo; } // <---
11561   // This is invalid (during instantiation) in C++03 because B::foo
11562   // resolves to the using decl in B, which is not a base class of D<T>.
11563   // We can't diagnose it immediately because C<T> is an unknown
11564   // specialization.  The UsingShadowDecl in D<T> then points directly
11565   // to A::foo, which will look well-formed when we instantiate.
11566   // The right solution is to not collapse the shadow-decl chain.
11567   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11568     DeclContext *OrigDC = Orig->getDeclContext();
11569 
11570     // Handle enums and anonymous structs.
11571     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11572     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11573     while (OrigRec->isAnonymousStructOrUnion())
11574       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11575 
11576     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11577       if (OrigDC == CurContext) {
11578         Diag(Using->getLocation(),
11579              diag::err_using_decl_nested_name_specifier_is_current_class)
11580           << Using->getQualifierLoc().getSourceRange();
11581         Diag(Orig->getLocation(), diag::note_using_decl_target);
11582         Using->setInvalidDecl();
11583         return true;
11584       }
11585 
11586       Diag(Using->getQualifierLoc().getBeginLoc(),
11587            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11588         << Using->getQualifier()
11589         << cast<CXXRecordDecl>(CurContext)
11590         << Using->getQualifierLoc().getSourceRange();
11591       Diag(Orig->getLocation(), diag::note_using_decl_target);
11592       Using->setInvalidDecl();
11593       return true;
11594     }
11595   }
11596 
11597   if (Previous.empty()) return false;
11598 
11599   NamedDecl *Target = Orig;
11600   if (isa<UsingShadowDecl>(Target))
11601     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11602 
11603   // If the target happens to be one of the previous declarations, we
11604   // don't have a conflict.
11605   //
11606   // FIXME: but we might be increasing its access, in which case we
11607   // should redeclare it.
11608   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11609   bool FoundEquivalentDecl = false;
11610   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11611          I != E; ++I) {
11612     NamedDecl *D = (*I)->getUnderlyingDecl();
11613     // We can have UsingDecls in our Previous results because we use the same
11614     // LookupResult for checking whether the UsingDecl itself is a valid
11615     // redeclaration.
11616     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11617       continue;
11618 
11619     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11620       // C++ [class.mem]p19:
11621       //   If T is the name of a class, then [every named member other than
11622       //   a non-static data member] shall have a name different from T
11623       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11624           !isa<IndirectFieldDecl>(Target) &&
11625           !isa<UnresolvedUsingValueDecl>(Target) &&
11626           DiagnoseClassNameShadow(
11627               CurContext,
11628               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11629         return true;
11630     }
11631 
11632     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11633       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11634         PrevShadow = Shadow;
11635       FoundEquivalentDecl = true;
11636     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11637       // We don't conflict with an existing using shadow decl of an equivalent
11638       // declaration, but we're not a redeclaration of it.
11639       FoundEquivalentDecl = true;
11640     }
11641 
11642     if (isVisible(D))
11643       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11644   }
11645 
11646   if (FoundEquivalentDecl)
11647     return false;
11648 
11649   if (FunctionDecl *FD = Target->getAsFunction()) {
11650     NamedDecl *OldDecl = nullptr;
11651     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11652                           /*IsForUsingDecl*/ true)) {
11653     case Ovl_Overload:
11654       return false;
11655 
11656     case Ovl_NonFunction:
11657       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11658       break;
11659 
11660     // We found a decl with the exact signature.
11661     case Ovl_Match:
11662       // If we're in a record, we want to hide the target, so we
11663       // return true (without a diagnostic) to tell the caller not to
11664       // build a shadow decl.
11665       if (CurContext->isRecord())
11666         return true;
11667 
11668       // If we're not in a record, this is an error.
11669       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11670       break;
11671     }
11672 
11673     Diag(Target->getLocation(), diag::note_using_decl_target);
11674     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11675     Using->setInvalidDecl();
11676     return true;
11677   }
11678 
11679   // Target is not a function.
11680 
11681   if (isa<TagDecl>(Target)) {
11682     // No conflict between a tag and a non-tag.
11683     if (!Tag) return false;
11684 
11685     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11686     Diag(Target->getLocation(), diag::note_using_decl_target);
11687     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11688     Using->setInvalidDecl();
11689     return true;
11690   }
11691 
11692   // No conflict between a tag and a non-tag.
11693   if (!NonTag) return false;
11694 
11695   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11696   Diag(Target->getLocation(), diag::note_using_decl_target);
11697   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11698   Using->setInvalidDecl();
11699   return true;
11700 }
11701 
11702 /// Determine whether a direct base class is a virtual base class.
11703 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11704   if (!Derived->getNumVBases())
11705     return false;
11706   for (auto &B : Derived->bases())
11707     if (B.getType()->getAsCXXRecordDecl() == Base)
11708       return B.isVirtual();
11709   llvm_unreachable("not a direct base class");
11710 }
11711 
11712 /// Builds a shadow declaration corresponding to a 'using' declaration.
11713 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11714                                             UsingDecl *UD,
11715                                             NamedDecl *Orig,
11716                                             UsingShadowDecl *PrevDecl) {
11717   // If we resolved to another shadow declaration, just coalesce them.
11718   NamedDecl *Target = Orig;
11719   if (isa<UsingShadowDecl>(Target)) {
11720     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11721     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11722   }
11723 
11724   NamedDecl *NonTemplateTarget = Target;
11725   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11726     NonTemplateTarget = TargetTD->getTemplatedDecl();
11727 
11728   UsingShadowDecl *Shadow;
11729   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11730     bool IsVirtualBase =
11731         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11732                             UD->getQualifier()->getAsRecordDecl());
11733     Shadow = ConstructorUsingShadowDecl::Create(
11734         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11735   } else {
11736     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11737                                      Target);
11738   }
11739   UD->addShadowDecl(Shadow);
11740 
11741   Shadow->setAccess(UD->getAccess());
11742   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11743     Shadow->setInvalidDecl();
11744 
11745   Shadow->setPreviousDecl(PrevDecl);
11746 
11747   if (S)
11748     PushOnScopeChains(Shadow, S);
11749   else
11750     CurContext->addDecl(Shadow);
11751 
11752 
11753   return Shadow;
11754 }
11755 
11756 /// Hides a using shadow declaration.  This is required by the current
11757 /// using-decl implementation when a resolvable using declaration in a
11758 /// class is followed by a declaration which would hide or override
11759 /// one or more of the using decl's targets; for example:
11760 ///
11761 ///   struct Base { void foo(int); };
11762 ///   struct Derived : Base {
11763 ///     using Base::foo;
11764 ///     void foo(int);
11765 ///   };
11766 ///
11767 /// The governing language is C++03 [namespace.udecl]p12:
11768 ///
11769 ///   When a using-declaration brings names from a base class into a
11770 ///   derived class scope, member functions in the derived class
11771 ///   override and/or hide member functions with the same name and
11772 ///   parameter types in a base class (rather than conflicting).
11773 ///
11774 /// There are two ways to implement this:
11775 ///   (1) optimistically create shadow decls when they're not hidden
11776 ///       by existing declarations, or
11777 ///   (2) don't create any shadow decls (or at least don't make them
11778 ///       visible) until we've fully parsed/instantiated the class.
11779 /// The problem with (1) is that we might have to retroactively remove
11780 /// a shadow decl, which requires several O(n) operations because the
11781 /// decl structures are (very reasonably) not designed for removal.
11782 /// (2) avoids this but is very fiddly and phase-dependent.
11783 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11784   if (Shadow->getDeclName().getNameKind() ==
11785         DeclarationName::CXXConversionFunctionName)
11786     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11787 
11788   // Remove it from the DeclContext...
11789   Shadow->getDeclContext()->removeDecl(Shadow);
11790 
11791   // ...and the scope, if applicable...
11792   if (S) {
11793     S->RemoveDecl(Shadow);
11794     IdResolver.RemoveDecl(Shadow);
11795   }
11796 
11797   // ...and the using decl.
11798   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11799 
11800   // TODO: complain somehow if Shadow was used.  It shouldn't
11801   // be possible for this to happen, because...?
11802 }
11803 
11804 /// Find the base specifier for a base class with the given type.
11805 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11806                                                 QualType DesiredBase,
11807                                                 bool &AnyDependentBases) {
11808   // Check whether the named type is a direct base class.
11809   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11810     .getUnqualifiedType();
11811   for (auto &Base : Derived->bases()) {
11812     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11813     if (CanonicalDesiredBase == BaseType)
11814       return &Base;
11815     if (BaseType->isDependentType())
11816       AnyDependentBases = true;
11817   }
11818   return nullptr;
11819 }
11820 
11821 namespace {
11822 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11823 public:
11824   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11825                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11826       : HasTypenameKeyword(HasTypenameKeyword),
11827         IsInstantiation(IsInstantiation), OldNNS(NNS),
11828         RequireMemberOf(RequireMemberOf) {}
11829 
11830   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11831     NamedDecl *ND = Candidate.getCorrectionDecl();
11832 
11833     // Keywords are not valid here.
11834     if (!ND || isa<NamespaceDecl>(ND))
11835       return false;
11836 
11837     // Completely unqualified names are invalid for a 'using' declaration.
11838     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11839       return false;
11840 
11841     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11842     // reject.
11843 
11844     if (RequireMemberOf) {
11845       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11846       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11847         // No-one ever wants a using-declaration to name an injected-class-name
11848         // of a base class, unless they're declaring an inheriting constructor.
11849         ASTContext &Ctx = ND->getASTContext();
11850         if (!Ctx.getLangOpts().CPlusPlus11)
11851           return false;
11852         QualType FoundType = Ctx.getRecordType(FoundRecord);
11853 
11854         // Check that the injected-class-name is named as a member of its own
11855         // type; we don't want to suggest 'using Derived::Base;', since that
11856         // means something else.
11857         NestedNameSpecifier *Specifier =
11858             Candidate.WillReplaceSpecifier()
11859                 ? Candidate.getCorrectionSpecifier()
11860                 : OldNNS;
11861         if (!Specifier->getAsType() ||
11862             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11863           return false;
11864 
11865         // Check that this inheriting constructor declaration actually names a
11866         // direct base class of the current class.
11867         bool AnyDependentBases = false;
11868         if (!findDirectBaseWithType(RequireMemberOf,
11869                                     Ctx.getRecordType(FoundRecord),
11870                                     AnyDependentBases) &&
11871             !AnyDependentBases)
11872           return false;
11873       } else {
11874         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11875         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11876           return false;
11877 
11878         // FIXME: Check that the base class member is accessible?
11879       }
11880     } else {
11881       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11882       if (FoundRecord && FoundRecord->isInjectedClassName())
11883         return false;
11884     }
11885 
11886     if (isa<TypeDecl>(ND))
11887       return HasTypenameKeyword || !IsInstantiation;
11888 
11889     return !HasTypenameKeyword;
11890   }
11891 
11892   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11893     return std::make_unique<UsingValidatorCCC>(*this);
11894   }
11895 
11896 private:
11897   bool HasTypenameKeyword;
11898   bool IsInstantiation;
11899   NestedNameSpecifier *OldNNS;
11900   CXXRecordDecl *RequireMemberOf;
11901 };
11902 } // end anonymous namespace
11903 
11904 /// Builds a using declaration.
11905 ///
11906 /// \param IsInstantiation - Whether this call arises from an
11907 ///   instantiation of an unresolved using declaration.  We treat
11908 ///   the lookup differently for these declarations.
11909 NamedDecl *Sema::BuildUsingDeclaration(
11910     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11911     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11912     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11913     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11914   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11915   SourceLocation IdentLoc = NameInfo.getLoc();
11916   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11917 
11918   // FIXME: We ignore attributes for now.
11919 
11920   // For an inheriting constructor declaration, the name of the using
11921   // declaration is the name of a constructor in this class, not in the
11922   // base class.
11923   DeclarationNameInfo UsingName = NameInfo;
11924   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11925     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11926       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11927           Context.getCanonicalType(Context.getRecordType(RD))));
11928 
11929   // Do the redeclaration lookup in the current scope.
11930   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11931                         ForVisibleRedeclaration);
11932   Previous.setHideTags(false);
11933   if (S) {
11934     LookupName(Previous, S);
11935 
11936     // It is really dumb that we have to do this.
11937     LookupResult::Filter F = Previous.makeFilter();
11938     while (F.hasNext()) {
11939       NamedDecl *D = F.next();
11940       if (!isDeclInScope(D, CurContext, S))
11941         F.erase();
11942       // If we found a local extern declaration that's not ordinarily visible,
11943       // and this declaration is being added to a non-block scope, ignore it.
11944       // We're only checking for scope conflicts here, not also for violations
11945       // of the linkage rules.
11946       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11947                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11948         F.erase();
11949     }
11950     F.done();
11951   } else {
11952     assert(IsInstantiation && "no scope in non-instantiation");
11953     if (CurContext->isRecord())
11954       LookupQualifiedName(Previous, CurContext);
11955     else {
11956       // No redeclaration check is needed here; in non-member contexts we
11957       // diagnosed all possible conflicts with other using-declarations when
11958       // building the template:
11959       //
11960       // For a dependent non-type using declaration, the only valid case is
11961       // if we instantiate to a single enumerator. We check for conflicts
11962       // between shadow declarations we introduce, and we check in the template
11963       // definition for conflicts between a non-type using declaration and any
11964       // other declaration, which together covers all cases.
11965       //
11966       // A dependent typename using declaration will never successfully
11967       // instantiate, since it will always name a class member, so we reject
11968       // that in the template definition.
11969     }
11970   }
11971 
11972   // Check for invalid redeclarations.
11973   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11974                                   SS, IdentLoc, Previous))
11975     return nullptr;
11976 
11977   // Check for bad qualifiers.
11978   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11979                               IdentLoc))
11980     return nullptr;
11981 
11982   DeclContext *LookupContext = computeDeclContext(SS);
11983   NamedDecl *D;
11984   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11985   if (!LookupContext || EllipsisLoc.isValid()) {
11986     if (HasTypenameKeyword) {
11987       // FIXME: not all declaration name kinds are legal here
11988       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11989                                               UsingLoc, TypenameLoc,
11990                                               QualifierLoc,
11991                                               IdentLoc, NameInfo.getName(),
11992                                               EllipsisLoc);
11993     } else {
11994       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11995                                            QualifierLoc, NameInfo, EllipsisLoc);
11996     }
11997     D->setAccess(AS);
11998     CurContext->addDecl(D);
11999     return D;
12000   }
12001 
12002   auto Build = [&](bool Invalid) {
12003     UsingDecl *UD =
12004         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12005                           UsingName, HasTypenameKeyword);
12006     UD->setAccess(AS);
12007     CurContext->addDecl(UD);
12008     UD->setInvalidDecl(Invalid);
12009     return UD;
12010   };
12011   auto BuildInvalid = [&]{ return Build(true); };
12012   auto BuildValid = [&]{ return Build(false); };
12013 
12014   if (RequireCompleteDeclContext(SS, LookupContext))
12015     return BuildInvalid();
12016 
12017   // Look up the target name.
12018   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12019 
12020   // Unlike most lookups, we don't always want to hide tag
12021   // declarations: tag names are visible through the using declaration
12022   // even if hidden by ordinary names, *except* in a dependent context
12023   // where it's important for the sanity of two-phase lookup.
12024   if (!IsInstantiation)
12025     R.setHideTags(false);
12026 
12027   // For the purposes of this lookup, we have a base object type
12028   // equal to that of the current context.
12029   if (CurContext->isRecord()) {
12030     R.setBaseObjectType(
12031                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12032   }
12033 
12034   LookupQualifiedName(R, LookupContext);
12035 
12036   // Try to correct typos if possible. If constructor name lookup finds no
12037   // results, that means the named class has no explicit constructors, and we
12038   // suppressed declaring implicit ones (probably because it's dependent or
12039   // invalid).
12040   if (R.empty() &&
12041       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12042     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12043     // it will believe that glibc provides a ::gets in cases where it does not,
12044     // and will try to pull it into namespace std with a using-declaration.
12045     // Just ignore the using-declaration in that case.
12046     auto *II = NameInfo.getName().getAsIdentifierInfo();
12047     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12048         CurContext->isStdNamespace() &&
12049         isa<TranslationUnitDecl>(LookupContext) &&
12050         getSourceManager().isInSystemHeader(UsingLoc))
12051       return nullptr;
12052     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12053                           dyn_cast<CXXRecordDecl>(CurContext));
12054     if (TypoCorrection Corrected =
12055             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12056                         CTK_ErrorRecovery)) {
12057       // We reject candidates where DroppedSpecifier == true, hence the
12058       // literal '0' below.
12059       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12060                                 << NameInfo.getName() << LookupContext << 0
12061                                 << SS.getRange());
12062 
12063       // If we picked a correction with no attached Decl we can't do anything
12064       // useful with it, bail out.
12065       NamedDecl *ND = Corrected.getCorrectionDecl();
12066       if (!ND)
12067         return BuildInvalid();
12068 
12069       // If we corrected to an inheriting constructor, handle it as one.
12070       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12071       if (RD && RD->isInjectedClassName()) {
12072         // The parent of the injected class name is the class itself.
12073         RD = cast<CXXRecordDecl>(RD->getParent());
12074 
12075         // Fix up the information we'll use to build the using declaration.
12076         if (Corrected.WillReplaceSpecifier()) {
12077           NestedNameSpecifierLocBuilder Builder;
12078           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12079                               QualifierLoc.getSourceRange());
12080           QualifierLoc = Builder.getWithLocInContext(Context);
12081         }
12082 
12083         // In this case, the name we introduce is the name of a derived class
12084         // constructor.
12085         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12086         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12087             Context.getCanonicalType(Context.getRecordType(CurClass))));
12088         UsingName.setNamedTypeInfo(nullptr);
12089         for (auto *Ctor : LookupConstructors(RD))
12090           R.addDecl(Ctor);
12091         R.resolveKind();
12092       } else {
12093         // FIXME: Pick up all the declarations if we found an overloaded
12094         // function.
12095         UsingName.setName(ND->getDeclName());
12096         R.addDecl(ND);
12097       }
12098     } else {
12099       Diag(IdentLoc, diag::err_no_member)
12100         << NameInfo.getName() << LookupContext << SS.getRange();
12101       return BuildInvalid();
12102     }
12103   }
12104 
12105   if (R.isAmbiguous())
12106     return BuildInvalid();
12107 
12108   if (HasTypenameKeyword) {
12109     // If we asked for a typename and got a non-type decl, error out.
12110     if (!R.getAsSingle<TypeDecl>()) {
12111       Diag(IdentLoc, diag::err_using_typename_non_type);
12112       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12113         Diag((*I)->getUnderlyingDecl()->getLocation(),
12114              diag::note_using_decl_target);
12115       return BuildInvalid();
12116     }
12117   } else {
12118     // If we asked for a non-typename and we got a type, error out,
12119     // but only if this is an instantiation of an unresolved using
12120     // decl.  Otherwise just silently find the type name.
12121     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12122       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12123       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12124       return BuildInvalid();
12125     }
12126   }
12127 
12128   // C++14 [namespace.udecl]p6:
12129   // A using-declaration shall not name a namespace.
12130   if (R.getAsSingle<NamespaceDecl>()) {
12131     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12132       << SS.getRange();
12133     return BuildInvalid();
12134   }
12135 
12136   // C++14 [namespace.udecl]p7:
12137   // A using-declaration shall not name a scoped enumerator.
12138   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12139     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12140       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12141         << SS.getRange();
12142       return BuildInvalid();
12143     }
12144   }
12145 
12146   UsingDecl *UD = BuildValid();
12147 
12148   // Some additional rules apply to inheriting constructors.
12149   if (UsingName.getName().getNameKind() ==
12150         DeclarationName::CXXConstructorName) {
12151     // Suppress access diagnostics; the access check is instead performed at the
12152     // point of use for an inheriting constructor.
12153     R.suppressDiagnostics();
12154     if (CheckInheritingConstructorUsingDecl(UD))
12155       return UD;
12156   }
12157 
12158   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12159     UsingShadowDecl *PrevDecl = nullptr;
12160     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12161       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12162   }
12163 
12164   return UD;
12165 }
12166 
12167 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12168                                     ArrayRef<NamedDecl *> Expansions) {
12169   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12170          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12171          isa<UsingPackDecl>(InstantiatedFrom));
12172 
12173   auto *UPD =
12174       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12175   UPD->setAccess(InstantiatedFrom->getAccess());
12176   CurContext->addDecl(UPD);
12177   return UPD;
12178 }
12179 
12180 /// Additional checks for a using declaration referring to a constructor name.
12181 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12182   assert(!UD->hasTypename() && "expecting a constructor name");
12183 
12184   const Type *SourceType = UD->getQualifier()->getAsType();
12185   assert(SourceType &&
12186          "Using decl naming constructor doesn't have type in scope spec.");
12187   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12188 
12189   // Check whether the named type is a direct base class.
12190   bool AnyDependentBases = false;
12191   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12192                                       AnyDependentBases);
12193   if (!Base && !AnyDependentBases) {
12194     Diag(UD->getUsingLoc(),
12195          diag::err_using_decl_constructor_not_in_direct_base)
12196       << UD->getNameInfo().getSourceRange()
12197       << QualType(SourceType, 0) << TargetClass;
12198     UD->setInvalidDecl();
12199     return true;
12200   }
12201 
12202   if (Base)
12203     Base->setInheritConstructors();
12204 
12205   return false;
12206 }
12207 
12208 /// Checks that the given using declaration is not an invalid
12209 /// redeclaration.  Note that this is checking only for the using decl
12210 /// itself, not for any ill-formedness among the UsingShadowDecls.
12211 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12212                                        bool HasTypenameKeyword,
12213                                        const CXXScopeSpec &SS,
12214                                        SourceLocation NameLoc,
12215                                        const LookupResult &Prev) {
12216   NestedNameSpecifier *Qual = SS.getScopeRep();
12217 
12218   // C++03 [namespace.udecl]p8:
12219   // C++0x [namespace.udecl]p10:
12220   //   A using-declaration is a declaration and can therefore be used
12221   //   repeatedly where (and only where) multiple declarations are
12222   //   allowed.
12223   //
12224   // That's in non-member contexts.
12225   if (!CurContext->getRedeclContext()->isRecord()) {
12226     // A dependent qualifier outside a class can only ever resolve to an
12227     // enumeration type. Therefore it conflicts with any other non-type
12228     // declaration in the same scope.
12229     // FIXME: How should we check for dependent type-type conflicts at block
12230     // scope?
12231     if (Qual->isDependent() && !HasTypenameKeyword) {
12232       for (auto *D : Prev) {
12233         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12234           bool OldCouldBeEnumerator =
12235               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12236           Diag(NameLoc,
12237                OldCouldBeEnumerator ? diag::err_redefinition
12238                                     : diag::err_redefinition_different_kind)
12239               << Prev.getLookupName();
12240           Diag(D->getLocation(), diag::note_previous_definition);
12241           return true;
12242         }
12243       }
12244     }
12245     return false;
12246   }
12247 
12248   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12249     NamedDecl *D = *I;
12250 
12251     bool DTypename;
12252     NestedNameSpecifier *DQual;
12253     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12254       DTypename = UD->hasTypename();
12255       DQual = UD->getQualifier();
12256     } else if (UnresolvedUsingValueDecl *UD
12257                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12258       DTypename = false;
12259       DQual = UD->getQualifier();
12260     } else if (UnresolvedUsingTypenameDecl *UD
12261                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12262       DTypename = true;
12263       DQual = UD->getQualifier();
12264     } else continue;
12265 
12266     // using decls differ if one says 'typename' and the other doesn't.
12267     // FIXME: non-dependent using decls?
12268     if (HasTypenameKeyword != DTypename) continue;
12269 
12270     // using decls differ if they name different scopes (but note that
12271     // template instantiation can cause this check to trigger when it
12272     // didn't before instantiation).
12273     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12274         Context.getCanonicalNestedNameSpecifier(DQual))
12275       continue;
12276 
12277     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12278     Diag(D->getLocation(), diag::note_using_decl) << 1;
12279     return true;
12280   }
12281 
12282   return false;
12283 }
12284 
12285 
12286 /// Checks that the given nested-name qualifier used in a using decl
12287 /// in the current context is appropriately related to the current
12288 /// scope.  If an error is found, diagnoses it and returns true.
12289 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12290                                    bool HasTypename,
12291                                    const CXXScopeSpec &SS,
12292                                    const DeclarationNameInfo &NameInfo,
12293                                    SourceLocation NameLoc) {
12294   DeclContext *NamedContext = computeDeclContext(SS);
12295 
12296   if (!CurContext->isRecord()) {
12297     // C++03 [namespace.udecl]p3:
12298     // C++0x [namespace.udecl]p8:
12299     //   A using-declaration for a class member shall be a member-declaration.
12300 
12301     // If we weren't able to compute a valid scope, it might validly be a
12302     // dependent class scope or a dependent enumeration unscoped scope. If
12303     // we have a 'typename' keyword, the scope must resolve to a class type.
12304     if ((HasTypename && !NamedContext) ||
12305         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12306       auto *RD = NamedContext
12307                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12308                      : nullptr;
12309       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12310         RD = nullptr;
12311 
12312       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12313         << SS.getRange();
12314 
12315       // If we have a complete, non-dependent source type, try to suggest a
12316       // way to get the same effect.
12317       if (!RD)
12318         return true;
12319 
12320       // Find what this using-declaration was referring to.
12321       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12322       R.setHideTags(false);
12323       R.suppressDiagnostics();
12324       LookupQualifiedName(R, RD);
12325 
12326       if (R.getAsSingle<TypeDecl>()) {
12327         if (getLangOpts().CPlusPlus11) {
12328           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12329           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12330             << 0 // alias declaration
12331             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12332                                           NameInfo.getName().getAsString() +
12333                                               " = ");
12334         } else {
12335           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12336           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12337           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12338             << 1 // typedef declaration
12339             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12340             << FixItHint::CreateInsertion(
12341                    InsertLoc, " " + NameInfo.getName().getAsString());
12342         }
12343       } else if (R.getAsSingle<VarDecl>()) {
12344         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12345         // repeating the type of the static data member here.
12346         FixItHint FixIt;
12347         if (getLangOpts().CPlusPlus11) {
12348           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12349           FixIt = FixItHint::CreateReplacement(
12350               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12351         }
12352 
12353         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12354           << 2 // reference declaration
12355           << FixIt;
12356       } else if (R.getAsSingle<EnumConstantDecl>()) {
12357         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12358         // repeating the type of the enumeration here, and we can't do so if
12359         // the type is anonymous.
12360         FixItHint FixIt;
12361         if (getLangOpts().CPlusPlus11) {
12362           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12363           FixIt = FixItHint::CreateReplacement(
12364               UsingLoc,
12365               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12366         }
12367 
12368         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12369           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12370           << FixIt;
12371       }
12372       return true;
12373     }
12374 
12375     // Otherwise, this might be valid.
12376     return false;
12377   }
12378 
12379   // The current scope is a record.
12380 
12381   // If the named context is dependent, we can't decide much.
12382   if (!NamedContext) {
12383     // FIXME: in C++0x, we can diagnose if we can prove that the
12384     // nested-name-specifier does not refer to a base class, which is
12385     // still possible in some cases.
12386 
12387     // Otherwise we have to conservatively report that things might be
12388     // okay.
12389     return false;
12390   }
12391 
12392   if (!NamedContext->isRecord()) {
12393     // Ideally this would point at the last name in the specifier,
12394     // but we don't have that level of source info.
12395     Diag(SS.getRange().getBegin(),
12396          diag::err_using_decl_nested_name_specifier_is_not_class)
12397       << SS.getScopeRep() << SS.getRange();
12398     return true;
12399   }
12400 
12401   if (!NamedContext->isDependentContext() &&
12402       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12403     return true;
12404 
12405   if (getLangOpts().CPlusPlus11) {
12406     // C++11 [namespace.udecl]p3:
12407     //   In a using-declaration used as a member-declaration, the
12408     //   nested-name-specifier shall name a base class of the class
12409     //   being defined.
12410 
12411     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12412                                  cast<CXXRecordDecl>(NamedContext))) {
12413       if (CurContext == NamedContext) {
12414         Diag(NameLoc,
12415              diag::err_using_decl_nested_name_specifier_is_current_class)
12416           << SS.getRange();
12417         return true;
12418       }
12419 
12420       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12421         Diag(SS.getRange().getBegin(),
12422              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12423           << SS.getScopeRep()
12424           << cast<CXXRecordDecl>(CurContext)
12425           << SS.getRange();
12426       }
12427       return true;
12428     }
12429 
12430     return false;
12431   }
12432 
12433   // C++03 [namespace.udecl]p4:
12434   //   A using-declaration used as a member-declaration shall refer
12435   //   to a member of a base class of the class being defined [etc.].
12436 
12437   // Salient point: SS doesn't have to name a base class as long as
12438   // lookup only finds members from base classes.  Therefore we can
12439   // diagnose here only if we can prove that that can't happen,
12440   // i.e. if the class hierarchies provably don't intersect.
12441 
12442   // TODO: it would be nice if "definitely valid" results were cached
12443   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12444   // need to be repeated.
12445 
12446   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12447   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12448     Bases.insert(Base);
12449     return true;
12450   };
12451 
12452   // Collect all bases. Return false if we find a dependent base.
12453   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12454     return false;
12455 
12456   // Returns true if the base is dependent or is one of the accumulated base
12457   // classes.
12458   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12459     return !Bases.count(Base);
12460   };
12461 
12462   // Return false if the class has a dependent base or if it or one
12463   // of its bases is present in the base set of the current context.
12464   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12465       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12466     return false;
12467 
12468   Diag(SS.getRange().getBegin(),
12469        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12470     << SS.getScopeRep()
12471     << cast<CXXRecordDecl>(CurContext)
12472     << SS.getRange();
12473 
12474   return true;
12475 }
12476 
12477 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12478                                   MultiTemplateParamsArg TemplateParamLists,
12479                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12480                                   const ParsedAttributesView &AttrList,
12481                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12482   // Skip up to the relevant declaration scope.
12483   while (S->isTemplateParamScope())
12484     S = S->getParent();
12485   assert((S->getFlags() & Scope::DeclScope) &&
12486          "got alias-declaration outside of declaration scope");
12487 
12488   if (Type.isInvalid())
12489     return nullptr;
12490 
12491   bool Invalid = false;
12492   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12493   TypeSourceInfo *TInfo = nullptr;
12494   GetTypeFromParser(Type.get(), &TInfo);
12495 
12496   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12497     return nullptr;
12498 
12499   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12500                                       UPPC_DeclarationType)) {
12501     Invalid = true;
12502     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12503                                              TInfo->getTypeLoc().getBeginLoc());
12504   }
12505 
12506   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12507                         TemplateParamLists.size()
12508                             ? forRedeclarationInCurContext()
12509                             : ForVisibleRedeclaration);
12510   LookupName(Previous, S);
12511 
12512   // Warn about shadowing the name of a template parameter.
12513   if (Previous.isSingleResult() &&
12514       Previous.getFoundDecl()->isTemplateParameter()) {
12515     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12516     Previous.clear();
12517   }
12518 
12519   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12520          "name in alias declaration must be an identifier");
12521   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12522                                                Name.StartLocation,
12523                                                Name.Identifier, TInfo);
12524 
12525   NewTD->setAccess(AS);
12526 
12527   if (Invalid)
12528     NewTD->setInvalidDecl();
12529 
12530   ProcessDeclAttributeList(S, NewTD, AttrList);
12531   AddPragmaAttributes(S, NewTD);
12532 
12533   CheckTypedefForVariablyModifiedType(S, NewTD);
12534   Invalid |= NewTD->isInvalidDecl();
12535 
12536   bool Redeclaration = false;
12537 
12538   NamedDecl *NewND;
12539   if (TemplateParamLists.size()) {
12540     TypeAliasTemplateDecl *OldDecl = nullptr;
12541     TemplateParameterList *OldTemplateParams = nullptr;
12542 
12543     if (TemplateParamLists.size() != 1) {
12544       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12545         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12546          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12547     }
12548     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12549 
12550     // Check that we can declare a template here.
12551     if (CheckTemplateDeclScope(S, TemplateParams))
12552       return nullptr;
12553 
12554     // Only consider previous declarations in the same scope.
12555     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12556                          /*ExplicitInstantiationOrSpecialization*/false);
12557     if (!Previous.empty()) {
12558       Redeclaration = true;
12559 
12560       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12561       if (!OldDecl && !Invalid) {
12562         Diag(UsingLoc, diag::err_redefinition_different_kind)
12563           << Name.Identifier;
12564 
12565         NamedDecl *OldD = Previous.getRepresentativeDecl();
12566         if (OldD->getLocation().isValid())
12567           Diag(OldD->getLocation(), diag::note_previous_definition);
12568 
12569         Invalid = true;
12570       }
12571 
12572       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12573         if (TemplateParameterListsAreEqual(TemplateParams,
12574                                            OldDecl->getTemplateParameters(),
12575                                            /*Complain=*/true,
12576                                            TPL_TemplateMatch))
12577           OldTemplateParams =
12578               OldDecl->getMostRecentDecl()->getTemplateParameters();
12579         else
12580           Invalid = true;
12581 
12582         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12583         if (!Invalid &&
12584             !Context.hasSameType(OldTD->getUnderlyingType(),
12585                                  NewTD->getUnderlyingType())) {
12586           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12587           // but we can't reasonably accept it.
12588           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12589             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12590           if (OldTD->getLocation().isValid())
12591             Diag(OldTD->getLocation(), diag::note_previous_definition);
12592           Invalid = true;
12593         }
12594       }
12595     }
12596 
12597     // Merge any previous default template arguments into our parameters,
12598     // and check the parameter list.
12599     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12600                                    TPC_TypeAliasTemplate))
12601       return nullptr;
12602 
12603     TypeAliasTemplateDecl *NewDecl =
12604       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12605                                     Name.Identifier, TemplateParams,
12606                                     NewTD);
12607     NewTD->setDescribedAliasTemplate(NewDecl);
12608 
12609     NewDecl->setAccess(AS);
12610 
12611     if (Invalid)
12612       NewDecl->setInvalidDecl();
12613     else if (OldDecl) {
12614       NewDecl->setPreviousDecl(OldDecl);
12615       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12616     }
12617 
12618     NewND = NewDecl;
12619   } else {
12620     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12621       setTagNameForLinkagePurposes(TD, NewTD);
12622       handleTagNumbering(TD, S);
12623     }
12624     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12625     NewND = NewTD;
12626   }
12627 
12628   PushOnScopeChains(NewND, S);
12629   ActOnDocumentableDecl(NewND);
12630   return NewND;
12631 }
12632 
12633 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12634                                    SourceLocation AliasLoc,
12635                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12636                                    SourceLocation IdentLoc,
12637                                    IdentifierInfo *Ident) {
12638 
12639   // Lookup the namespace name.
12640   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12641   LookupParsedName(R, S, &SS);
12642 
12643   if (R.isAmbiguous())
12644     return nullptr;
12645 
12646   if (R.empty()) {
12647     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12648       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12649       return nullptr;
12650     }
12651   }
12652   assert(!R.isAmbiguous() && !R.empty());
12653   NamedDecl *ND = R.getRepresentativeDecl();
12654 
12655   // Check if we have a previous declaration with the same name.
12656   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12657                      ForVisibleRedeclaration);
12658   LookupName(PrevR, S);
12659 
12660   // Check we're not shadowing a template parameter.
12661   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12662     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12663     PrevR.clear();
12664   }
12665 
12666   // Filter out any other lookup result from an enclosing scope.
12667   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12668                        /*AllowInlineNamespace*/false);
12669 
12670   // Find the previous declaration and check that we can redeclare it.
12671   NamespaceAliasDecl *Prev = nullptr;
12672   if (PrevR.isSingleResult()) {
12673     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12674     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12675       // We already have an alias with the same name that points to the same
12676       // namespace; check that it matches.
12677       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12678         Prev = AD;
12679       } else if (isVisible(PrevDecl)) {
12680         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12681           << Alias;
12682         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12683           << AD->getNamespace();
12684         return nullptr;
12685       }
12686     } else if (isVisible(PrevDecl)) {
12687       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12688                             ? diag::err_redefinition
12689                             : diag::err_redefinition_different_kind;
12690       Diag(AliasLoc, DiagID) << Alias;
12691       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12692       return nullptr;
12693     }
12694   }
12695 
12696   // The use of a nested name specifier may trigger deprecation warnings.
12697   DiagnoseUseOfDecl(ND, IdentLoc);
12698 
12699   NamespaceAliasDecl *AliasDecl =
12700     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12701                                Alias, SS.getWithLocInContext(Context),
12702                                IdentLoc, ND);
12703   if (Prev)
12704     AliasDecl->setPreviousDecl(Prev);
12705 
12706   PushOnScopeChains(AliasDecl, S);
12707   return AliasDecl;
12708 }
12709 
12710 namespace {
12711 struct SpecialMemberExceptionSpecInfo
12712     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12713   SourceLocation Loc;
12714   Sema::ImplicitExceptionSpecification ExceptSpec;
12715 
12716   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12717                                  Sema::CXXSpecialMember CSM,
12718                                  Sema::InheritedConstructorInfo *ICI,
12719                                  SourceLocation Loc)
12720       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12721 
12722   bool visitBase(CXXBaseSpecifier *Base);
12723   bool visitField(FieldDecl *FD);
12724 
12725   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12726                            unsigned Quals);
12727 
12728   void visitSubobjectCall(Subobject Subobj,
12729                           Sema::SpecialMemberOverloadResult SMOR);
12730 };
12731 }
12732 
12733 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12734   auto *RT = Base->getType()->getAs<RecordType>();
12735   if (!RT)
12736     return false;
12737 
12738   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12739   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12740   if (auto *BaseCtor = SMOR.getMethod()) {
12741     visitSubobjectCall(Base, BaseCtor);
12742     return false;
12743   }
12744 
12745   visitClassSubobject(BaseClass, Base, 0);
12746   return false;
12747 }
12748 
12749 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12750   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12751     Expr *E = FD->getInClassInitializer();
12752     if (!E)
12753       // FIXME: It's a little wasteful to build and throw away a
12754       // CXXDefaultInitExpr here.
12755       // FIXME: We should have a single context note pointing at Loc, and
12756       // this location should be MD->getLocation() instead, since that's
12757       // the location where we actually use the default init expression.
12758       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12759     if (E)
12760       ExceptSpec.CalledExpr(E);
12761   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12762                             ->getAs<RecordType>()) {
12763     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12764                         FD->getType().getCVRQualifiers());
12765   }
12766   return false;
12767 }
12768 
12769 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12770                                                          Subobject Subobj,
12771                                                          unsigned Quals) {
12772   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12773   bool IsMutable = Field && Field->isMutable();
12774   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12775 }
12776 
12777 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12778     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12779   // Note, if lookup fails, it doesn't matter what exception specification we
12780   // choose because the special member will be deleted.
12781   if (CXXMethodDecl *MD = SMOR.getMethod())
12782     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12783 }
12784 
12785 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12786   llvm::APSInt Result;
12787   ExprResult Converted = CheckConvertedConstantExpression(
12788       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12789   ExplicitSpec.setExpr(Converted.get());
12790   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12791     ExplicitSpec.setKind(Result.getBoolValue()
12792                              ? ExplicitSpecKind::ResolvedTrue
12793                              : ExplicitSpecKind::ResolvedFalse);
12794     return true;
12795   }
12796   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12797   return false;
12798 }
12799 
12800 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12801   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12802   if (!ExplicitExpr->isTypeDependent())
12803     tryResolveExplicitSpecifier(ES);
12804   return ES;
12805 }
12806 
12807 static Sema::ImplicitExceptionSpecification
12808 ComputeDefaultedSpecialMemberExceptionSpec(
12809     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12810     Sema::InheritedConstructorInfo *ICI) {
12811   ComputingExceptionSpec CES(S, MD, Loc);
12812 
12813   CXXRecordDecl *ClassDecl = MD->getParent();
12814 
12815   // C++ [except.spec]p14:
12816   //   An implicitly declared special member function (Clause 12) shall have an
12817   //   exception-specification. [...]
12818   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12819   if (ClassDecl->isInvalidDecl())
12820     return Info.ExceptSpec;
12821 
12822   // FIXME: If this diagnostic fires, we're probably missing a check for
12823   // attempting to resolve an exception specification before it's known
12824   // at a higher level.
12825   if (S.RequireCompleteType(MD->getLocation(),
12826                             S.Context.getRecordType(ClassDecl),
12827                             diag::err_exception_spec_incomplete_type))
12828     return Info.ExceptSpec;
12829 
12830   // C++1z [except.spec]p7:
12831   //   [Look for exceptions thrown by] a constructor selected [...] to
12832   //   initialize a potentially constructed subobject,
12833   // C++1z [except.spec]p8:
12834   //   The exception specification for an implicitly-declared destructor, or a
12835   //   destructor without a noexcept-specifier, is potentially-throwing if and
12836   //   only if any of the destructors for any of its potentially constructed
12837   //   subojects is potentially throwing.
12838   // FIXME: We respect the first rule but ignore the "potentially constructed"
12839   // in the second rule to resolve a core issue (no number yet) that would have
12840   // us reject:
12841   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12842   //   struct B : A {};
12843   //   struct C : B { void f(); };
12844   // ... due to giving B::~B() a non-throwing exception specification.
12845   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12846                                 : Info.VisitAllBases);
12847 
12848   return Info.ExceptSpec;
12849 }
12850 
12851 namespace {
12852 /// RAII object to register a special member as being currently declared.
12853 struct DeclaringSpecialMember {
12854   Sema &S;
12855   Sema::SpecialMemberDecl D;
12856   Sema::ContextRAII SavedContext;
12857   bool WasAlreadyBeingDeclared;
12858 
12859   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12860       : S(S), D(RD, CSM), SavedContext(S, RD) {
12861     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12862     if (WasAlreadyBeingDeclared)
12863       // This almost never happens, but if it does, ensure that our cache
12864       // doesn't contain a stale result.
12865       S.SpecialMemberCache.clear();
12866     else {
12867       // Register a note to be produced if we encounter an error while
12868       // declaring the special member.
12869       Sema::CodeSynthesisContext Ctx;
12870       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12871       // FIXME: We don't have a location to use here. Using the class's
12872       // location maintains the fiction that we declare all special members
12873       // with the class, but (1) it's not clear that lying about that helps our
12874       // users understand what's going on, and (2) there may be outer contexts
12875       // on the stack (some of which are relevant) and printing them exposes
12876       // our lies.
12877       Ctx.PointOfInstantiation = RD->getLocation();
12878       Ctx.Entity = RD;
12879       Ctx.SpecialMember = CSM;
12880       S.pushCodeSynthesisContext(Ctx);
12881     }
12882   }
12883   ~DeclaringSpecialMember() {
12884     if (!WasAlreadyBeingDeclared) {
12885       S.SpecialMembersBeingDeclared.erase(D);
12886       S.popCodeSynthesisContext();
12887     }
12888   }
12889 
12890   /// Are we already trying to declare this special member?
12891   bool isAlreadyBeingDeclared() const {
12892     return WasAlreadyBeingDeclared;
12893   }
12894 };
12895 }
12896 
12897 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12898   // Look up any existing declarations, but don't trigger declaration of all
12899   // implicit special members with this name.
12900   DeclarationName Name = FD->getDeclName();
12901   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12902                  ForExternalRedeclaration);
12903   for (auto *D : FD->getParent()->lookup(Name))
12904     if (auto *Acceptable = R.getAcceptableDecl(D))
12905       R.addDecl(Acceptable);
12906   R.resolveKind();
12907   R.suppressDiagnostics();
12908 
12909   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12910 }
12911 
12912 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12913                                           QualType ResultTy,
12914                                           ArrayRef<QualType> Args) {
12915   // Build an exception specification pointing back at this constructor.
12916   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12917 
12918   LangAS AS = getDefaultCXXMethodAddrSpace();
12919   if (AS != LangAS::Default) {
12920     EPI.TypeQuals.addAddressSpace(AS);
12921   }
12922 
12923   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12924   SpecialMem->setType(QT);
12925 }
12926 
12927 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12928                                                      CXXRecordDecl *ClassDecl) {
12929   // C++ [class.ctor]p5:
12930   //   A default constructor for a class X is a constructor of class X
12931   //   that can be called without an argument. If there is no
12932   //   user-declared constructor for class X, a default constructor is
12933   //   implicitly declared. An implicitly-declared default constructor
12934   //   is an inline public member of its class.
12935   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12936          "Should not build implicit default constructor!");
12937 
12938   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12939   if (DSM.isAlreadyBeingDeclared())
12940     return nullptr;
12941 
12942   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12943                                                      CXXDefaultConstructor,
12944                                                      false);
12945 
12946   // Create the actual constructor declaration.
12947   CanQualType ClassType
12948     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12949   SourceLocation ClassLoc = ClassDecl->getLocation();
12950   DeclarationName Name
12951     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12952   DeclarationNameInfo NameInfo(Name, ClassLoc);
12953   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12954       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12955       /*TInfo=*/nullptr, ExplicitSpecifier(),
12956       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12957       Constexpr ? CSK_constexpr : CSK_unspecified);
12958   DefaultCon->setAccess(AS_public);
12959   DefaultCon->setDefaulted();
12960 
12961   if (getLangOpts().CUDA) {
12962     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12963                                             DefaultCon,
12964                                             /* ConstRHS */ false,
12965                                             /* Diagnose */ false);
12966   }
12967 
12968   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12969 
12970   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12971   // constructors is easy to compute.
12972   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12973 
12974   // Note that we have declared this constructor.
12975   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12976 
12977   Scope *S = getScopeForContext(ClassDecl);
12978   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12979 
12980   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12981     SetDeclDeleted(DefaultCon, ClassLoc);
12982 
12983   if (S)
12984     PushOnScopeChains(DefaultCon, S, false);
12985   ClassDecl->addDecl(DefaultCon);
12986 
12987   return DefaultCon;
12988 }
12989 
12990 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12991                                             CXXConstructorDecl *Constructor) {
12992   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12993           !Constructor->doesThisDeclarationHaveABody() &&
12994           !Constructor->isDeleted()) &&
12995     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12996   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12997     return;
12998 
12999   CXXRecordDecl *ClassDecl = Constructor->getParent();
13000   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13001 
13002   SynthesizedFunctionScope Scope(*this, Constructor);
13003 
13004   // The exception specification is needed because we are defining the
13005   // function.
13006   ResolveExceptionSpec(CurrentLocation,
13007                        Constructor->getType()->castAs<FunctionProtoType>());
13008   MarkVTableUsed(CurrentLocation, ClassDecl);
13009 
13010   // Add a context note for diagnostics produced after this point.
13011   Scope.addContextNote(CurrentLocation);
13012 
13013   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13014     Constructor->setInvalidDecl();
13015     return;
13016   }
13017 
13018   SourceLocation Loc = Constructor->getEndLoc().isValid()
13019                            ? Constructor->getEndLoc()
13020                            : Constructor->getLocation();
13021   Constructor->setBody(new (Context) CompoundStmt(Loc));
13022   Constructor->markUsed(Context);
13023 
13024   if (ASTMutationListener *L = getASTMutationListener()) {
13025     L->CompletedImplicitDefinition(Constructor);
13026   }
13027 
13028   DiagnoseUninitializedFields(*this, Constructor);
13029 }
13030 
13031 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13032   // Perform any delayed checks on exception specifications.
13033   CheckDelayedMemberExceptionSpecs();
13034 }
13035 
13036 /// Find or create the fake constructor we synthesize to model constructing an
13037 /// object of a derived class via a constructor of a base class.
13038 CXXConstructorDecl *
13039 Sema::findInheritingConstructor(SourceLocation Loc,
13040                                 CXXConstructorDecl *BaseCtor,
13041                                 ConstructorUsingShadowDecl *Shadow) {
13042   CXXRecordDecl *Derived = Shadow->getParent();
13043   SourceLocation UsingLoc = Shadow->getLocation();
13044 
13045   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13046   // For now we use the name of the base class constructor as a member of the
13047   // derived class to indicate a (fake) inherited constructor name.
13048   DeclarationName Name = BaseCtor->getDeclName();
13049 
13050   // Check to see if we already have a fake constructor for this inherited
13051   // constructor call.
13052   for (NamedDecl *Ctor : Derived->lookup(Name))
13053     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13054                                ->getInheritedConstructor()
13055                                .getConstructor(),
13056                            BaseCtor))
13057       return cast<CXXConstructorDecl>(Ctor);
13058 
13059   DeclarationNameInfo NameInfo(Name, UsingLoc);
13060   TypeSourceInfo *TInfo =
13061       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13062   FunctionProtoTypeLoc ProtoLoc =
13063       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13064 
13065   // Check the inherited constructor is valid and find the list of base classes
13066   // from which it was inherited.
13067   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13068 
13069   bool Constexpr =
13070       BaseCtor->isConstexpr() &&
13071       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13072                                         false, BaseCtor, &ICI);
13073 
13074   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13075       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13076       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13077       /*isImplicitlyDeclared=*/true,
13078       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13079       InheritedConstructor(Shadow, BaseCtor),
13080       BaseCtor->getTrailingRequiresClause());
13081   if (Shadow->isInvalidDecl())
13082     DerivedCtor->setInvalidDecl();
13083 
13084   // Build an unevaluated exception specification for this fake constructor.
13085   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13086   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13087   EPI.ExceptionSpec.Type = EST_Unevaluated;
13088   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13089   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13090                                                FPT->getParamTypes(), EPI));
13091 
13092   // Build the parameter declarations.
13093   SmallVector<ParmVarDecl *, 16> ParamDecls;
13094   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13095     TypeSourceInfo *TInfo =
13096         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13097     ParmVarDecl *PD = ParmVarDecl::Create(
13098         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13099         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13100     PD->setScopeInfo(0, I);
13101     PD->setImplicit();
13102     // Ensure attributes are propagated onto parameters (this matters for
13103     // format, pass_object_size, ...).
13104     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13105     ParamDecls.push_back(PD);
13106     ProtoLoc.setParam(I, PD);
13107   }
13108 
13109   // Set up the new constructor.
13110   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13111   DerivedCtor->setAccess(BaseCtor->getAccess());
13112   DerivedCtor->setParams(ParamDecls);
13113   Derived->addDecl(DerivedCtor);
13114 
13115   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13116     SetDeclDeleted(DerivedCtor, UsingLoc);
13117 
13118   return DerivedCtor;
13119 }
13120 
13121 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13122   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13123                                Ctor->getInheritedConstructor().getShadowDecl());
13124   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13125                             /*Diagnose*/true);
13126 }
13127 
13128 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13129                                        CXXConstructorDecl *Constructor) {
13130   CXXRecordDecl *ClassDecl = Constructor->getParent();
13131   assert(Constructor->getInheritedConstructor() &&
13132          !Constructor->doesThisDeclarationHaveABody() &&
13133          !Constructor->isDeleted());
13134   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13135     return;
13136 
13137   // Initializations are performed "as if by a defaulted default constructor",
13138   // so enter the appropriate scope.
13139   SynthesizedFunctionScope Scope(*this, Constructor);
13140 
13141   // The exception specification is needed because we are defining the
13142   // function.
13143   ResolveExceptionSpec(CurrentLocation,
13144                        Constructor->getType()->castAs<FunctionProtoType>());
13145   MarkVTableUsed(CurrentLocation, ClassDecl);
13146 
13147   // Add a context note for diagnostics produced after this point.
13148   Scope.addContextNote(CurrentLocation);
13149 
13150   ConstructorUsingShadowDecl *Shadow =
13151       Constructor->getInheritedConstructor().getShadowDecl();
13152   CXXConstructorDecl *InheritedCtor =
13153       Constructor->getInheritedConstructor().getConstructor();
13154 
13155   // [class.inhctor.init]p1:
13156   //   initialization proceeds as if a defaulted default constructor is used to
13157   //   initialize the D object and each base class subobject from which the
13158   //   constructor was inherited
13159 
13160   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13161   CXXRecordDecl *RD = Shadow->getParent();
13162   SourceLocation InitLoc = Shadow->getLocation();
13163 
13164   // Build explicit initializers for all base classes from which the
13165   // constructor was inherited.
13166   SmallVector<CXXCtorInitializer*, 8> Inits;
13167   for (bool VBase : {false, true}) {
13168     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13169       if (B.isVirtual() != VBase)
13170         continue;
13171 
13172       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13173       if (!BaseRD)
13174         continue;
13175 
13176       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13177       if (!BaseCtor.first)
13178         continue;
13179 
13180       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13181       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13182           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13183 
13184       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13185       Inits.push_back(new (Context) CXXCtorInitializer(
13186           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13187           SourceLocation()));
13188     }
13189   }
13190 
13191   // We now proceed as if for a defaulted default constructor, with the relevant
13192   // initializers replaced.
13193 
13194   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13195     Constructor->setInvalidDecl();
13196     return;
13197   }
13198 
13199   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13200   Constructor->markUsed(Context);
13201 
13202   if (ASTMutationListener *L = getASTMutationListener()) {
13203     L->CompletedImplicitDefinition(Constructor);
13204   }
13205 
13206   DiagnoseUninitializedFields(*this, Constructor);
13207 }
13208 
13209 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13210   // C++ [class.dtor]p2:
13211   //   If a class has no user-declared destructor, a destructor is
13212   //   declared implicitly. An implicitly-declared destructor is an
13213   //   inline public member of its class.
13214   assert(ClassDecl->needsImplicitDestructor());
13215 
13216   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13217   if (DSM.isAlreadyBeingDeclared())
13218     return nullptr;
13219 
13220   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13221                                                      CXXDestructor,
13222                                                      false);
13223 
13224   // Create the actual destructor declaration.
13225   CanQualType ClassType
13226     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13227   SourceLocation ClassLoc = ClassDecl->getLocation();
13228   DeclarationName Name
13229     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13230   DeclarationNameInfo NameInfo(Name, ClassLoc);
13231   CXXDestructorDecl *Destructor =
13232       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13233                                 QualType(), nullptr, /*isInline=*/true,
13234                                 /*isImplicitlyDeclared=*/true,
13235                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13236   Destructor->setAccess(AS_public);
13237   Destructor->setDefaulted();
13238 
13239   if (getLangOpts().CUDA) {
13240     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13241                                             Destructor,
13242                                             /* ConstRHS */ false,
13243                                             /* Diagnose */ false);
13244   }
13245 
13246   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13247 
13248   // We don't need to use SpecialMemberIsTrivial here; triviality for
13249   // destructors is easy to compute.
13250   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13251   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13252                                 ClassDecl->hasTrivialDestructorForCall());
13253 
13254   // Note that we have declared this destructor.
13255   ++getASTContext().NumImplicitDestructorsDeclared;
13256 
13257   Scope *S = getScopeForContext(ClassDecl);
13258   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13259 
13260   // We can't check whether an implicit destructor is deleted before we complete
13261   // the definition of the class, because its validity depends on the alignment
13262   // of the class. We'll check this from ActOnFields once the class is complete.
13263   if (ClassDecl->isCompleteDefinition() &&
13264       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13265     SetDeclDeleted(Destructor, ClassLoc);
13266 
13267   // Introduce this destructor into its scope.
13268   if (S)
13269     PushOnScopeChains(Destructor, S, false);
13270   ClassDecl->addDecl(Destructor);
13271 
13272   return Destructor;
13273 }
13274 
13275 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13276                                     CXXDestructorDecl *Destructor) {
13277   assert((Destructor->isDefaulted() &&
13278           !Destructor->doesThisDeclarationHaveABody() &&
13279           !Destructor->isDeleted()) &&
13280          "DefineImplicitDestructor - call it for implicit default dtor");
13281   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13282     return;
13283 
13284   CXXRecordDecl *ClassDecl = Destructor->getParent();
13285   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13286 
13287   SynthesizedFunctionScope Scope(*this, Destructor);
13288 
13289   // The exception specification is needed because we are defining the
13290   // function.
13291   ResolveExceptionSpec(CurrentLocation,
13292                        Destructor->getType()->castAs<FunctionProtoType>());
13293   MarkVTableUsed(CurrentLocation, ClassDecl);
13294 
13295   // Add a context note for diagnostics produced after this point.
13296   Scope.addContextNote(CurrentLocation);
13297 
13298   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13299                                          Destructor->getParent());
13300 
13301   if (CheckDestructor(Destructor)) {
13302     Destructor->setInvalidDecl();
13303     return;
13304   }
13305 
13306   SourceLocation Loc = Destructor->getEndLoc().isValid()
13307                            ? Destructor->getEndLoc()
13308                            : Destructor->getLocation();
13309   Destructor->setBody(new (Context) CompoundStmt(Loc));
13310   Destructor->markUsed(Context);
13311 
13312   if (ASTMutationListener *L = getASTMutationListener()) {
13313     L->CompletedImplicitDefinition(Destructor);
13314   }
13315 }
13316 
13317 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13318                                           CXXDestructorDecl *Destructor) {
13319   if (Destructor->isInvalidDecl())
13320     return;
13321 
13322   CXXRecordDecl *ClassDecl = Destructor->getParent();
13323   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13324          "implicit complete dtors unneeded outside MS ABI");
13325   assert(ClassDecl->getNumVBases() > 0 &&
13326          "complete dtor only exists for classes with vbases");
13327 
13328   SynthesizedFunctionScope Scope(*this, Destructor);
13329 
13330   // Add a context note for diagnostics produced after this point.
13331   Scope.addContextNote(CurrentLocation);
13332 
13333   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13334 }
13335 
13336 /// Perform any semantic analysis which needs to be delayed until all
13337 /// pending class member declarations have been parsed.
13338 void Sema::ActOnFinishCXXMemberDecls() {
13339   // If the context is an invalid C++ class, just suppress these checks.
13340   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13341     if (Record->isInvalidDecl()) {
13342       DelayedOverridingExceptionSpecChecks.clear();
13343       DelayedEquivalentExceptionSpecChecks.clear();
13344       return;
13345     }
13346     checkForMultipleExportedDefaultConstructors(*this, Record);
13347   }
13348 }
13349 
13350 void Sema::ActOnFinishCXXNonNestedClass() {
13351   referenceDLLExportedClassMethods();
13352 
13353   if (!DelayedDllExportMemberFunctions.empty()) {
13354     SmallVector<CXXMethodDecl*, 4> WorkList;
13355     std::swap(DelayedDllExportMemberFunctions, WorkList);
13356     for (CXXMethodDecl *M : WorkList) {
13357       DefineDefaultedFunction(*this, M, M->getLocation());
13358 
13359       // Pass the method to the consumer to get emitted. This is not necessary
13360       // for explicit instantiation definitions, as they will get emitted
13361       // anyway.
13362       if (M->getParent()->getTemplateSpecializationKind() !=
13363           TSK_ExplicitInstantiationDefinition)
13364         ActOnFinishInlineFunctionDef(M);
13365     }
13366   }
13367 }
13368 
13369 void Sema::referenceDLLExportedClassMethods() {
13370   if (!DelayedDllExportClasses.empty()) {
13371     // Calling ReferenceDllExportedMembers might cause the current function to
13372     // be called again, so use a local copy of DelayedDllExportClasses.
13373     SmallVector<CXXRecordDecl *, 4> WorkList;
13374     std::swap(DelayedDllExportClasses, WorkList);
13375     for (CXXRecordDecl *Class : WorkList)
13376       ReferenceDllExportedMembers(*this, Class);
13377   }
13378 }
13379 
13380 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13381   assert(getLangOpts().CPlusPlus11 &&
13382          "adjusting dtor exception specs was introduced in c++11");
13383 
13384   if (Destructor->isDependentContext())
13385     return;
13386 
13387   // C++11 [class.dtor]p3:
13388   //   A declaration of a destructor that does not have an exception-
13389   //   specification is implicitly considered to have the same exception-
13390   //   specification as an implicit declaration.
13391   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13392   if (DtorType->hasExceptionSpec())
13393     return;
13394 
13395   // Replace the destructor's type, building off the existing one. Fortunately,
13396   // the only thing of interest in the destructor type is its extended info.
13397   // The return and arguments are fixed.
13398   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13399   EPI.ExceptionSpec.Type = EST_Unevaluated;
13400   EPI.ExceptionSpec.SourceDecl = Destructor;
13401   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13402 
13403   // FIXME: If the destructor has a body that could throw, and the newly created
13404   // spec doesn't allow exceptions, we should emit a warning, because this
13405   // change in behavior can break conforming C++03 programs at runtime.
13406   // However, we don't have a body or an exception specification yet, so it
13407   // needs to be done somewhere else.
13408 }
13409 
13410 namespace {
13411 /// An abstract base class for all helper classes used in building the
13412 //  copy/move operators. These classes serve as factory functions and help us
13413 //  avoid using the same Expr* in the AST twice.
13414 class ExprBuilder {
13415   ExprBuilder(const ExprBuilder&) = delete;
13416   ExprBuilder &operator=(const ExprBuilder&) = delete;
13417 
13418 protected:
13419   static Expr *assertNotNull(Expr *E) {
13420     assert(E && "Expression construction must not fail.");
13421     return E;
13422   }
13423 
13424 public:
13425   ExprBuilder() {}
13426   virtual ~ExprBuilder() {}
13427 
13428   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13429 };
13430 
13431 class RefBuilder: public ExprBuilder {
13432   VarDecl *Var;
13433   QualType VarType;
13434 
13435 public:
13436   Expr *build(Sema &S, SourceLocation Loc) const override {
13437     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13438   }
13439 
13440   RefBuilder(VarDecl *Var, QualType VarType)
13441       : Var(Var), VarType(VarType) {}
13442 };
13443 
13444 class ThisBuilder: public ExprBuilder {
13445 public:
13446   Expr *build(Sema &S, SourceLocation Loc) const override {
13447     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13448   }
13449 };
13450 
13451 class CastBuilder: public ExprBuilder {
13452   const ExprBuilder &Builder;
13453   QualType Type;
13454   ExprValueKind Kind;
13455   const CXXCastPath &Path;
13456 
13457 public:
13458   Expr *build(Sema &S, SourceLocation Loc) const override {
13459     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13460                                              CK_UncheckedDerivedToBase, Kind,
13461                                              &Path).get());
13462   }
13463 
13464   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13465               const CXXCastPath &Path)
13466       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13467 };
13468 
13469 class DerefBuilder: public ExprBuilder {
13470   const ExprBuilder &Builder;
13471 
13472 public:
13473   Expr *build(Sema &S, SourceLocation Loc) const override {
13474     return assertNotNull(
13475         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13476   }
13477 
13478   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13479 };
13480 
13481 class MemberBuilder: public ExprBuilder {
13482   const ExprBuilder &Builder;
13483   QualType Type;
13484   CXXScopeSpec SS;
13485   bool IsArrow;
13486   LookupResult &MemberLookup;
13487 
13488 public:
13489   Expr *build(Sema &S, SourceLocation Loc) const override {
13490     return assertNotNull(S.BuildMemberReferenceExpr(
13491         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13492         nullptr, MemberLookup, nullptr, nullptr).get());
13493   }
13494 
13495   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13496                 LookupResult &MemberLookup)
13497       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13498         MemberLookup(MemberLookup) {}
13499 };
13500 
13501 class MoveCastBuilder: public ExprBuilder {
13502   const ExprBuilder &Builder;
13503 
13504 public:
13505   Expr *build(Sema &S, SourceLocation Loc) const override {
13506     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13507   }
13508 
13509   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13510 };
13511 
13512 class LvalueConvBuilder: public ExprBuilder {
13513   const ExprBuilder &Builder;
13514 
13515 public:
13516   Expr *build(Sema &S, SourceLocation Loc) const override {
13517     return assertNotNull(
13518         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13519   }
13520 
13521   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13522 };
13523 
13524 class SubscriptBuilder: public ExprBuilder {
13525   const ExprBuilder &Base;
13526   const ExprBuilder &Index;
13527 
13528 public:
13529   Expr *build(Sema &S, SourceLocation Loc) const override {
13530     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13531         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13532   }
13533 
13534   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13535       : Base(Base), Index(Index) {}
13536 };
13537 
13538 } // end anonymous namespace
13539 
13540 /// When generating a defaulted copy or move assignment operator, if a field
13541 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13542 /// do so. This optimization only applies for arrays of scalars, and for arrays
13543 /// of class type where the selected copy/move-assignment operator is trivial.
13544 static StmtResult
13545 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13546                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13547   // Compute the size of the memory buffer to be copied.
13548   QualType SizeType = S.Context.getSizeType();
13549   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13550                    S.Context.getTypeSizeInChars(T).getQuantity());
13551 
13552   // Take the address of the field references for "from" and "to". We
13553   // directly construct UnaryOperators here because semantic analysis
13554   // does not permit us to take the address of an xvalue.
13555   Expr *From = FromB.build(S, Loc);
13556   From = UnaryOperator::Create(
13557       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13558       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13559   Expr *To = ToB.build(S, Loc);
13560   To = UnaryOperator::Create(
13561       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13562       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13563 
13564   const Type *E = T->getBaseElementTypeUnsafe();
13565   bool NeedsCollectableMemCpy =
13566       E->isRecordType() &&
13567       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13568 
13569   // Create a reference to the __builtin_objc_memmove_collectable function
13570   StringRef MemCpyName = NeedsCollectableMemCpy ?
13571     "__builtin_objc_memmove_collectable" :
13572     "__builtin_memcpy";
13573   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13574                  Sema::LookupOrdinaryName);
13575   S.LookupName(R, S.TUScope, true);
13576 
13577   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13578   if (!MemCpy)
13579     // Something went horribly wrong earlier, and we will have complained
13580     // about it.
13581     return StmtError();
13582 
13583   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13584                                             VK_RValue, Loc, nullptr);
13585   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13586 
13587   Expr *CallArgs[] = {
13588     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13589   };
13590   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13591                                     Loc, CallArgs, Loc);
13592 
13593   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13594   return Call.getAs<Stmt>();
13595 }
13596 
13597 /// Builds a statement that copies/moves the given entity from \p From to
13598 /// \c To.
13599 ///
13600 /// This routine is used to copy/move the members of a class with an
13601 /// implicitly-declared copy/move assignment operator. When the entities being
13602 /// copied are arrays, this routine builds for loops to copy them.
13603 ///
13604 /// \param S The Sema object used for type-checking.
13605 ///
13606 /// \param Loc The location where the implicit copy/move is being generated.
13607 ///
13608 /// \param T The type of the expressions being copied/moved. Both expressions
13609 /// must have this type.
13610 ///
13611 /// \param To The expression we are copying/moving to.
13612 ///
13613 /// \param From The expression we are copying/moving from.
13614 ///
13615 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13616 /// Otherwise, it's a non-static member subobject.
13617 ///
13618 /// \param Copying Whether we're copying or moving.
13619 ///
13620 /// \param Depth Internal parameter recording the depth of the recursion.
13621 ///
13622 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13623 /// if a memcpy should be used instead.
13624 static StmtResult
13625 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13626                                  const ExprBuilder &To, const ExprBuilder &From,
13627                                  bool CopyingBaseSubobject, bool Copying,
13628                                  unsigned Depth = 0) {
13629   // C++11 [class.copy]p28:
13630   //   Each subobject is assigned in the manner appropriate to its type:
13631   //
13632   //     - if the subobject is of class type, as if by a call to operator= with
13633   //       the subobject as the object expression and the corresponding
13634   //       subobject of x as a single function argument (as if by explicit
13635   //       qualification; that is, ignoring any possible virtual overriding
13636   //       functions in more derived classes);
13637   //
13638   // C++03 [class.copy]p13:
13639   //     - if the subobject is of class type, the copy assignment operator for
13640   //       the class is used (as if by explicit qualification; that is,
13641   //       ignoring any possible virtual overriding functions in more derived
13642   //       classes);
13643   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13644     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13645 
13646     // Look for operator=.
13647     DeclarationName Name
13648       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13649     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13650     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13651 
13652     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13653     // operator.
13654     if (!S.getLangOpts().CPlusPlus11) {
13655       LookupResult::Filter F = OpLookup.makeFilter();
13656       while (F.hasNext()) {
13657         NamedDecl *D = F.next();
13658         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13659           if (Method->isCopyAssignmentOperator() ||
13660               (!Copying && Method->isMoveAssignmentOperator()))
13661             continue;
13662 
13663         F.erase();
13664       }
13665       F.done();
13666     }
13667 
13668     // Suppress the protected check (C++ [class.protected]) for each of the
13669     // assignment operators we found. This strange dance is required when
13670     // we're assigning via a base classes's copy-assignment operator. To
13671     // ensure that we're getting the right base class subobject (without
13672     // ambiguities), we need to cast "this" to that subobject type; to
13673     // ensure that we don't go through the virtual call mechanism, we need
13674     // to qualify the operator= name with the base class (see below). However,
13675     // this means that if the base class has a protected copy assignment
13676     // operator, the protected member access check will fail. So, we
13677     // rewrite "protected" access to "public" access in this case, since we
13678     // know by construction that we're calling from a derived class.
13679     if (CopyingBaseSubobject) {
13680       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13681            L != LEnd; ++L) {
13682         if (L.getAccess() == AS_protected)
13683           L.setAccess(AS_public);
13684       }
13685     }
13686 
13687     // Create the nested-name-specifier that will be used to qualify the
13688     // reference to operator=; this is required to suppress the virtual
13689     // call mechanism.
13690     CXXScopeSpec SS;
13691     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13692     SS.MakeTrivial(S.Context,
13693                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13694                                                CanonicalT),
13695                    Loc);
13696 
13697     // Create the reference to operator=.
13698     ExprResult OpEqualRef
13699       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13700                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13701                                    /*FirstQualifierInScope=*/nullptr,
13702                                    OpLookup,
13703                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13704                                    /*SuppressQualifierCheck=*/true);
13705     if (OpEqualRef.isInvalid())
13706       return StmtError();
13707 
13708     // Build the call to the assignment operator.
13709 
13710     Expr *FromInst = From.build(S, Loc);
13711     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13712                                                   OpEqualRef.getAs<Expr>(),
13713                                                   Loc, FromInst, Loc);
13714     if (Call.isInvalid())
13715       return StmtError();
13716 
13717     // If we built a call to a trivial 'operator=' while copying an array,
13718     // bail out. We'll replace the whole shebang with a memcpy.
13719     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13720     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13721       return StmtResult((Stmt*)nullptr);
13722 
13723     // Convert to an expression-statement, and clean up any produced
13724     // temporaries.
13725     return S.ActOnExprStmt(Call);
13726   }
13727 
13728   //     - if the subobject is of scalar type, the built-in assignment
13729   //       operator is used.
13730   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13731   if (!ArrayTy) {
13732     ExprResult Assignment = S.CreateBuiltinBinOp(
13733         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13734     if (Assignment.isInvalid())
13735       return StmtError();
13736     return S.ActOnExprStmt(Assignment);
13737   }
13738 
13739   //     - if the subobject is an array, each element is assigned, in the
13740   //       manner appropriate to the element type;
13741 
13742   // Construct a loop over the array bounds, e.g.,
13743   //
13744   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13745   //
13746   // that will copy each of the array elements.
13747   QualType SizeType = S.Context.getSizeType();
13748 
13749   // Create the iteration variable.
13750   IdentifierInfo *IterationVarName = nullptr;
13751   {
13752     SmallString<8> Str;
13753     llvm::raw_svector_ostream OS(Str);
13754     OS << "__i" << Depth;
13755     IterationVarName = &S.Context.Idents.get(OS.str());
13756   }
13757   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13758                                           IterationVarName, SizeType,
13759                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13760                                           SC_None);
13761 
13762   // Initialize the iteration variable to zero.
13763   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13764   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13765 
13766   // Creates a reference to the iteration variable.
13767   RefBuilder IterationVarRef(IterationVar, SizeType);
13768   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13769 
13770   // Create the DeclStmt that holds the iteration variable.
13771   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13772 
13773   // Subscript the "from" and "to" expressions with the iteration variable.
13774   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13775   MoveCastBuilder FromIndexMove(FromIndexCopy);
13776   const ExprBuilder *FromIndex;
13777   if (Copying)
13778     FromIndex = &FromIndexCopy;
13779   else
13780     FromIndex = &FromIndexMove;
13781 
13782   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13783 
13784   // Build the copy/move for an individual element of the array.
13785   StmtResult Copy =
13786     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13787                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13788                                      Copying, Depth + 1);
13789   // Bail out if copying fails or if we determined that we should use memcpy.
13790   if (Copy.isInvalid() || !Copy.get())
13791     return Copy;
13792 
13793   // Create the comparison against the array bound.
13794   llvm::APInt Upper
13795     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13796   Expr *Comparison = BinaryOperator::Create(
13797       S.Context, IterationVarRefRVal.build(S, Loc),
13798       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13799       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13800 
13801   // Create the pre-increment of the iteration variable. We can determine
13802   // whether the increment will overflow based on the value of the array
13803   // bound.
13804   Expr *Increment = UnaryOperator::Create(
13805       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13806       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13807 
13808   // Construct the loop that copies all elements of this array.
13809   return S.ActOnForStmt(
13810       Loc, Loc, InitStmt,
13811       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13812       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13813 }
13814 
13815 static StmtResult
13816 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13817                       const ExprBuilder &To, const ExprBuilder &From,
13818                       bool CopyingBaseSubobject, bool Copying) {
13819   // Maybe we should use a memcpy?
13820   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13821       T.isTriviallyCopyableType(S.Context))
13822     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13823 
13824   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13825                                                      CopyingBaseSubobject,
13826                                                      Copying, 0));
13827 
13828   // If we ended up picking a trivial assignment operator for an array of a
13829   // non-trivially-copyable class type, just emit a memcpy.
13830   if (!Result.isInvalid() && !Result.get())
13831     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13832 
13833   return Result;
13834 }
13835 
13836 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13837   // Note: The following rules are largely analoguous to the copy
13838   // constructor rules. Note that virtual bases are not taken into account
13839   // for determining the argument type of the operator. Note also that
13840   // operators taking an object instead of a reference are allowed.
13841   assert(ClassDecl->needsImplicitCopyAssignment());
13842 
13843   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13844   if (DSM.isAlreadyBeingDeclared())
13845     return nullptr;
13846 
13847   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13848   LangAS AS = getDefaultCXXMethodAddrSpace();
13849   if (AS != LangAS::Default)
13850     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13851   QualType RetType = Context.getLValueReferenceType(ArgType);
13852   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13853   if (Const)
13854     ArgType = ArgType.withConst();
13855 
13856   ArgType = Context.getLValueReferenceType(ArgType);
13857 
13858   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13859                                                      CXXCopyAssignment,
13860                                                      Const);
13861 
13862   //   An implicitly-declared copy assignment operator is an inline public
13863   //   member of its class.
13864   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13865   SourceLocation ClassLoc = ClassDecl->getLocation();
13866   DeclarationNameInfo NameInfo(Name, ClassLoc);
13867   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13868       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13869       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13870       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13871       SourceLocation());
13872   CopyAssignment->setAccess(AS_public);
13873   CopyAssignment->setDefaulted();
13874   CopyAssignment->setImplicit();
13875 
13876   if (getLangOpts().CUDA) {
13877     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13878                                             CopyAssignment,
13879                                             /* ConstRHS */ Const,
13880                                             /* Diagnose */ false);
13881   }
13882 
13883   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13884 
13885   // Add the parameter to the operator.
13886   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13887                                                ClassLoc, ClassLoc,
13888                                                /*Id=*/nullptr, ArgType,
13889                                                /*TInfo=*/nullptr, SC_None,
13890                                                nullptr);
13891   CopyAssignment->setParams(FromParam);
13892 
13893   CopyAssignment->setTrivial(
13894     ClassDecl->needsOverloadResolutionForCopyAssignment()
13895       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13896       : ClassDecl->hasTrivialCopyAssignment());
13897 
13898   // Note that we have added this copy-assignment operator.
13899   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13900 
13901   Scope *S = getScopeForContext(ClassDecl);
13902   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13903 
13904   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13905     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13906     SetDeclDeleted(CopyAssignment, ClassLoc);
13907   }
13908 
13909   if (S)
13910     PushOnScopeChains(CopyAssignment, S, false);
13911   ClassDecl->addDecl(CopyAssignment);
13912 
13913   return CopyAssignment;
13914 }
13915 
13916 /// Diagnose an implicit copy operation for a class which is odr-used, but
13917 /// which is deprecated because the class has a user-declared copy constructor,
13918 /// copy assignment operator, or destructor.
13919 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13920   assert(CopyOp->isImplicit());
13921 
13922   CXXRecordDecl *RD = CopyOp->getParent();
13923   CXXMethodDecl *UserDeclaredOperation = nullptr;
13924 
13925   // In Microsoft mode, assignment operations don't affect constructors and
13926   // vice versa.
13927   if (RD->hasUserDeclaredDestructor()) {
13928     UserDeclaredOperation = RD->getDestructor();
13929   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13930              RD->hasUserDeclaredCopyConstructor() &&
13931              !S.getLangOpts().MSVCCompat) {
13932     // Find any user-declared copy constructor.
13933     for (auto *I : RD->ctors()) {
13934       if (I->isCopyConstructor()) {
13935         UserDeclaredOperation = I;
13936         break;
13937       }
13938     }
13939     assert(UserDeclaredOperation);
13940   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13941              RD->hasUserDeclaredCopyAssignment() &&
13942              !S.getLangOpts().MSVCCompat) {
13943     // Find any user-declared move assignment operator.
13944     for (auto *I : RD->methods()) {
13945       if (I->isCopyAssignmentOperator()) {
13946         UserDeclaredOperation = I;
13947         break;
13948       }
13949     }
13950     assert(UserDeclaredOperation);
13951   }
13952 
13953   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13954     S.Diag(UserDeclaredOperation->getLocation(),
13955            isa<CXXDestructorDecl>(UserDeclaredOperation)
13956                ? diag::warn_deprecated_copy_dtor_operation
13957                : diag::warn_deprecated_copy_operation)
13958         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13959   }
13960 }
13961 
13962 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13963                                         CXXMethodDecl *CopyAssignOperator) {
13964   assert((CopyAssignOperator->isDefaulted() &&
13965           CopyAssignOperator->isOverloadedOperator() &&
13966           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13967           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13968           !CopyAssignOperator->isDeleted()) &&
13969          "DefineImplicitCopyAssignment called for wrong function");
13970   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13971     return;
13972 
13973   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13974   if (ClassDecl->isInvalidDecl()) {
13975     CopyAssignOperator->setInvalidDecl();
13976     return;
13977   }
13978 
13979   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13980 
13981   // The exception specification is needed because we are defining the
13982   // function.
13983   ResolveExceptionSpec(CurrentLocation,
13984                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13985 
13986   // Add a context note for diagnostics produced after this point.
13987   Scope.addContextNote(CurrentLocation);
13988 
13989   // C++11 [class.copy]p18:
13990   //   The [definition of an implicitly declared copy assignment operator] is
13991   //   deprecated if the class has a user-declared copy constructor or a
13992   //   user-declared destructor.
13993   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13994     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13995 
13996   // C++0x [class.copy]p30:
13997   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13998   //   for a non-union class X performs memberwise copy assignment of its
13999   //   subobjects. The direct base classes of X are assigned first, in the
14000   //   order of their declaration in the base-specifier-list, and then the
14001   //   immediate non-static data members of X are assigned, in the order in
14002   //   which they were declared in the class definition.
14003 
14004   // The statements that form the synthesized function body.
14005   SmallVector<Stmt*, 8> Statements;
14006 
14007   // The parameter for the "other" object, which we are copying from.
14008   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14009   Qualifiers OtherQuals = Other->getType().getQualifiers();
14010   QualType OtherRefType = Other->getType();
14011   if (const LValueReferenceType *OtherRef
14012                                 = OtherRefType->getAs<LValueReferenceType>()) {
14013     OtherRefType = OtherRef->getPointeeType();
14014     OtherQuals = OtherRefType.getQualifiers();
14015   }
14016 
14017   // Our location for everything implicitly-generated.
14018   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14019                            ? CopyAssignOperator->getEndLoc()
14020                            : CopyAssignOperator->getLocation();
14021 
14022   // Builds a DeclRefExpr for the "other" object.
14023   RefBuilder OtherRef(Other, OtherRefType);
14024 
14025   // Builds the "this" pointer.
14026   ThisBuilder This;
14027 
14028   // Assign base classes.
14029   bool Invalid = false;
14030   for (auto &Base : ClassDecl->bases()) {
14031     // Form the assignment:
14032     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14033     QualType BaseType = Base.getType().getUnqualifiedType();
14034     if (!BaseType->isRecordType()) {
14035       Invalid = true;
14036       continue;
14037     }
14038 
14039     CXXCastPath BasePath;
14040     BasePath.push_back(&Base);
14041 
14042     // Construct the "from" expression, which is an implicit cast to the
14043     // appropriately-qualified base type.
14044     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14045                      VK_LValue, BasePath);
14046 
14047     // Dereference "this".
14048     DerefBuilder DerefThis(This);
14049     CastBuilder To(DerefThis,
14050                    Context.getQualifiedType(
14051                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14052                    VK_LValue, BasePath);
14053 
14054     // Build the copy.
14055     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14056                                             To, From,
14057                                             /*CopyingBaseSubobject=*/true,
14058                                             /*Copying=*/true);
14059     if (Copy.isInvalid()) {
14060       CopyAssignOperator->setInvalidDecl();
14061       return;
14062     }
14063 
14064     // Success! Record the copy.
14065     Statements.push_back(Copy.getAs<Expr>());
14066   }
14067 
14068   // Assign non-static members.
14069   for (auto *Field : ClassDecl->fields()) {
14070     // FIXME: We should form some kind of AST representation for the implied
14071     // memcpy in a union copy operation.
14072     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14073       continue;
14074 
14075     if (Field->isInvalidDecl()) {
14076       Invalid = true;
14077       continue;
14078     }
14079 
14080     // Check for members of reference type; we can't copy those.
14081     if (Field->getType()->isReferenceType()) {
14082       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14083         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14084       Diag(Field->getLocation(), diag::note_declared_at);
14085       Invalid = true;
14086       continue;
14087     }
14088 
14089     // Check for members of const-qualified, non-class type.
14090     QualType BaseType = Context.getBaseElementType(Field->getType());
14091     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14092       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14093         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14094       Diag(Field->getLocation(), diag::note_declared_at);
14095       Invalid = true;
14096       continue;
14097     }
14098 
14099     // Suppress assigning zero-width bitfields.
14100     if (Field->isZeroLengthBitField(Context))
14101       continue;
14102 
14103     QualType FieldType = Field->getType().getNonReferenceType();
14104     if (FieldType->isIncompleteArrayType()) {
14105       assert(ClassDecl->hasFlexibleArrayMember() &&
14106              "Incomplete array type is not valid");
14107       continue;
14108     }
14109 
14110     // Build references to the field in the object we're copying from and to.
14111     CXXScopeSpec SS; // Intentionally empty
14112     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14113                               LookupMemberName);
14114     MemberLookup.addDecl(Field);
14115     MemberLookup.resolveKind();
14116 
14117     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14118 
14119     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14120 
14121     // Build the copy of this field.
14122     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14123                                             To, From,
14124                                             /*CopyingBaseSubobject=*/false,
14125                                             /*Copying=*/true);
14126     if (Copy.isInvalid()) {
14127       CopyAssignOperator->setInvalidDecl();
14128       return;
14129     }
14130 
14131     // Success! Record the copy.
14132     Statements.push_back(Copy.getAs<Stmt>());
14133   }
14134 
14135   if (!Invalid) {
14136     // Add a "return *this;"
14137     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14138 
14139     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14140     if (Return.isInvalid())
14141       Invalid = true;
14142     else
14143       Statements.push_back(Return.getAs<Stmt>());
14144   }
14145 
14146   if (Invalid) {
14147     CopyAssignOperator->setInvalidDecl();
14148     return;
14149   }
14150 
14151   StmtResult Body;
14152   {
14153     CompoundScopeRAII CompoundScope(*this);
14154     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14155                              /*isStmtExpr=*/false);
14156     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14157   }
14158   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14159   CopyAssignOperator->markUsed(Context);
14160 
14161   if (ASTMutationListener *L = getASTMutationListener()) {
14162     L->CompletedImplicitDefinition(CopyAssignOperator);
14163   }
14164 }
14165 
14166 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14167   assert(ClassDecl->needsImplicitMoveAssignment());
14168 
14169   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14170   if (DSM.isAlreadyBeingDeclared())
14171     return nullptr;
14172 
14173   // Note: The following rules are largely analoguous to the move
14174   // constructor rules.
14175 
14176   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14177   LangAS AS = getDefaultCXXMethodAddrSpace();
14178   if (AS != LangAS::Default)
14179     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14180   QualType RetType = Context.getLValueReferenceType(ArgType);
14181   ArgType = Context.getRValueReferenceType(ArgType);
14182 
14183   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14184                                                      CXXMoveAssignment,
14185                                                      false);
14186 
14187   //   An implicitly-declared move assignment operator is an inline public
14188   //   member of its class.
14189   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14190   SourceLocation ClassLoc = ClassDecl->getLocation();
14191   DeclarationNameInfo NameInfo(Name, ClassLoc);
14192   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14193       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14194       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14195       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14196       SourceLocation());
14197   MoveAssignment->setAccess(AS_public);
14198   MoveAssignment->setDefaulted();
14199   MoveAssignment->setImplicit();
14200 
14201   if (getLangOpts().CUDA) {
14202     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14203                                             MoveAssignment,
14204                                             /* ConstRHS */ false,
14205                                             /* Diagnose */ false);
14206   }
14207 
14208   // Build an exception specification pointing back at this member.
14209   FunctionProtoType::ExtProtoInfo EPI =
14210       getImplicitMethodEPI(*this, MoveAssignment);
14211   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14212 
14213   // Add the parameter to the operator.
14214   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14215                                                ClassLoc, ClassLoc,
14216                                                /*Id=*/nullptr, ArgType,
14217                                                /*TInfo=*/nullptr, SC_None,
14218                                                nullptr);
14219   MoveAssignment->setParams(FromParam);
14220 
14221   MoveAssignment->setTrivial(
14222     ClassDecl->needsOverloadResolutionForMoveAssignment()
14223       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14224       : ClassDecl->hasTrivialMoveAssignment());
14225 
14226   // Note that we have added this copy-assignment operator.
14227   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14228 
14229   Scope *S = getScopeForContext(ClassDecl);
14230   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14231 
14232   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14233     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14234     SetDeclDeleted(MoveAssignment, ClassLoc);
14235   }
14236 
14237   if (S)
14238     PushOnScopeChains(MoveAssignment, S, false);
14239   ClassDecl->addDecl(MoveAssignment);
14240 
14241   return MoveAssignment;
14242 }
14243 
14244 /// Check if we're implicitly defining a move assignment operator for a class
14245 /// with virtual bases. Such a move assignment might move-assign the virtual
14246 /// base multiple times.
14247 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14248                                                SourceLocation CurrentLocation) {
14249   assert(!Class->isDependentContext() && "should not define dependent move");
14250 
14251   // Only a virtual base could get implicitly move-assigned multiple times.
14252   // Only a non-trivial move assignment can observe this. We only want to
14253   // diagnose if we implicitly define an assignment operator that assigns
14254   // two base classes, both of which move-assign the same virtual base.
14255   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14256       Class->getNumBases() < 2)
14257     return;
14258 
14259   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14260   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14261   VBaseMap VBases;
14262 
14263   for (auto &BI : Class->bases()) {
14264     Worklist.push_back(&BI);
14265     while (!Worklist.empty()) {
14266       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14267       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14268 
14269       // If the base has no non-trivial move assignment operators,
14270       // we don't care about moves from it.
14271       if (!Base->hasNonTrivialMoveAssignment())
14272         continue;
14273 
14274       // If there's nothing virtual here, skip it.
14275       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14276         continue;
14277 
14278       // If we're not actually going to call a move assignment for this base,
14279       // or the selected move assignment is trivial, skip it.
14280       Sema::SpecialMemberOverloadResult SMOR =
14281         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14282                               /*ConstArg*/false, /*VolatileArg*/false,
14283                               /*RValueThis*/true, /*ConstThis*/false,
14284                               /*VolatileThis*/false);
14285       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14286           !SMOR.getMethod()->isMoveAssignmentOperator())
14287         continue;
14288 
14289       if (BaseSpec->isVirtual()) {
14290         // We're going to move-assign this virtual base, and its move
14291         // assignment operator is not trivial. If this can happen for
14292         // multiple distinct direct bases of Class, diagnose it. (If it
14293         // only happens in one base, we'll diagnose it when synthesizing
14294         // that base class's move assignment operator.)
14295         CXXBaseSpecifier *&Existing =
14296             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14297                 .first->second;
14298         if (Existing && Existing != &BI) {
14299           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14300             << Class << Base;
14301           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14302               << (Base->getCanonicalDecl() ==
14303                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14304               << Base << Existing->getType() << Existing->getSourceRange();
14305           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14306               << (Base->getCanonicalDecl() ==
14307                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14308               << Base << BI.getType() << BaseSpec->getSourceRange();
14309 
14310           // Only diagnose each vbase once.
14311           Existing = nullptr;
14312         }
14313       } else {
14314         // Only walk over bases that have defaulted move assignment operators.
14315         // We assume that any user-provided move assignment operator handles
14316         // the multiple-moves-of-vbase case itself somehow.
14317         if (!SMOR.getMethod()->isDefaulted())
14318           continue;
14319 
14320         // We're going to move the base classes of Base. Add them to the list.
14321         for (auto &BI : Base->bases())
14322           Worklist.push_back(&BI);
14323       }
14324     }
14325   }
14326 }
14327 
14328 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14329                                         CXXMethodDecl *MoveAssignOperator) {
14330   assert((MoveAssignOperator->isDefaulted() &&
14331           MoveAssignOperator->isOverloadedOperator() &&
14332           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14333           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14334           !MoveAssignOperator->isDeleted()) &&
14335          "DefineImplicitMoveAssignment called for wrong function");
14336   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14337     return;
14338 
14339   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14340   if (ClassDecl->isInvalidDecl()) {
14341     MoveAssignOperator->setInvalidDecl();
14342     return;
14343   }
14344 
14345   // C++0x [class.copy]p28:
14346   //   The implicitly-defined or move assignment operator for a non-union class
14347   //   X performs memberwise move assignment of its subobjects. The direct base
14348   //   classes of X are assigned first, in the order of their declaration in the
14349   //   base-specifier-list, and then the immediate non-static data members of X
14350   //   are assigned, in the order in which they were declared in the class
14351   //   definition.
14352 
14353   // Issue a warning if our implicit move assignment operator will move
14354   // from a virtual base more than once.
14355   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14356 
14357   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14358 
14359   // The exception specification is needed because we are defining the
14360   // function.
14361   ResolveExceptionSpec(CurrentLocation,
14362                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14363 
14364   // Add a context note for diagnostics produced after this point.
14365   Scope.addContextNote(CurrentLocation);
14366 
14367   // The statements that form the synthesized function body.
14368   SmallVector<Stmt*, 8> Statements;
14369 
14370   // The parameter for the "other" object, which we are move from.
14371   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14372   QualType OtherRefType =
14373       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14374 
14375   // Our location for everything implicitly-generated.
14376   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14377                            ? MoveAssignOperator->getEndLoc()
14378                            : MoveAssignOperator->getLocation();
14379 
14380   // Builds a reference to the "other" object.
14381   RefBuilder OtherRef(Other, OtherRefType);
14382   // Cast to rvalue.
14383   MoveCastBuilder MoveOther(OtherRef);
14384 
14385   // Builds the "this" pointer.
14386   ThisBuilder This;
14387 
14388   // Assign base classes.
14389   bool Invalid = false;
14390   for (auto &Base : ClassDecl->bases()) {
14391     // C++11 [class.copy]p28:
14392     //   It is unspecified whether subobjects representing virtual base classes
14393     //   are assigned more than once by the implicitly-defined copy assignment
14394     //   operator.
14395     // FIXME: Do not assign to a vbase that will be assigned by some other base
14396     // class. For a move-assignment, this can result in the vbase being moved
14397     // multiple times.
14398 
14399     // Form the assignment:
14400     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14401     QualType BaseType = Base.getType().getUnqualifiedType();
14402     if (!BaseType->isRecordType()) {
14403       Invalid = true;
14404       continue;
14405     }
14406 
14407     CXXCastPath BasePath;
14408     BasePath.push_back(&Base);
14409 
14410     // Construct the "from" expression, which is an implicit cast to the
14411     // appropriately-qualified base type.
14412     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14413 
14414     // Dereference "this".
14415     DerefBuilder DerefThis(This);
14416 
14417     // Implicitly cast "this" to the appropriately-qualified base type.
14418     CastBuilder To(DerefThis,
14419                    Context.getQualifiedType(
14420                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14421                    VK_LValue, BasePath);
14422 
14423     // Build the move.
14424     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14425                                             To, From,
14426                                             /*CopyingBaseSubobject=*/true,
14427                                             /*Copying=*/false);
14428     if (Move.isInvalid()) {
14429       MoveAssignOperator->setInvalidDecl();
14430       return;
14431     }
14432 
14433     // Success! Record the move.
14434     Statements.push_back(Move.getAs<Expr>());
14435   }
14436 
14437   // Assign non-static members.
14438   for (auto *Field : ClassDecl->fields()) {
14439     // FIXME: We should form some kind of AST representation for the implied
14440     // memcpy in a union copy operation.
14441     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14442       continue;
14443 
14444     if (Field->isInvalidDecl()) {
14445       Invalid = true;
14446       continue;
14447     }
14448 
14449     // Check for members of reference type; we can't move those.
14450     if (Field->getType()->isReferenceType()) {
14451       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14452         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14453       Diag(Field->getLocation(), diag::note_declared_at);
14454       Invalid = true;
14455       continue;
14456     }
14457 
14458     // Check for members of const-qualified, non-class type.
14459     QualType BaseType = Context.getBaseElementType(Field->getType());
14460     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14461       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14462         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14463       Diag(Field->getLocation(), diag::note_declared_at);
14464       Invalid = true;
14465       continue;
14466     }
14467 
14468     // Suppress assigning zero-width bitfields.
14469     if (Field->isZeroLengthBitField(Context))
14470       continue;
14471 
14472     QualType FieldType = Field->getType().getNonReferenceType();
14473     if (FieldType->isIncompleteArrayType()) {
14474       assert(ClassDecl->hasFlexibleArrayMember() &&
14475              "Incomplete array type is not valid");
14476       continue;
14477     }
14478 
14479     // Build references to the field in the object we're copying from and to.
14480     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14481                               LookupMemberName);
14482     MemberLookup.addDecl(Field);
14483     MemberLookup.resolveKind();
14484     MemberBuilder From(MoveOther, OtherRefType,
14485                        /*IsArrow=*/false, MemberLookup);
14486     MemberBuilder To(This, getCurrentThisType(),
14487                      /*IsArrow=*/true, MemberLookup);
14488 
14489     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14490         "Member reference with rvalue base must be rvalue except for reference "
14491         "members, which aren't allowed for move assignment.");
14492 
14493     // Build the move of this field.
14494     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14495                                             To, From,
14496                                             /*CopyingBaseSubobject=*/false,
14497                                             /*Copying=*/false);
14498     if (Move.isInvalid()) {
14499       MoveAssignOperator->setInvalidDecl();
14500       return;
14501     }
14502 
14503     // Success! Record the copy.
14504     Statements.push_back(Move.getAs<Stmt>());
14505   }
14506 
14507   if (!Invalid) {
14508     // Add a "return *this;"
14509     ExprResult ThisObj =
14510         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14511 
14512     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14513     if (Return.isInvalid())
14514       Invalid = true;
14515     else
14516       Statements.push_back(Return.getAs<Stmt>());
14517   }
14518 
14519   if (Invalid) {
14520     MoveAssignOperator->setInvalidDecl();
14521     return;
14522   }
14523 
14524   StmtResult Body;
14525   {
14526     CompoundScopeRAII CompoundScope(*this);
14527     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14528                              /*isStmtExpr=*/false);
14529     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14530   }
14531   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14532   MoveAssignOperator->markUsed(Context);
14533 
14534   if (ASTMutationListener *L = getASTMutationListener()) {
14535     L->CompletedImplicitDefinition(MoveAssignOperator);
14536   }
14537 }
14538 
14539 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14540                                                     CXXRecordDecl *ClassDecl) {
14541   // C++ [class.copy]p4:
14542   //   If the class definition does not explicitly declare a copy
14543   //   constructor, one is declared implicitly.
14544   assert(ClassDecl->needsImplicitCopyConstructor());
14545 
14546   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14547   if (DSM.isAlreadyBeingDeclared())
14548     return nullptr;
14549 
14550   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14551   QualType ArgType = ClassType;
14552   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14553   if (Const)
14554     ArgType = ArgType.withConst();
14555 
14556   LangAS AS = getDefaultCXXMethodAddrSpace();
14557   if (AS != LangAS::Default)
14558     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14559 
14560   ArgType = Context.getLValueReferenceType(ArgType);
14561 
14562   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14563                                                      CXXCopyConstructor,
14564                                                      Const);
14565 
14566   DeclarationName Name
14567     = Context.DeclarationNames.getCXXConstructorName(
14568                                            Context.getCanonicalType(ClassType));
14569   SourceLocation ClassLoc = ClassDecl->getLocation();
14570   DeclarationNameInfo NameInfo(Name, ClassLoc);
14571 
14572   //   An implicitly-declared copy constructor is an inline public
14573   //   member of its class.
14574   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14575       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14576       ExplicitSpecifier(),
14577       /*isInline=*/true,
14578       /*isImplicitlyDeclared=*/true,
14579       Constexpr ? CSK_constexpr : CSK_unspecified);
14580   CopyConstructor->setAccess(AS_public);
14581   CopyConstructor->setDefaulted();
14582 
14583   if (getLangOpts().CUDA) {
14584     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14585                                             CopyConstructor,
14586                                             /* ConstRHS */ Const,
14587                                             /* Diagnose */ false);
14588   }
14589 
14590   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14591 
14592   // Add the parameter to the constructor.
14593   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14594                                                ClassLoc, ClassLoc,
14595                                                /*IdentifierInfo=*/nullptr,
14596                                                ArgType, /*TInfo=*/nullptr,
14597                                                SC_None, nullptr);
14598   CopyConstructor->setParams(FromParam);
14599 
14600   CopyConstructor->setTrivial(
14601       ClassDecl->needsOverloadResolutionForCopyConstructor()
14602           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14603           : ClassDecl->hasTrivialCopyConstructor());
14604 
14605   CopyConstructor->setTrivialForCall(
14606       ClassDecl->hasAttr<TrivialABIAttr>() ||
14607       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14608            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14609              TAH_ConsiderTrivialABI)
14610            : ClassDecl->hasTrivialCopyConstructorForCall()));
14611 
14612   // Note that we have declared this constructor.
14613   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14614 
14615   Scope *S = getScopeForContext(ClassDecl);
14616   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14617 
14618   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14619     ClassDecl->setImplicitCopyConstructorIsDeleted();
14620     SetDeclDeleted(CopyConstructor, ClassLoc);
14621   }
14622 
14623   if (S)
14624     PushOnScopeChains(CopyConstructor, S, false);
14625   ClassDecl->addDecl(CopyConstructor);
14626 
14627   return CopyConstructor;
14628 }
14629 
14630 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14631                                          CXXConstructorDecl *CopyConstructor) {
14632   assert((CopyConstructor->isDefaulted() &&
14633           CopyConstructor->isCopyConstructor() &&
14634           !CopyConstructor->doesThisDeclarationHaveABody() &&
14635           !CopyConstructor->isDeleted()) &&
14636          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14637   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14638     return;
14639 
14640   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14641   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14642 
14643   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14644 
14645   // The exception specification is needed because we are defining the
14646   // function.
14647   ResolveExceptionSpec(CurrentLocation,
14648                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14649   MarkVTableUsed(CurrentLocation, ClassDecl);
14650 
14651   // Add a context note for diagnostics produced after this point.
14652   Scope.addContextNote(CurrentLocation);
14653 
14654   // C++11 [class.copy]p7:
14655   //   The [definition of an implicitly declared copy constructor] is
14656   //   deprecated if the class has a user-declared copy assignment operator
14657   //   or a user-declared destructor.
14658   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14659     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14660 
14661   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14662     CopyConstructor->setInvalidDecl();
14663   }  else {
14664     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14665                              ? CopyConstructor->getEndLoc()
14666                              : CopyConstructor->getLocation();
14667     Sema::CompoundScopeRAII CompoundScope(*this);
14668     CopyConstructor->setBody(
14669         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14670     CopyConstructor->markUsed(Context);
14671   }
14672 
14673   if (ASTMutationListener *L = getASTMutationListener()) {
14674     L->CompletedImplicitDefinition(CopyConstructor);
14675   }
14676 }
14677 
14678 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14679                                                     CXXRecordDecl *ClassDecl) {
14680   assert(ClassDecl->needsImplicitMoveConstructor());
14681 
14682   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14683   if (DSM.isAlreadyBeingDeclared())
14684     return nullptr;
14685 
14686   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14687 
14688   QualType ArgType = ClassType;
14689   LangAS AS = getDefaultCXXMethodAddrSpace();
14690   if (AS != LangAS::Default)
14691     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14692   ArgType = Context.getRValueReferenceType(ArgType);
14693 
14694   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14695                                                      CXXMoveConstructor,
14696                                                      false);
14697 
14698   DeclarationName Name
14699     = Context.DeclarationNames.getCXXConstructorName(
14700                                            Context.getCanonicalType(ClassType));
14701   SourceLocation ClassLoc = ClassDecl->getLocation();
14702   DeclarationNameInfo NameInfo(Name, ClassLoc);
14703 
14704   // C++11 [class.copy]p11:
14705   //   An implicitly-declared copy/move constructor is an inline public
14706   //   member of its class.
14707   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14708       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14709       ExplicitSpecifier(),
14710       /*isInline=*/true,
14711       /*isImplicitlyDeclared=*/true,
14712       Constexpr ? CSK_constexpr : CSK_unspecified);
14713   MoveConstructor->setAccess(AS_public);
14714   MoveConstructor->setDefaulted();
14715 
14716   if (getLangOpts().CUDA) {
14717     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14718                                             MoveConstructor,
14719                                             /* ConstRHS */ false,
14720                                             /* Diagnose */ false);
14721   }
14722 
14723   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14724 
14725   // Add the parameter to the constructor.
14726   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14727                                                ClassLoc, ClassLoc,
14728                                                /*IdentifierInfo=*/nullptr,
14729                                                ArgType, /*TInfo=*/nullptr,
14730                                                SC_None, nullptr);
14731   MoveConstructor->setParams(FromParam);
14732 
14733   MoveConstructor->setTrivial(
14734       ClassDecl->needsOverloadResolutionForMoveConstructor()
14735           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14736           : ClassDecl->hasTrivialMoveConstructor());
14737 
14738   MoveConstructor->setTrivialForCall(
14739       ClassDecl->hasAttr<TrivialABIAttr>() ||
14740       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14741            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14742                                     TAH_ConsiderTrivialABI)
14743            : ClassDecl->hasTrivialMoveConstructorForCall()));
14744 
14745   // Note that we have declared this constructor.
14746   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14747 
14748   Scope *S = getScopeForContext(ClassDecl);
14749   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14750 
14751   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14752     ClassDecl->setImplicitMoveConstructorIsDeleted();
14753     SetDeclDeleted(MoveConstructor, ClassLoc);
14754   }
14755 
14756   if (S)
14757     PushOnScopeChains(MoveConstructor, S, false);
14758   ClassDecl->addDecl(MoveConstructor);
14759 
14760   return MoveConstructor;
14761 }
14762 
14763 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14764                                          CXXConstructorDecl *MoveConstructor) {
14765   assert((MoveConstructor->isDefaulted() &&
14766           MoveConstructor->isMoveConstructor() &&
14767           !MoveConstructor->doesThisDeclarationHaveABody() &&
14768           !MoveConstructor->isDeleted()) &&
14769          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14770   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14771     return;
14772 
14773   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14774   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14775 
14776   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14777 
14778   // The exception specification is needed because we are defining the
14779   // function.
14780   ResolveExceptionSpec(CurrentLocation,
14781                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14782   MarkVTableUsed(CurrentLocation, ClassDecl);
14783 
14784   // Add a context note for diagnostics produced after this point.
14785   Scope.addContextNote(CurrentLocation);
14786 
14787   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14788     MoveConstructor->setInvalidDecl();
14789   } else {
14790     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14791                              ? MoveConstructor->getEndLoc()
14792                              : MoveConstructor->getLocation();
14793     Sema::CompoundScopeRAII CompoundScope(*this);
14794     MoveConstructor->setBody(ActOnCompoundStmt(
14795         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14796     MoveConstructor->markUsed(Context);
14797   }
14798 
14799   if (ASTMutationListener *L = getASTMutationListener()) {
14800     L->CompletedImplicitDefinition(MoveConstructor);
14801   }
14802 }
14803 
14804 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14805   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14806 }
14807 
14808 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14809                             SourceLocation CurrentLocation,
14810                             CXXConversionDecl *Conv) {
14811   SynthesizedFunctionScope Scope(*this, Conv);
14812   assert(!Conv->getReturnType()->isUndeducedType());
14813 
14814   CXXRecordDecl *Lambda = Conv->getParent();
14815   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14816   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14817 
14818   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14819     CallOp = InstantiateFunctionDeclaration(
14820         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14821     if (!CallOp)
14822       return;
14823 
14824     Invoker = InstantiateFunctionDeclaration(
14825         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14826     if (!Invoker)
14827       return;
14828   }
14829 
14830   if (CallOp->isInvalidDecl())
14831     return;
14832 
14833   // Mark the call operator referenced (and add to pending instantiations
14834   // if necessary).
14835   // For both the conversion and static-invoker template specializations
14836   // we construct their body's in this function, so no need to add them
14837   // to the PendingInstantiations.
14838   MarkFunctionReferenced(CurrentLocation, CallOp);
14839 
14840   // Fill in the __invoke function with a dummy implementation. IR generation
14841   // will fill in the actual details. Update its type in case it contained
14842   // an 'auto'.
14843   Invoker->markUsed(Context);
14844   Invoker->setReferenced();
14845   Invoker->setType(Conv->getReturnType()->getPointeeType());
14846   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14847 
14848   // Construct the body of the conversion function { return __invoke; }.
14849   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14850                                        VK_LValue, Conv->getLocation());
14851   assert(FunctionRef && "Can't refer to __invoke function?");
14852   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14853   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14854                                      Conv->getLocation()));
14855   Conv->markUsed(Context);
14856   Conv->setReferenced();
14857 
14858   if (ASTMutationListener *L = getASTMutationListener()) {
14859     L->CompletedImplicitDefinition(Conv);
14860     L->CompletedImplicitDefinition(Invoker);
14861   }
14862 }
14863 
14864 
14865 
14866 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14867        SourceLocation CurrentLocation,
14868        CXXConversionDecl *Conv)
14869 {
14870   assert(!Conv->getParent()->isGenericLambda());
14871 
14872   SynthesizedFunctionScope Scope(*this, Conv);
14873 
14874   // Copy-initialize the lambda object as needed to capture it.
14875   Expr *This = ActOnCXXThis(CurrentLocation).get();
14876   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14877 
14878   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14879                                                         Conv->getLocation(),
14880                                                         Conv, DerefThis);
14881 
14882   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14883   // behavior.  Note that only the general conversion function does this
14884   // (since it's unusable otherwise); in the case where we inline the
14885   // block literal, it has block literal lifetime semantics.
14886   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14887     BuildBlock = ImplicitCastExpr::Create(
14888         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14889         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14890 
14891   if (BuildBlock.isInvalid()) {
14892     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14893     Conv->setInvalidDecl();
14894     return;
14895   }
14896 
14897   // Create the return statement that returns the block from the conversion
14898   // function.
14899   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14900   if (Return.isInvalid()) {
14901     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14902     Conv->setInvalidDecl();
14903     return;
14904   }
14905 
14906   // Set the body of the conversion function.
14907   Stmt *ReturnS = Return.get();
14908   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14909                                      Conv->getLocation()));
14910   Conv->markUsed(Context);
14911 
14912   // We're done; notify the mutation listener, if any.
14913   if (ASTMutationListener *L = getASTMutationListener()) {
14914     L->CompletedImplicitDefinition(Conv);
14915   }
14916 }
14917 
14918 /// Determine whether the given list arguments contains exactly one
14919 /// "real" (non-default) argument.
14920 static bool hasOneRealArgument(MultiExprArg Args) {
14921   switch (Args.size()) {
14922   case 0:
14923     return false;
14924 
14925   default:
14926     if (!Args[1]->isDefaultArgument())
14927       return false;
14928 
14929     LLVM_FALLTHROUGH;
14930   case 1:
14931     return !Args[0]->isDefaultArgument();
14932   }
14933 
14934   return false;
14935 }
14936 
14937 ExprResult
14938 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14939                             NamedDecl *FoundDecl,
14940                             CXXConstructorDecl *Constructor,
14941                             MultiExprArg ExprArgs,
14942                             bool HadMultipleCandidates,
14943                             bool IsListInitialization,
14944                             bool IsStdInitListInitialization,
14945                             bool RequiresZeroInit,
14946                             unsigned ConstructKind,
14947                             SourceRange ParenRange) {
14948   bool Elidable = false;
14949 
14950   // C++0x [class.copy]p34:
14951   //   When certain criteria are met, an implementation is allowed to
14952   //   omit the copy/move construction of a class object, even if the
14953   //   copy/move constructor and/or destructor for the object have
14954   //   side effects. [...]
14955   //     - when a temporary class object that has not been bound to a
14956   //       reference (12.2) would be copied/moved to a class object
14957   //       with the same cv-unqualified type, the copy/move operation
14958   //       can be omitted by constructing the temporary object
14959   //       directly into the target of the omitted copy/move
14960   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14961       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14962     Expr *SubExpr = ExprArgs[0];
14963     Elidable = SubExpr->isTemporaryObject(
14964         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14965   }
14966 
14967   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14968                                FoundDecl, Constructor,
14969                                Elidable, ExprArgs, HadMultipleCandidates,
14970                                IsListInitialization,
14971                                IsStdInitListInitialization, RequiresZeroInit,
14972                                ConstructKind, ParenRange);
14973 }
14974 
14975 ExprResult
14976 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14977                             NamedDecl *FoundDecl,
14978                             CXXConstructorDecl *Constructor,
14979                             bool Elidable,
14980                             MultiExprArg ExprArgs,
14981                             bool HadMultipleCandidates,
14982                             bool IsListInitialization,
14983                             bool IsStdInitListInitialization,
14984                             bool RequiresZeroInit,
14985                             unsigned ConstructKind,
14986                             SourceRange ParenRange) {
14987   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14988     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14989     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14990       return ExprError();
14991   }
14992 
14993   return BuildCXXConstructExpr(
14994       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14995       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14996       RequiresZeroInit, ConstructKind, ParenRange);
14997 }
14998 
14999 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15000 /// including handling of its default argument expressions.
15001 ExprResult
15002 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15003                             CXXConstructorDecl *Constructor,
15004                             bool Elidable,
15005                             MultiExprArg ExprArgs,
15006                             bool HadMultipleCandidates,
15007                             bool IsListInitialization,
15008                             bool IsStdInitListInitialization,
15009                             bool RequiresZeroInit,
15010                             unsigned ConstructKind,
15011                             SourceRange ParenRange) {
15012   assert(declaresSameEntity(
15013              Constructor->getParent(),
15014              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15015          "given constructor for wrong type");
15016   MarkFunctionReferenced(ConstructLoc, Constructor);
15017   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15018     return ExprError();
15019   if (getLangOpts().SYCLIsDevice &&
15020       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15021     return ExprError();
15022 
15023   return CheckForImmediateInvocation(
15024       CXXConstructExpr::Create(
15025           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15026           HadMultipleCandidates, IsListInitialization,
15027           IsStdInitListInitialization, RequiresZeroInit,
15028           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15029           ParenRange),
15030       Constructor);
15031 }
15032 
15033 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15034   assert(Field->hasInClassInitializer());
15035 
15036   // If we already have the in-class initializer nothing needs to be done.
15037   if (Field->getInClassInitializer())
15038     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15039 
15040   // If we might have already tried and failed to instantiate, don't try again.
15041   if (Field->isInvalidDecl())
15042     return ExprError();
15043 
15044   // Maybe we haven't instantiated the in-class initializer. Go check the
15045   // pattern FieldDecl to see if it has one.
15046   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15047 
15048   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15049     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15050     DeclContext::lookup_result Lookup =
15051         ClassPattern->lookup(Field->getDeclName());
15052 
15053     // Lookup can return at most two results: the pattern for the field, or the
15054     // injected class name of the parent record. No other member can have the
15055     // same name as the field.
15056     // In modules mode, lookup can return multiple results (coming from
15057     // different modules).
15058     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15059            "more than two lookup results for field name");
15060     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15061     if (!Pattern) {
15062       assert(isa<CXXRecordDecl>(Lookup[0]) &&
15063              "cannot have other non-field member with same name");
15064       for (auto L : Lookup)
15065         if (isa<FieldDecl>(L)) {
15066           Pattern = cast<FieldDecl>(L);
15067           break;
15068         }
15069       assert(Pattern && "We must have set the Pattern!");
15070     }
15071 
15072     if (!Pattern->hasInClassInitializer() ||
15073         InstantiateInClassInitializer(Loc, Field, Pattern,
15074                                       getTemplateInstantiationArgs(Field))) {
15075       // Don't diagnose this again.
15076       Field->setInvalidDecl();
15077       return ExprError();
15078     }
15079     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15080   }
15081 
15082   // DR1351:
15083   //   If the brace-or-equal-initializer of a non-static data member
15084   //   invokes a defaulted default constructor of its class or of an
15085   //   enclosing class in a potentially evaluated subexpression, the
15086   //   program is ill-formed.
15087   //
15088   // This resolution is unworkable: the exception specification of the
15089   // default constructor can be needed in an unevaluated context, in
15090   // particular, in the operand of a noexcept-expression, and we can be
15091   // unable to compute an exception specification for an enclosed class.
15092   //
15093   // Any attempt to resolve the exception specification of a defaulted default
15094   // constructor before the initializer is lexically complete will ultimately
15095   // come here at which point we can diagnose it.
15096   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15097   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15098       << OutermostClass << Field;
15099   Diag(Field->getEndLoc(),
15100        diag::note_default_member_initializer_not_yet_parsed);
15101   // Recover by marking the field invalid, unless we're in a SFINAE context.
15102   if (!isSFINAEContext())
15103     Field->setInvalidDecl();
15104   return ExprError();
15105 }
15106 
15107 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15108   if (VD->isInvalidDecl()) return;
15109   // If initializing the variable failed, don't also diagnose problems with
15110   // the desctructor, they're likely related.
15111   if (VD->getInit() && VD->getInit()->containsErrors())
15112     return;
15113 
15114   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15115   if (ClassDecl->isInvalidDecl()) return;
15116   if (ClassDecl->hasIrrelevantDestructor()) return;
15117   if (ClassDecl->isDependentContext()) return;
15118 
15119   if (VD->isNoDestroy(getASTContext()))
15120     return;
15121 
15122   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15123 
15124   // If this is an array, we'll require the destructor during initialization, so
15125   // we can skip over this. We still want to emit exit-time destructor warnings
15126   // though.
15127   if (!VD->getType()->isArrayType()) {
15128     MarkFunctionReferenced(VD->getLocation(), Destructor);
15129     CheckDestructorAccess(VD->getLocation(), Destructor,
15130                           PDiag(diag::err_access_dtor_var)
15131                               << VD->getDeclName() << VD->getType());
15132     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15133   }
15134 
15135   if (Destructor->isTrivial()) return;
15136 
15137   // If the destructor is constexpr, check whether the variable has constant
15138   // destruction now.
15139   if (Destructor->isConstexpr()) {
15140     bool HasConstantInit = false;
15141     if (VD->getInit() && !VD->getInit()->isValueDependent())
15142       HasConstantInit = VD->evaluateValue();
15143     SmallVector<PartialDiagnosticAt, 8> Notes;
15144     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15145         HasConstantInit) {
15146       Diag(VD->getLocation(),
15147            diag::err_constexpr_var_requires_const_destruction) << VD;
15148       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15149         Diag(Notes[I].first, Notes[I].second);
15150     }
15151   }
15152 
15153   if (!VD->hasGlobalStorage()) return;
15154 
15155   // Emit warning for non-trivial dtor in global scope (a real global,
15156   // class-static, function-static).
15157   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15158 
15159   // TODO: this should be re-enabled for static locals by !CXAAtExit
15160   if (!VD->isStaticLocal())
15161     Diag(VD->getLocation(), diag::warn_global_destructor);
15162 }
15163 
15164 /// Given a constructor and the set of arguments provided for the
15165 /// constructor, convert the arguments and add any required default arguments
15166 /// to form a proper call to this constructor.
15167 ///
15168 /// \returns true if an error occurred, false otherwise.
15169 bool
15170 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15171                               MultiExprArg ArgsPtr,
15172                               SourceLocation Loc,
15173                               SmallVectorImpl<Expr*> &ConvertedArgs,
15174                               bool AllowExplicit,
15175                               bool IsListInitialization) {
15176   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15177   unsigned NumArgs = ArgsPtr.size();
15178   Expr **Args = ArgsPtr.data();
15179 
15180   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15181   unsigned NumParams = Proto->getNumParams();
15182 
15183   // If too few arguments are available, we'll fill in the rest with defaults.
15184   if (NumArgs < NumParams)
15185     ConvertedArgs.reserve(NumParams);
15186   else
15187     ConvertedArgs.reserve(NumArgs);
15188 
15189   VariadicCallType CallType =
15190     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15191   SmallVector<Expr *, 8> AllArgs;
15192   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15193                                         Proto, 0,
15194                                         llvm::makeArrayRef(Args, NumArgs),
15195                                         AllArgs,
15196                                         CallType, AllowExplicit,
15197                                         IsListInitialization);
15198   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15199 
15200   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15201 
15202   CheckConstructorCall(Constructor,
15203                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15204                        Proto, Loc);
15205 
15206   return Invalid;
15207 }
15208 
15209 static inline bool
15210 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15211                                        const FunctionDecl *FnDecl) {
15212   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15213   if (isa<NamespaceDecl>(DC)) {
15214     return SemaRef.Diag(FnDecl->getLocation(),
15215                         diag::err_operator_new_delete_declared_in_namespace)
15216       << FnDecl->getDeclName();
15217   }
15218 
15219   if (isa<TranslationUnitDecl>(DC) &&
15220       FnDecl->getStorageClass() == SC_Static) {
15221     return SemaRef.Diag(FnDecl->getLocation(),
15222                         diag::err_operator_new_delete_declared_static)
15223       << FnDecl->getDeclName();
15224   }
15225 
15226   return false;
15227 }
15228 
15229 static QualType
15230 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15231   QualType QTy = PtrTy->getPointeeType();
15232   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15233   return SemaRef.Context.getPointerType(QTy);
15234 }
15235 
15236 static inline bool
15237 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15238                             CanQualType ExpectedResultType,
15239                             CanQualType ExpectedFirstParamType,
15240                             unsigned DependentParamTypeDiag,
15241                             unsigned InvalidParamTypeDiag) {
15242   QualType ResultType =
15243       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15244 
15245   // The operator is valid on any address space for OpenCL.
15246   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15247     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15248       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15249     }
15250   }
15251 
15252   // Check that the result type is what we expect.
15253   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15254     // Reject even if the type is dependent; an operator delete function is
15255     // required to have a non-dependent result type.
15256     return SemaRef.Diag(
15257                FnDecl->getLocation(),
15258                ResultType->isDependentType()
15259                    ? diag::err_operator_new_delete_dependent_result_type
15260                    : diag::err_operator_new_delete_invalid_result_type)
15261            << FnDecl->getDeclName() << ExpectedResultType;
15262   }
15263 
15264   // A function template must have at least 2 parameters.
15265   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15266     return SemaRef.Diag(FnDecl->getLocation(),
15267                       diag::err_operator_new_delete_template_too_few_parameters)
15268         << FnDecl->getDeclName();
15269 
15270   // The function decl must have at least 1 parameter.
15271   if (FnDecl->getNumParams() == 0)
15272     return SemaRef.Diag(FnDecl->getLocation(),
15273                         diag::err_operator_new_delete_too_few_parameters)
15274       << FnDecl->getDeclName();
15275 
15276   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15277   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15278     // The operator is valid on any address space for OpenCL.
15279     if (auto *PtrTy =
15280             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15281       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15282     }
15283   }
15284 
15285   // Check that the first parameter type is what we expect.
15286   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15287       ExpectedFirstParamType) {
15288     // The first parameter type is not allowed to be dependent. As a tentative
15289     // DR resolution, we allow a dependent parameter type if it is the right
15290     // type anyway, to allow destroying operator delete in class templates.
15291     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15292                                                    ? DependentParamTypeDiag
15293                                                    : InvalidParamTypeDiag)
15294            << FnDecl->getDeclName() << ExpectedFirstParamType;
15295   }
15296 
15297   return false;
15298 }
15299 
15300 static bool
15301 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15302   // C++ [basic.stc.dynamic.allocation]p1:
15303   //   A program is ill-formed if an allocation function is declared in a
15304   //   namespace scope other than global scope or declared static in global
15305   //   scope.
15306   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15307     return true;
15308 
15309   CanQualType SizeTy =
15310     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15311 
15312   // C++ [basic.stc.dynamic.allocation]p1:
15313   //  The return type shall be void*. The first parameter shall have type
15314   //  std::size_t.
15315   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15316                                   SizeTy,
15317                                   diag::err_operator_new_dependent_param_type,
15318                                   diag::err_operator_new_param_type))
15319     return true;
15320 
15321   // C++ [basic.stc.dynamic.allocation]p1:
15322   //  The first parameter shall not have an associated default argument.
15323   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15324     return SemaRef.Diag(FnDecl->getLocation(),
15325                         diag::err_operator_new_default_arg)
15326       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15327 
15328   return false;
15329 }
15330 
15331 static bool
15332 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15333   // C++ [basic.stc.dynamic.deallocation]p1:
15334   //   A program is ill-formed if deallocation functions are declared in a
15335   //   namespace scope other than global scope or declared static in global
15336   //   scope.
15337   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15338     return true;
15339 
15340   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15341 
15342   // C++ P0722:
15343   //   Within a class C, the first parameter of a destroying operator delete
15344   //   shall be of type C *. The first parameter of any other deallocation
15345   //   function shall be of type void *.
15346   CanQualType ExpectedFirstParamType =
15347       MD && MD->isDestroyingOperatorDelete()
15348           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15349                 SemaRef.Context.getRecordType(MD->getParent())))
15350           : SemaRef.Context.VoidPtrTy;
15351 
15352   // C++ [basic.stc.dynamic.deallocation]p2:
15353   //   Each deallocation function shall return void
15354   if (CheckOperatorNewDeleteTypes(
15355           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15356           diag::err_operator_delete_dependent_param_type,
15357           diag::err_operator_delete_param_type))
15358     return true;
15359 
15360   // C++ P0722:
15361   //   A destroying operator delete shall be a usual deallocation function.
15362   if (MD && !MD->getParent()->isDependentContext() &&
15363       MD->isDestroyingOperatorDelete() &&
15364       !SemaRef.isUsualDeallocationFunction(MD)) {
15365     SemaRef.Diag(MD->getLocation(),
15366                  diag::err_destroying_operator_delete_not_usual);
15367     return true;
15368   }
15369 
15370   return false;
15371 }
15372 
15373 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15374 /// of this overloaded operator is well-formed. If so, returns false;
15375 /// otherwise, emits appropriate diagnostics and returns true.
15376 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15377   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15378          "Expected an overloaded operator declaration");
15379 
15380   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15381 
15382   // C++ [over.oper]p5:
15383   //   The allocation and deallocation functions, operator new,
15384   //   operator new[], operator delete and operator delete[], are
15385   //   described completely in 3.7.3. The attributes and restrictions
15386   //   found in the rest of this subclause do not apply to them unless
15387   //   explicitly stated in 3.7.3.
15388   if (Op == OO_Delete || Op == OO_Array_Delete)
15389     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15390 
15391   if (Op == OO_New || Op == OO_Array_New)
15392     return CheckOperatorNewDeclaration(*this, FnDecl);
15393 
15394   // C++ [over.oper]p6:
15395   //   An operator function shall either be a non-static member
15396   //   function or be a non-member function and have at least one
15397   //   parameter whose type is a class, a reference to a class, an
15398   //   enumeration, or a reference to an enumeration.
15399   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15400     if (MethodDecl->isStatic())
15401       return Diag(FnDecl->getLocation(),
15402                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15403   } else {
15404     bool ClassOrEnumParam = false;
15405     for (auto Param : FnDecl->parameters()) {
15406       QualType ParamType = Param->getType().getNonReferenceType();
15407       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15408           ParamType->isEnumeralType()) {
15409         ClassOrEnumParam = true;
15410         break;
15411       }
15412     }
15413 
15414     if (!ClassOrEnumParam)
15415       return Diag(FnDecl->getLocation(),
15416                   diag::err_operator_overload_needs_class_or_enum)
15417         << FnDecl->getDeclName();
15418   }
15419 
15420   // C++ [over.oper]p8:
15421   //   An operator function cannot have default arguments (8.3.6),
15422   //   except where explicitly stated below.
15423   //
15424   // Only the function-call operator allows default arguments
15425   // (C++ [over.call]p1).
15426   if (Op != OO_Call) {
15427     for (auto Param : FnDecl->parameters()) {
15428       if (Param->hasDefaultArg())
15429         return Diag(Param->getLocation(),
15430                     diag::err_operator_overload_default_arg)
15431           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15432     }
15433   }
15434 
15435   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15436     { false, false, false }
15437 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15438     , { Unary, Binary, MemberOnly }
15439 #include "clang/Basic/OperatorKinds.def"
15440   };
15441 
15442   bool CanBeUnaryOperator = OperatorUses[Op][0];
15443   bool CanBeBinaryOperator = OperatorUses[Op][1];
15444   bool MustBeMemberOperator = OperatorUses[Op][2];
15445 
15446   // C++ [over.oper]p8:
15447   //   [...] Operator functions cannot have more or fewer parameters
15448   //   than the number required for the corresponding operator, as
15449   //   described in the rest of this subclause.
15450   unsigned NumParams = FnDecl->getNumParams()
15451                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15452   if (Op != OO_Call &&
15453       ((NumParams == 1 && !CanBeUnaryOperator) ||
15454        (NumParams == 2 && !CanBeBinaryOperator) ||
15455        (NumParams < 1) || (NumParams > 2))) {
15456     // We have the wrong number of parameters.
15457     unsigned ErrorKind;
15458     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15459       ErrorKind = 2;  // 2 -> unary or binary.
15460     } else if (CanBeUnaryOperator) {
15461       ErrorKind = 0;  // 0 -> unary
15462     } else {
15463       assert(CanBeBinaryOperator &&
15464              "All non-call overloaded operators are unary or binary!");
15465       ErrorKind = 1;  // 1 -> binary
15466     }
15467 
15468     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15469       << FnDecl->getDeclName() << NumParams << ErrorKind;
15470   }
15471 
15472   // Overloaded operators other than operator() cannot be variadic.
15473   if (Op != OO_Call &&
15474       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15475     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15476       << FnDecl->getDeclName();
15477   }
15478 
15479   // Some operators must be non-static member functions.
15480   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15481     return Diag(FnDecl->getLocation(),
15482                 diag::err_operator_overload_must_be_member)
15483       << FnDecl->getDeclName();
15484   }
15485 
15486   // C++ [over.inc]p1:
15487   //   The user-defined function called operator++ implements the
15488   //   prefix and postfix ++ operator. If this function is a member
15489   //   function with no parameters, or a non-member function with one
15490   //   parameter of class or enumeration type, it defines the prefix
15491   //   increment operator ++ for objects of that type. If the function
15492   //   is a member function with one parameter (which shall be of type
15493   //   int) or a non-member function with two parameters (the second
15494   //   of which shall be of type int), it defines the postfix
15495   //   increment operator ++ for objects of that type.
15496   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15497     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15498     QualType ParamType = LastParam->getType();
15499 
15500     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15501         !ParamType->isDependentType())
15502       return Diag(LastParam->getLocation(),
15503                   diag::err_operator_overload_post_incdec_must_be_int)
15504         << LastParam->getType() << (Op == OO_MinusMinus);
15505   }
15506 
15507   return false;
15508 }
15509 
15510 static bool
15511 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15512                                           FunctionTemplateDecl *TpDecl) {
15513   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15514 
15515   // Must have one or two template parameters.
15516   if (TemplateParams->size() == 1) {
15517     NonTypeTemplateParmDecl *PmDecl =
15518         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15519 
15520     // The template parameter must be a char parameter pack.
15521     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15522         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15523       return false;
15524 
15525     // C++20 [over.literal]p5:
15526     //   A string literal operator template is a literal operator template
15527     //   whose template-parameter-list comprises a single non-type
15528     //   template-parameter of class type.
15529     //
15530     // As a DR resolution, we also allow placeholders for deduced class
15531     // template specializations.
15532     if (SemaRef.getLangOpts().CPlusPlus20 &&
15533         !PmDecl->isTemplateParameterPack() &&
15534         (PmDecl->getType()->isRecordType() ||
15535          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15536       return false;
15537   } else if (TemplateParams->size() == 2) {
15538     TemplateTypeParmDecl *PmType =
15539         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15540     NonTypeTemplateParmDecl *PmArgs =
15541         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15542 
15543     // The second template parameter must be a parameter pack with the
15544     // first template parameter as its type.
15545     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15546         PmArgs->isTemplateParameterPack()) {
15547       const TemplateTypeParmType *TArgs =
15548           PmArgs->getType()->getAs<TemplateTypeParmType>();
15549       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15550           TArgs->getIndex() == PmType->getIndex()) {
15551         if (!SemaRef.inTemplateInstantiation())
15552           SemaRef.Diag(TpDecl->getLocation(),
15553                        diag::ext_string_literal_operator_template);
15554         return false;
15555       }
15556     }
15557   }
15558 
15559   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15560                diag::err_literal_operator_template)
15561       << TpDecl->getTemplateParameters()->getSourceRange();
15562   return true;
15563 }
15564 
15565 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15566 /// of this literal operator function is well-formed. If so, returns
15567 /// false; otherwise, emits appropriate diagnostics and returns true.
15568 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15569   if (isa<CXXMethodDecl>(FnDecl)) {
15570     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15571       << FnDecl->getDeclName();
15572     return true;
15573   }
15574 
15575   if (FnDecl->isExternC()) {
15576     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15577     if (const LinkageSpecDecl *LSD =
15578             FnDecl->getDeclContext()->getExternCContext())
15579       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15580     return true;
15581   }
15582 
15583   // This might be the definition of a literal operator template.
15584   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15585 
15586   // This might be a specialization of a literal operator template.
15587   if (!TpDecl)
15588     TpDecl = FnDecl->getPrimaryTemplate();
15589 
15590   // template <char...> type operator "" name() and
15591   // template <class T, T...> type operator "" name() are the only valid
15592   // template signatures, and the only valid signatures with no parameters.
15593   //
15594   // C++20 also allows template <SomeClass T> type operator "" name().
15595   if (TpDecl) {
15596     if (FnDecl->param_size() != 0) {
15597       Diag(FnDecl->getLocation(),
15598            diag::err_literal_operator_template_with_params);
15599       return true;
15600     }
15601 
15602     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15603       return true;
15604 
15605   } else if (FnDecl->param_size() == 1) {
15606     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15607 
15608     QualType ParamType = Param->getType().getUnqualifiedType();
15609 
15610     // Only unsigned long long int, long double, any character type, and const
15611     // char * are allowed as the only parameters.
15612     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15613         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15614         Context.hasSameType(ParamType, Context.CharTy) ||
15615         Context.hasSameType(ParamType, Context.WideCharTy) ||
15616         Context.hasSameType(ParamType, Context.Char8Ty) ||
15617         Context.hasSameType(ParamType, Context.Char16Ty) ||
15618         Context.hasSameType(ParamType, Context.Char32Ty)) {
15619     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15620       QualType InnerType = Ptr->getPointeeType();
15621 
15622       // Pointer parameter must be a const char *.
15623       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15624                                 Context.CharTy) &&
15625             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15626         Diag(Param->getSourceRange().getBegin(),
15627              diag::err_literal_operator_param)
15628             << ParamType << "'const char *'" << Param->getSourceRange();
15629         return true;
15630       }
15631 
15632     } else if (ParamType->isRealFloatingType()) {
15633       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15634           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15635       return true;
15636 
15637     } else if (ParamType->isIntegerType()) {
15638       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15639           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15640       return true;
15641 
15642     } else {
15643       Diag(Param->getSourceRange().getBegin(),
15644            diag::err_literal_operator_invalid_param)
15645           << ParamType << Param->getSourceRange();
15646       return true;
15647     }
15648 
15649   } else if (FnDecl->param_size() == 2) {
15650     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15651 
15652     // First, verify that the first parameter is correct.
15653 
15654     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15655 
15656     // Two parameter function must have a pointer to const as a
15657     // first parameter; let's strip those qualifiers.
15658     const PointerType *PT = FirstParamType->getAs<PointerType>();
15659 
15660     if (!PT) {
15661       Diag((*Param)->getSourceRange().getBegin(),
15662            diag::err_literal_operator_param)
15663           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15664       return true;
15665     }
15666 
15667     QualType PointeeType = PT->getPointeeType();
15668     // First parameter must be const
15669     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15670       Diag((*Param)->getSourceRange().getBegin(),
15671            diag::err_literal_operator_param)
15672           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15673       return true;
15674     }
15675 
15676     QualType InnerType = PointeeType.getUnqualifiedType();
15677     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15678     // const char32_t* are allowed as the first parameter to a two-parameter
15679     // function
15680     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15681           Context.hasSameType(InnerType, Context.WideCharTy) ||
15682           Context.hasSameType(InnerType, Context.Char8Ty) ||
15683           Context.hasSameType(InnerType, Context.Char16Ty) ||
15684           Context.hasSameType(InnerType, Context.Char32Ty))) {
15685       Diag((*Param)->getSourceRange().getBegin(),
15686            diag::err_literal_operator_param)
15687           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15688       return true;
15689     }
15690 
15691     // Move on to the second and final parameter.
15692     ++Param;
15693 
15694     // The second parameter must be a std::size_t.
15695     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15696     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15697       Diag((*Param)->getSourceRange().getBegin(),
15698            diag::err_literal_operator_param)
15699           << SecondParamType << Context.getSizeType()
15700           << (*Param)->getSourceRange();
15701       return true;
15702     }
15703   } else {
15704     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15705     return true;
15706   }
15707 
15708   // Parameters are good.
15709 
15710   // A parameter-declaration-clause containing a default argument is not
15711   // equivalent to any of the permitted forms.
15712   for (auto Param : FnDecl->parameters()) {
15713     if (Param->hasDefaultArg()) {
15714       Diag(Param->getDefaultArgRange().getBegin(),
15715            diag::err_literal_operator_default_argument)
15716         << Param->getDefaultArgRange();
15717       break;
15718     }
15719   }
15720 
15721   StringRef LiteralName
15722     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15723   if (LiteralName[0] != '_' &&
15724       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15725     // C++11 [usrlit.suffix]p1:
15726     //   Literal suffix identifiers that do not start with an underscore
15727     //   are reserved for future standardization.
15728     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15729       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15730   }
15731 
15732   return false;
15733 }
15734 
15735 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15736 /// linkage specification, including the language and (if present)
15737 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15738 /// language string literal. LBraceLoc, if valid, provides the location of
15739 /// the '{' brace. Otherwise, this linkage specification does not
15740 /// have any braces.
15741 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15742                                            Expr *LangStr,
15743                                            SourceLocation LBraceLoc) {
15744   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15745   if (!Lit->isAscii()) {
15746     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15747       << LangStr->getSourceRange();
15748     return nullptr;
15749   }
15750 
15751   StringRef Lang = Lit->getString();
15752   LinkageSpecDecl::LanguageIDs Language;
15753   if (Lang == "C")
15754     Language = LinkageSpecDecl::lang_c;
15755   else if (Lang == "C++")
15756     Language = LinkageSpecDecl::lang_cxx;
15757   else {
15758     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15759       << LangStr->getSourceRange();
15760     return nullptr;
15761   }
15762 
15763   // FIXME: Add all the various semantics of linkage specifications
15764 
15765   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15766                                                LangStr->getExprLoc(), Language,
15767                                                LBraceLoc.isValid());
15768   CurContext->addDecl(D);
15769   PushDeclContext(S, D);
15770   return D;
15771 }
15772 
15773 /// ActOnFinishLinkageSpecification - Complete the definition of
15774 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15775 /// valid, it's the position of the closing '}' brace in a linkage
15776 /// specification that uses braces.
15777 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15778                                             Decl *LinkageSpec,
15779                                             SourceLocation RBraceLoc) {
15780   if (RBraceLoc.isValid()) {
15781     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15782     LSDecl->setRBraceLoc(RBraceLoc);
15783   }
15784   PopDeclContext();
15785   return LinkageSpec;
15786 }
15787 
15788 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15789                                   const ParsedAttributesView &AttrList,
15790                                   SourceLocation SemiLoc) {
15791   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15792   // Attribute declarations appertain to empty declaration so we handle
15793   // them here.
15794   ProcessDeclAttributeList(S, ED, AttrList);
15795 
15796   CurContext->addDecl(ED);
15797   return ED;
15798 }
15799 
15800 /// Perform semantic analysis for the variable declaration that
15801 /// occurs within a C++ catch clause, returning the newly-created
15802 /// variable.
15803 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15804                                          TypeSourceInfo *TInfo,
15805                                          SourceLocation StartLoc,
15806                                          SourceLocation Loc,
15807                                          IdentifierInfo *Name) {
15808   bool Invalid = false;
15809   QualType ExDeclType = TInfo->getType();
15810 
15811   // Arrays and functions decay.
15812   if (ExDeclType->isArrayType())
15813     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15814   else if (ExDeclType->isFunctionType())
15815     ExDeclType = Context.getPointerType(ExDeclType);
15816 
15817   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15818   // The exception-declaration shall not denote a pointer or reference to an
15819   // incomplete type, other than [cv] void*.
15820   // N2844 forbids rvalue references.
15821   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15822     Diag(Loc, diag::err_catch_rvalue_ref);
15823     Invalid = true;
15824   }
15825 
15826   if (ExDeclType->isVariablyModifiedType()) {
15827     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15828     Invalid = true;
15829   }
15830 
15831   QualType BaseType = ExDeclType;
15832   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15833   unsigned DK = diag::err_catch_incomplete;
15834   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15835     BaseType = Ptr->getPointeeType();
15836     Mode = 1;
15837     DK = diag::err_catch_incomplete_ptr;
15838   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15839     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15840     BaseType = Ref->getPointeeType();
15841     Mode = 2;
15842     DK = diag::err_catch_incomplete_ref;
15843   }
15844   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15845       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15846     Invalid = true;
15847 
15848   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15849     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15850     Invalid = true;
15851   }
15852 
15853   if (!Invalid && !ExDeclType->isDependentType() &&
15854       RequireNonAbstractType(Loc, ExDeclType,
15855                              diag::err_abstract_type_in_decl,
15856                              AbstractVariableType))
15857     Invalid = true;
15858 
15859   // Only the non-fragile NeXT runtime currently supports C++ catches
15860   // of ObjC types, and no runtime supports catching ObjC types by value.
15861   if (!Invalid && getLangOpts().ObjC) {
15862     QualType T = ExDeclType;
15863     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15864       T = RT->getPointeeType();
15865 
15866     if (T->isObjCObjectType()) {
15867       Diag(Loc, diag::err_objc_object_catch);
15868       Invalid = true;
15869     } else if (T->isObjCObjectPointerType()) {
15870       // FIXME: should this be a test for macosx-fragile specifically?
15871       if (getLangOpts().ObjCRuntime.isFragile())
15872         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15873     }
15874   }
15875 
15876   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15877                                     ExDeclType, TInfo, SC_None);
15878   ExDecl->setExceptionVariable(true);
15879 
15880   // In ARC, infer 'retaining' for variables of retainable type.
15881   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15882     Invalid = true;
15883 
15884   if (!Invalid && !ExDeclType->isDependentType()) {
15885     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15886       // Insulate this from anything else we might currently be parsing.
15887       EnterExpressionEvaluationContext scope(
15888           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15889 
15890       // C++ [except.handle]p16:
15891       //   The object declared in an exception-declaration or, if the
15892       //   exception-declaration does not specify a name, a temporary (12.2) is
15893       //   copy-initialized (8.5) from the exception object. [...]
15894       //   The object is destroyed when the handler exits, after the destruction
15895       //   of any automatic objects initialized within the handler.
15896       //
15897       // We just pretend to initialize the object with itself, then make sure
15898       // it can be destroyed later.
15899       QualType initType = Context.getExceptionObjectType(ExDeclType);
15900 
15901       InitializedEntity entity =
15902         InitializedEntity::InitializeVariable(ExDecl);
15903       InitializationKind initKind =
15904         InitializationKind::CreateCopy(Loc, SourceLocation());
15905 
15906       Expr *opaqueValue =
15907         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15908       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15909       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15910       if (result.isInvalid())
15911         Invalid = true;
15912       else {
15913         // If the constructor used was non-trivial, set this as the
15914         // "initializer".
15915         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15916         if (!construct->getConstructor()->isTrivial()) {
15917           Expr *init = MaybeCreateExprWithCleanups(construct);
15918           ExDecl->setInit(init);
15919         }
15920 
15921         // And make sure it's destructable.
15922         FinalizeVarWithDestructor(ExDecl, recordType);
15923       }
15924     }
15925   }
15926 
15927   if (Invalid)
15928     ExDecl->setInvalidDecl();
15929 
15930   return ExDecl;
15931 }
15932 
15933 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15934 /// handler.
15935 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15936   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15937   bool Invalid = D.isInvalidType();
15938 
15939   // Check for unexpanded parameter packs.
15940   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15941                                       UPPC_ExceptionType)) {
15942     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15943                                              D.getIdentifierLoc());
15944     Invalid = true;
15945   }
15946 
15947   IdentifierInfo *II = D.getIdentifier();
15948   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15949                                              LookupOrdinaryName,
15950                                              ForVisibleRedeclaration)) {
15951     // The scope should be freshly made just for us. There is just no way
15952     // it contains any previous declaration, except for function parameters in
15953     // a function-try-block's catch statement.
15954     assert(!S->isDeclScope(PrevDecl));
15955     if (isDeclInScope(PrevDecl, CurContext, S)) {
15956       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15957         << D.getIdentifier();
15958       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15959       Invalid = true;
15960     } else if (PrevDecl->isTemplateParameter())
15961       // Maybe we will complain about the shadowed template parameter.
15962       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15963   }
15964 
15965   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15966     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15967       << D.getCXXScopeSpec().getRange();
15968     Invalid = true;
15969   }
15970 
15971   VarDecl *ExDecl = BuildExceptionDeclaration(
15972       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15973   if (Invalid)
15974     ExDecl->setInvalidDecl();
15975 
15976   // Add the exception declaration into this scope.
15977   if (II)
15978     PushOnScopeChains(ExDecl, S);
15979   else
15980     CurContext->addDecl(ExDecl);
15981 
15982   ProcessDeclAttributes(S, ExDecl, D);
15983   return ExDecl;
15984 }
15985 
15986 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15987                                          Expr *AssertExpr,
15988                                          Expr *AssertMessageExpr,
15989                                          SourceLocation RParenLoc) {
15990   StringLiteral *AssertMessage =
15991       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15992 
15993   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15994     return nullptr;
15995 
15996   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15997                                       AssertMessage, RParenLoc, false);
15998 }
15999 
16000 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16001                                          Expr *AssertExpr,
16002                                          StringLiteral *AssertMessage,
16003                                          SourceLocation RParenLoc,
16004                                          bool Failed) {
16005   assert(AssertExpr != nullptr && "Expected non-null condition");
16006   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16007       !Failed) {
16008     // In a static_assert-declaration, the constant-expression shall be a
16009     // constant expression that can be contextually converted to bool.
16010     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16011     if (Converted.isInvalid())
16012       Failed = true;
16013 
16014     ExprResult FullAssertExpr =
16015         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16016                             /*DiscardedValue*/ false,
16017                             /*IsConstexpr*/ true);
16018     if (FullAssertExpr.isInvalid())
16019       Failed = true;
16020     else
16021       AssertExpr = FullAssertExpr.get();
16022 
16023     llvm::APSInt Cond;
16024     if (!Failed && VerifyIntegerConstantExpression(
16025                        AssertExpr, &Cond,
16026                        diag::err_static_assert_expression_is_not_constant)
16027                        .isInvalid())
16028       Failed = true;
16029 
16030     if (!Failed && !Cond) {
16031       SmallString<256> MsgBuffer;
16032       llvm::raw_svector_ostream Msg(MsgBuffer);
16033       if (AssertMessage)
16034         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16035 
16036       Expr *InnerCond = nullptr;
16037       std::string InnerCondDescription;
16038       std::tie(InnerCond, InnerCondDescription) =
16039         findFailedBooleanCondition(Converted.get());
16040       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16041         // Drill down into concept specialization expressions to see why they
16042         // weren't satisfied.
16043         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16044           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16045         ConstraintSatisfaction Satisfaction;
16046         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16047           DiagnoseUnsatisfiedConstraint(Satisfaction);
16048       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16049                            && !isa<IntegerLiteral>(InnerCond)) {
16050         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16051           << InnerCondDescription << !AssertMessage
16052           << Msg.str() << InnerCond->getSourceRange();
16053       } else {
16054         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16055           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16056       }
16057       Failed = true;
16058     }
16059   } else {
16060     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16061                                                     /*DiscardedValue*/false,
16062                                                     /*IsConstexpr*/true);
16063     if (FullAssertExpr.isInvalid())
16064       Failed = true;
16065     else
16066       AssertExpr = FullAssertExpr.get();
16067   }
16068 
16069   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16070                                         AssertExpr, AssertMessage, RParenLoc,
16071                                         Failed);
16072 
16073   CurContext->addDecl(Decl);
16074   return Decl;
16075 }
16076 
16077 /// Perform semantic analysis of the given friend type declaration.
16078 ///
16079 /// \returns A friend declaration that.
16080 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16081                                       SourceLocation FriendLoc,
16082                                       TypeSourceInfo *TSInfo) {
16083   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16084 
16085   QualType T = TSInfo->getType();
16086   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16087 
16088   // C++03 [class.friend]p2:
16089   //   An elaborated-type-specifier shall be used in a friend declaration
16090   //   for a class.*
16091   //
16092   //   * The class-key of the elaborated-type-specifier is required.
16093   if (!CodeSynthesisContexts.empty()) {
16094     // Do not complain about the form of friend template types during any kind
16095     // of code synthesis. For template instantiation, we will have complained
16096     // when the template was defined.
16097   } else {
16098     if (!T->isElaboratedTypeSpecifier()) {
16099       // If we evaluated the type to a record type, suggest putting
16100       // a tag in front.
16101       if (const RecordType *RT = T->getAs<RecordType>()) {
16102         RecordDecl *RD = RT->getDecl();
16103 
16104         SmallString<16> InsertionText(" ");
16105         InsertionText += RD->getKindName();
16106 
16107         Diag(TypeRange.getBegin(),
16108              getLangOpts().CPlusPlus11 ?
16109                diag::warn_cxx98_compat_unelaborated_friend_type :
16110                diag::ext_unelaborated_friend_type)
16111           << (unsigned) RD->getTagKind()
16112           << T
16113           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16114                                         InsertionText);
16115       } else {
16116         Diag(FriendLoc,
16117              getLangOpts().CPlusPlus11 ?
16118                diag::warn_cxx98_compat_nonclass_type_friend :
16119                diag::ext_nonclass_type_friend)
16120           << T
16121           << TypeRange;
16122       }
16123     } else if (T->getAs<EnumType>()) {
16124       Diag(FriendLoc,
16125            getLangOpts().CPlusPlus11 ?
16126              diag::warn_cxx98_compat_enum_friend :
16127              diag::ext_enum_friend)
16128         << T
16129         << TypeRange;
16130     }
16131 
16132     // C++11 [class.friend]p3:
16133     //   A friend declaration that does not declare a function shall have one
16134     //   of the following forms:
16135     //     friend elaborated-type-specifier ;
16136     //     friend simple-type-specifier ;
16137     //     friend typename-specifier ;
16138     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16139       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16140   }
16141 
16142   //   If the type specifier in a friend declaration designates a (possibly
16143   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16144   //   the friend declaration is ignored.
16145   return FriendDecl::Create(Context, CurContext,
16146                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16147                             FriendLoc);
16148 }
16149 
16150 /// Handle a friend tag declaration where the scope specifier was
16151 /// templated.
16152 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16153                                     unsigned TagSpec, SourceLocation TagLoc,
16154                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16155                                     SourceLocation NameLoc,
16156                                     const ParsedAttributesView &Attr,
16157                                     MultiTemplateParamsArg TempParamLists) {
16158   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16159 
16160   bool IsMemberSpecialization = false;
16161   bool Invalid = false;
16162 
16163   if (TemplateParameterList *TemplateParams =
16164           MatchTemplateParametersToScopeSpecifier(
16165               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16166               IsMemberSpecialization, Invalid)) {
16167     if (TemplateParams->size() > 0) {
16168       // This is a declaration of a class template.
16169       if (Invalid)
16170         return nullptr;
16171 
16172       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16173                                 NameLoc, Attr, TemplateParams, AS_public,
16174                                 /*ModulePrivateLoc=*/SourceLocation(),
16175                                 FriendLoc, TempParamLists.size() - 1,
16176                                 TempParamLists.data()).get();
16177     } else {
16178       // The "template<>" header is extraneous.
16179       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16180         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16181       IsMemberSpecialization = true;
16182     }
16183   }
16184 
16185   if (Invalid) return nullptr;
16186 
16187   bool isAllExplicitSpecializations = true;
16188   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16189     if (TempParamLists[I]->size()) {
16190       isAllExplicitSpecializations = false;
16191       break;
16192     }
16193   }
16194 
16195   // FIXME: don't ignore attributes.
16196 
16197   // If it's explicit specializations all the way down, just forget
16198   // about the template header and build an appropriate non-templated
16199   // friend.  TODO: for source fidelity, remember the headers.
16200   if (isAllExplicitSpecializations) {
16201     if (SS.isEmpty()) {
16202       bool Owned = false;
16203       bool IsDependent = false;
16204       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16205                       Attr, AS_public,
16206                       /*ModulePrivateLoc=*/SourceLocation(),
16207                       MultiTemplateParamsArg(), Owned, IsDependent,
16208                       /*ScopedEnumKWLoc=*/SourceLocation(),
16209                       /*ScopedEnumUsesClassTag=*/false,
16210                       /*UnderlyingType=*/TypeResult(),
16211                       /*IsTypeSpecifier=*/false,
16212                       /*IsTemplateParamOrArg=*/false);
16213     }
16214 
16215     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16216     ElaboratedTypeKeyword Keyword
16217       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16218     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16219                                    *Name, NameLoc);
16220     if (T.isNull())
16221       return nullptr;
16222 
16223     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16224     if (isa<DependentNameType>(T)) {
16225       DependentNameTypeLoc TL =
16226           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16227       TL.setElaboratedKeywordLoc(TagLoc);
16228       TL.setQualifierLoc(QualifierLoc);
16229       TL.setNameLoc(NameLoc);
16230     } else {
16231       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16232       TL.setElaboratedKeywordLoc(TagLoc);
16233       TL.setQualifierLoc(QualifierLoc);
16234       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16235     }
16236 
16237     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16238                                             TSI, FriendLoc, TempParamLists);
16239     Friend->setAccess(AS_public);
16240     CurContext->addDecl(Friend);
16241     return Friend;
16242   }
16243 
16244   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16245 
16246 
16247 
16248   // Handle the case of a templated-scope friend class.  e.g.
16249   //   template <class T> class A<T>::B;
16250   // FIXME: we don't support these right now.
16251   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16252     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16253   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16254   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16255   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16256   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16257   TL.setElaboratedKeywordLoc(TagLoc);
16258   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16259   TL.setNameLoc(NameLoc);
16260 
16261   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16262                                           TSI, FriendLoc, TempParamLists);
16263   Friend->setAccess(AS_public);
16264   Friend->setUnsupportedFriend(true);
16265   CurContext->addDecl(Friend);
16266   return Friend;
16267 }
16268 
16269 /// Handle a friend type declaration.  This works in tandem with
16270 /// ActOnTag.
16271 ///
16272 /// Notes on friend class templates:
16273 ///
16274 /// We generally treat friend class declarations as if they were
16275 /// declaring a class.  So, for example, the elaborated type specifier
16276 /// in a friend declaration is required to obey the restrictions of a
16277 /// class-head (i.e. no typedefs in the scope chain), template
16278 /// parameters are required to match up with simple template-ids, &c.
16279 /// However, unlike when declaring a template specialization, it's
16280 /// okay to refer to a template specialization without an empty
16281 /// template parameter declaration, e.g.
16282 ///   friend class A<T>::B<unsigned>;
16283 /// We permit this as a special case; if there are any template
16284 /// parameters present at all, require proper matching, i.e.
16285 ///   template <> template \<class T> friend class A<int>::B;
16286 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16287                                 MultiTemplateParamsArg TempParams) {
16288   SourceLocation Loc = DS.getBeginLoc();
16289 
16290   assert(DS.isFriendSpecified());
16291   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16292 
16293   // C++ [class.friend]p3:
16294   // A friend declaration that does not declare a function shall have one of
16295   // the following forms:
16296   //     friend elaborated-type-specifier ;
16297   //     friend simple-type-specifier ;
16298   //     friend typename-specifier ;
16299   //
16300   // Any declaration with a type qualifier does not have that form. (It's
16301   // legal to specify a qualified type as a friend, you just can't write the
16302   // keywords.)
16303   if (DS.getTypeQualifiers()) {
16304     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16305       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16306     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16307       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16308     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16309       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16310     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16311       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16312     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16313       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16314   }
16315 
16316   // Try to convert the decl specifier to a type.  This works for
16317   // friend templates because ActOnTag never produces a ClassTemplateDecl
16318   // for a TUK_Friend.
16319   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16320   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16321   QualType T = TSI->getType();
16322   if (TheDeclarator.isInvalidType())
16323     return nullptr;
16324 
16325   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16326     return nullptr;
16327 
16328   // This is definitely an error in C++98.  It's probably meant to
16329   // be forbidden in C++0x, too, but the specification is just
16330   // poorly written.
16331   //
16332   // The problem is with declarations like the following:
16333   //   template <T> friend A<T>::foo;
16334   // where deciding whether a class C is a friend or not now hinges
16335   // on whether there exists an instantiation of A that causes
16336   // 'foo' to equal C.  There are restrictions on class-heads
16337   // (which we declare (by fiat) elaborated friend declarations to
16338   // be) that makes this tractable.
16339   //
16340   // FIXME: handle "template <> friend class A<T>;", which
16341   // is possibly well-formed?  Who even knows?
16342   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16343     Diag(Loc, diag::err_tagless_friend_type_template)
16344       << DS.getSourceRange();
16345     return nullptr;
16346   }
16347 
16348   // C++98 [class.friend]p1: A friend of a class is a function
16349   //   or class that is not a member of the class . . .
16350   // This is fixed in DR77, which just barely didn't make the C++03
16351   // deadline.  It's also a very silly restriction that seriously
16352   // affects inner classes and which nobody else seems to implement;
16353   // thus we never diagnose it, not even in -pedantic.
16354   //
16355   // But note that we could warn about it: it's always useless to
16356   // friend one of your own members (it's not, however, worthless to
16357   // friend a member of an arbitrary specialization of your template).
16358 
16359   Decl *D;
16360   if (!TempParams.empty())
16361     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16362                                    TempParams,
16363                                    TSI,
16364                                    DS.getFriendSpecLoc());
16365   else
16366     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16367 
16368   if (!D)
16369     return nullptr;
16370 
16371   D->setAccess(AS_public);
16372   CurContext->addDecl(D);
16373 
16374   return D;
16375 }
16376 
16377 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16378                                         MultiTemplateParamsArg TemplateParams) {
16379   const DeclSpec &DS = D.getDeclSpec();
16380 
16381   assert(DS.isFriendSpecified());
16382   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16383 
16384   SourceLocation Loc = D.getIdentifierLoc();
16385   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16386 
16387   // C++ [class.friend]p1
16388   //   A friend of a class is a function or class....
16389   // Note that this sees through typedefs, which is intended.
16390   // It *doesn't* see through dependent types, which is correct
16391   // according to [temp.arg.type]p3:
16392   //   If a declaration acquires a function type through a
16393   //   type dependent on a template-parameter and this causes
16394   //   a declaration that does not use the syntactic form of a
16395   //   function declarator to have a function type, the program
16396   //   is ill-formed.
16397   if (!TInfo->getType()->isFunctionType()) {
16398     Diag(Loc, diag::err_unexpected_friend);
16399 
16400     // It might be worthwhile to try to recover by creating an
16401     // appropriate declaration.
16402     return nullptr;
16403   }
16404 
16405   // C++ [namespace.memdef]p3
16406   //  - If a friend declaration in a non-local class first declares a
16407   //    class or function, the friend class or function is a member
16408   //    of the innermost enclosing namespace.
16409   //  - The name of the friend is not found by simple name lookup
16410   //    until a matching declaration is provided in that namespace
16411   //    scope (either before or after the class declaration granting
16412   //    friendship).
16413   //  - If a friend function is called, its name may be found by the
16414   //    name lookup that considers functions from namespaces and
16415   //    classes associated with the types of the function arguments.
16416   //  - When looking for a prior declaration of a class or a function
16417   //    declared as a friend, scopes outside the innermost enclosing
16418   //    namespace scope are not considered.
16419 
16420   CXXScopeSpec &SS = D.getCXXScopeSpec();
16421   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16422   assert(NameInfo.getName());
16423 
16424   // Check for unexpanded parameter packs.
16425   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16426       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16427       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16428     return nullptr;
16429 
16430   // The context we found the declaration in, or in which we should
16431   // create the declaration.
16432   DeclContext *DC;
16433   Scope *DCScope = S;
16434   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16435                         ForExternalRedeclaration);
16436 
16437   // There are five cases here.
16438   //   - There's no scope specifier and we're in a local class. Only look
16439   //     for functions declared in the immediately-enclosing block scope.
16440   // We recover from invalid scope qualifiers as if they just weren't there.
16441   FunctionDecl *FunctionContainingLocalClass = nullptr;
16442   if ((SS.isInvalid() || !SS.isSet()) &&
16443       (FunctionContainingLocalClass =
16444            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16445     // C++11 [class.friend]p11:
16446     //   If a friend declaration appears in a local class and the name
16447     //   specified is an unqualified name, a prior declaration is
16448     //   looked up without considering scopes that are outside the
16449     //   innermost enclosing non-class scope. For a friend function
16450     //   declaration, if there is no prior declaration, the program is
16451     //   ill-formed.
16452 
16453     // Find the innermost enclosing non-class scope. This is the block
16454     // scope containing the local class definition (or for a nested class,
16455     // the outer local class).
16456     DCScope = S->getFnParent();
16457 
16458     // Look up the function name in the scope.
16459     Previous.clear(LookupLocalFriendName);
16460     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16461 
16462     if (!Previous.empty()) {
16463       // All possible previous declarations must have the same context:
16464       // either they were declared at block scope or they are members of
16465       // one of the enclosing local classes.
16466       DC = Previous.getRepresentativeDecl()->getDeclContext();
16467     } else {
16468       // This is ill-formed, but provide the context that we would have
16469       // declared the function in, if we were permitted to, for error recovery.
16470       DC = FunctionContainingLocalClass;
16471     }
16472     adjustContextForLocalExternDecl(DC);
16473 
16474     // C++ [class.friend]p6:
16475     //   A function can be defined in a friend declaration of a class if and
16476     //   only if the class is a non-local class (9.8), the function name is
16477     //   unqualified, and the function has namespace scope.
16478     if (D.isFunctionDefinition()) {
16479       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16480     }
16481 
16482   //   - There's no scope specifier, in which case we just go to the
16483   //     appropriate scope and look for a function or function template
16484   //     there as appropriate.
16485   } else if (SS.isInvalid() || !SS.isSet()) {
16486     // C++11 [namespace.memdef]p3:
16487     //   If the name in a friend declaration is neither qualified nor
16488     //   a template-id and the declaration is a function or an
16489     //   elaborated-type-specifier, the lookup to determine whether
16490     //   the entity has been previously declared shall not consider
16491     //   any scopes outside the innermost enclosing namespace.
16492     bool isTemplateId =
16493         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16494 
16495     // Find the appropriate context according to the above.
16496     DC = CurContext;
16497 
16498     // Skip class contexts.  If someone can cite chapter and verse
16499     // for this behavior, that would be nice --- it's what GCC and
16500     // EDG do, and it seems like a reasonable intent, but the spec
16501     // really only says that checks for unqualified existing
16502     // declarations should stop at the nearest enclosing namespace,
16503     // not that they should only consider the nearest enclosing
16504     // namespace.
16505     while (DC->isRecord())
16506       DC = DC->getParent();
16507 
16508     DeclContext *LookupDC = DC;
16509     while (LookupDC->isTransparentContext())
16510       LookupDC = LookupDC->getParent();
16511 
16512     while (true) {
16513       LookupQualifiedName(Previous, LookupDC);
16514 
16515       if (!Previous.empty()) {
16516         DC = LookupDC;
16517         break;
16518       }
16519 
16520       if (isTemplateId) {
16521         if (isa<TranslationUnitDecl>(LookupDC)) break;
16522       } else {
16523         if (LookupDC->isFileContext()) break;
16524       }
16525       LookupDC = LookupDC->getParent();
16526     }
16527 
16528     DCScope = getScopeForDeclContext(S, DC);
16529 
16530   //   - There's a non-dependent scope specifier, in which case we
16531   //     compute it and do a previous lookup there for a function
16532   //     or function template.
16533   } else if (!SS.getScopeRep()->isDependent()) {
16534     DC = computeDeclContext(SS);
16535     if (!DC) return nullptr;
16536 
16537     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16538 
16539     LookupQualifiedName(Previous, DC);
16540 
16541     // C++ [class.friend]p1: A friend of a class is a function or
16542     //   class that is not a member of the class . . .
16543     if (DC->Equals(CurContext))
16544       Diag(DS.getFriendSpecLoc(),
16545            getLangOpts().CPlusPlus11 ?
16546              diag::warn_cxx98_compat_friend_is_member :
16547              diag::err_friend_is_member);
16548 
16549     if (D.isFunctionDefinition()) {
16550       // C++ [class.friend]p6:
16551       //   A function can be defined in a friend declaration of a class if and
16552       //   only if the class is a non-local class (9.8), the function name is
16553       //   unqualified, and the function has namespace scope.
16554       //
16555       // FIXME: We should only do this if the scope specifier names the
16556       // innermost enclosing namespace; otherwise the fixit changes the
16557       // meaning of the code.
16558       SemaDiagnosticBuilder DB
16559         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16560 
16561       DB << SS.getScopeRep();
16562       if (DC->isFileContext())
16563         DB << FixItHint::CreateRemoval(SS.getRange());
16564       SS.clear();
16565     }
16566 
16567   //   - There's a scope specifier that does not match any template
16568   //     parameter lists, in which case we use some arbitrary context,
16569   //     create a method or method template, and wait for instantiation.
16570   //   - There's a scope specifier that does match some template
16571   //     parameter lists, which we don't handle right now.
16572   } else {
16573     if (D.isFunctionDefinition()) {
16574       // C++ [class.friend]p6:
16575       //   A function can be defined in a friend declaration of a class if and
16576       //   only if the class is a non-local class (9.8), the function name is
16577       //   unqualified, and the function has namespace scope.
16578       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16579         << SS.getScopeRep();
16580     }
16581 
16582     DC = CurContext;
16583     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16584   }
16585 
16586   if (!DC->isRecord()) {
16587     int DiagArg = -1;
16588     switch (D.getName().getKind()) {
16589     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16590     case UnqualifiedIdKind::IK_ConstructorName:
16591       DiagArg = 0;
16592       break;
16593     case UnqualifiedIdKind::IK_DestructorName:
16594       DiagArg = 1;
16595       break;
16596     case UnqualifiedIdKind::IK_ConversionFunctionId:
16597       DiagArg = 2;
16598       break;
16599     case UnqualifiedIdKind::IK_DeductionGuideName:
16600       DiagArg = 3;
16601       break;
16602     case UnqualifiedIdKind::IK_Identifier:
16603     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16604     case UnqualifiedIdKind::IK_LiteralOperatorId:
16605     case UnqualifiedIdKind::IK_OperatorFunctionId:
16606     case UnqualifiedIdKind::IK_TemplateId:
16607       break;
16608     }
16609     // This implies that it has to be an operator or function.
16610     if (DiagArg >= 0) {
16611       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16612       return nullptr;
16613     }
16614   }
16615 
16616   // FIXME: This is an egregious hack to cope with cases where the scope stack
16617   // does not contain the declaration context, i.e., in an out-of-line
16618   // definition of a class.
16619   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16620   if (!DCScope) {
16621     FakeDCScope.setEntity(DC);
16622     DCScope = &FakeDCScope;
16623   }
16624 
16625   bool AddToScope = true;
16626   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16627                                           TemplateParams, AddToScope);
16628   if (!ND) return nullptr;
16629 
16630   assert(ND->getLexicalDeclContext() == CurContext);
16631 
16632   // If we performed typo correction, we might have added a scope specifier
16633   // and changed the decl context.
16634   DC = ND->getDeclContext();
16635 
16636   // Add the function declaration to the appropriate lookup tables,
16637   // adjusting the redeclarations list as necessary.  We don't
16638   // want to do this yet if the friending class is dependent.
16639   //
16640   // Also update the scope-based lookup if the target context's
16641   // lookup context is in lexical scope.
16642   if (!CurContext->isDependentContext()) {
16643     DC = DC->getRedeclContext();
16644     DC->makeDeclVisibleInContext(ND);
16645     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16646       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16647   }
16648 
16649   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16650                                        D.getIdentifierLoc(), ND,
16651                                        DS.getFriendSpecLoc());
16652   FrD->setAccess(AS_public);
16653   CurContext->addDecl(FrD);
16654 
16655   if (ND->isInvalidDecl()) {
16656     FrD->setInvalidDecl();
16657   } else {
16658     if (DC->isRecord()) CheckFriendAccess(ND);
16659 
16660     FunctionDecl *FD;
16661     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16662       FD = FTD->getTemplatedDecl();
16663     else
16664       FD = cast<FunctionDecl>(ND);
16665 
16666     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16667     // default argument expression, that declaration shall be a definition
16668     // and shall be the only declaration of the function or function
16669     // template in the translation unit.
16670     if (functionDeclHasDefaultArgument(FD)) {
16671       // We can't look at FD->getPreviousDecl() because it may not have been set
16672       // if we're in a dependent context. If the function is known to be a
16673       // redeclaration, we will have narrowed Previous down to the right decl.
16674       if (D.isRedeclaration()) {
16675         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16676         Diag(Previous.getRepresentativeDecl()->getLocation(),
16677              diag::note_previous_declaration);
16678       } else if (!D.isFunctionDefinition())
16679         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16680     }
16681 
16682     // Mark templated-scope function declarations as unsupported.
16683     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16684       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16685         << SS.getScopeRep() << SS.getRange()
16686         << cast<CXXRecordDecl>(CurContext);
16687       FrD->setUnsupportedFriend(true);
16688     }
16689   }
16690 
16691   return ND;
16692 }
16693 
16694 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16695   AdjustDeclIfTemplate(Dcl);
16696 
16697   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16698   if (!Fn) {
16699     Diag(DelLoc, diag::err_deleted_non_function);
16700     return;
16701   }
16702 
16703   // Deleted function does not have a body.
16704   Fn->setWillHaveBody(false);
16705 
16706   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16707     // Don't consider the implicit declaration we generate for explicit
16708     // specializations. FIXME: Do not generate these implicit declarations.
16709     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16710          Prev->getPreviousDecl()) &&
16711         !Prev->isDefined()) {
16712       Diag(DelLoc, diag::err_deleted_decl_not_first);
16713       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16714            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16715                               : diag::note_previous_declaration);
16716       // We can't recover from this; the declaration might have already
16717       // been used.
16718       Fn->setInvalidDecl();
16719       return;
16720     }
16721 
16722     // To maintain the invariant that functions are only deleted on their first
16723     // declaration, mark the implicitly-instantiated declaration of the
16724     // explicitly-specialized function as deleted instead of marking the
16725     // instantiated redeclaration.
16726     Fn = Fn->getCanonicalDecl();
16727   }
16728 
16729   // dllimport/dllexport cannot be deleted.
16730   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16731     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16732     Fn->setInvalidDecl();
16733   }
16734 
16735   // C++11 [basic.start.main]p3:
16736   //   A program that defines main as deleted [...] is ill-formed.
16737   if (Fn->isMain())
16738     Diag(DelLoc, diag::err_deleted_main);
16739 
16740   // C++11 [dcl.fct.def.delete]p4:
16741   //  A deleted function is implicitly inline.
16742   Fn->setImplicitlyInline();
16743   Fn->setDeletedAsWritten();
16744 }
16745 
16746 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16747   if (!Dcl || Dcl->isInvalidDecl())
16748     return;
16749 
16750   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16751   if (!FD) {
16752     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16753       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16754         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16755         return;
16756       }
16757     }
16758 
16759     Diag(DefaultLoc, diag::err_default_special_members)
16760         << getLangOpts().CPlusPlus20;
16761     return;
16762   }
16763 
16764   // Reject if this can't possibly be a defaultable function.
16765   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16766   if (!DefKind &&
16767       // A dependent function that doesn't locally look defaultable can
16768       // still instantiate to a defaultable function if it's a constructor
16769       // or assignment operator.
16770       (!FD->isDependentContext() ||
16771        (!isa<CXXConstructorDecl>(FD) &&
16772         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16773     Diag(DefaultLoc, diag::err_default_special_members)
16774         << getLangOpts().CPlusPlus20;
16775     return;
16776   }
16777 
16778   if (DefKind.isComparison() &&
16779       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16780     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16781         << (int)DefKind.asComparison();
16782     return;
16783   }
16784 
16785   // Issue compatibility warning. We already warned if the operator is
16786   // 'operator<=>' when parsing the '<=>' token.
16787   if (DefKind.isComparison() &&
16788       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16789     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16790                          ? diag::warn_cxx17_compat_defaulted_comparison
16791                          : diag::ext_defaulted_comparison);
16792   }
16793 
16794   FD->setDefaulted();
16795   FD->setExplicitlyDefaulted();
16796 
16797   // Defer checking functions that are defaulted in a dependent context.
16798   if (FD->isDependentContext())
16799     return;
16800 
16801   // Unset that we will have a body for this function. We might not,
16802   // if it turns out to be trivial, and we don't need this marking now
16803   // that we've marked it as defaulted.
16804   FD->setWillHaveBody(false);
16805 
16806   // If this definition appears within the record, do the checking when
16807   // the record is complete. This is always the case for a defaulted
16808   // comparison.
16809   if (DefKind.isComparison())
16810     return;
16811   auto *MD = cast<CXXMethodDecl>(FD);
16812 
16813   const FunctionDecl *Primary = FD;
16814   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16815     // Ask the template instantiation pattern that actually had the
16816     // '= default' on it.
16817     Primary = Pattern;
16818 
16819   // If the method was defaulted on its first declaration, we will have
16820   // already performed the checking in CheckCompletedCXXClass. Such a
16821   // declaration doesn't trigger an implicit definition.
16822   if (Primary->getCanonicalDecl()->isDefaulted())
16823     return;
16824 
16825   // FIXME: Once we support defining comparisons out of class, check for a
16826   // defaulted comparison here.
16827   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16828     MD->setInvalidDecl();
16829   else
16830     DefineDefaultedFunction(*this, MD, DefaultLoc);
16831 }
16832 
16833 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16834   for (Stmt *SubStmt : S->children()) {
16835     if (!SubStmt)
16836       continue;
16837     if (isa<ReturnStmt>(SubStmt))
16838       Self.Diag(SubStmt->getBeginLoc(),
16839                 diag::err_return_in_constructor_handler);
16840     if (!isa<Expr>(SubStmt))
16841       SearchForReturnInStmt(Self, SubStmt);
16842   }
16843 }
16844 
16845 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16846   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16847     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16848     SearchForReturnInStmt(*this, Handler);
16849   }
16850 }
16851 
16852 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16853                                              const CXXMethodDecl *Old) {
16854   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16855   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16856 
16857   if (OldFT->hasExtParameterInfos()) {
16858     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16859       // A parameter of the overriding method should be annotated with noescape
16860       // if the corresponding parameter of the overridden method is annotated.
16861       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16862           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16863         Diag(New->getParamDecl(I)->getLocation(),
16864              diag::warn_overriding_method_missing_noescape);
16865         Diag(Old->getParamDecl(I)->getLocation(),
16866              diag::note_overridden_marked_noescape);
16867       }
16868   }
16869 
16870   // Virtual overrides must have the same code_seg.
16871   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16872   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16873   if ((NewCSA || OldCSA) &&
16874       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16875     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16876     Diag(Old->getLocation(), diag::note_previous_declaration);
16877     return true;
16878   }
16879 
16880   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16881 
16882   // If the calling conventions match, everything is fine
16883   if (NewCC == OldCC)
16884     return false;
16885 
16886   // If the calling conventions mismatch because the new function is static,
16887   // suppress the calling convention mismatch error; the error about static
16888   // function override (err_static_overrides_virtual from
16889   // Sema::CheckFunctionDeclaration) is more clear.
16890   if (New->getStorageClass() == SC_Static)
16891     return false;
16892 
16893   Diag(New->getLocation(),
16894        diag::err_conflicting_overriding_cc_attributes)
16895     << New->getDeclName() << New->getType() << Old->getType();
16896   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16897   return true;
16898 }
16899 
16900 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16901                                              const CXXMethodDecl *Old) {
16902   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16903   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16904 
16905   if (Context.hasSameType(NewTy, OldTy) ||
16906       NewTy->isDependentType() || OldTy->isDependentType())
16907     return false;
16908 
16909   // Check if the return types are covariant
16910   QualType NewClassTy, OldClassTy;
16911 
16912   /// Both types must be pointers or references to classes.
16913   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16914     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16915       NewClassTy = NewPT->getPointeeType();
16916       OldClassTy = OldPT->getPointeeType();
16917     }
16918   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16919     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16920       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16921         NewClassTy = NewRT->getPointeeType();
16922         OldClassTy = OldRT->getPointeeType();
16923       }
16924     }
16925   }
16926 
16927   // The return types aren't either both pointers or references to a class type.
16928   if (NewClassTy.isNull()) {
16929     Diag(New->getLocation(),
16930          diag::err_different_return_type_for_overriding_virtual_function)
16931         << New->getDeclName() << NewTy << OldTy
16932         << New->getReturnTypeSourceRange();
16933     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16934         << Old->getReturnTypeSourceRange();
16935 
16936     return true;
16937   }
16938 
16939   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16940     // C++14 [class.virtual]p8:
16941     //   If the class type in the covariant return type of D::f differs from
16942     //   that of B::f, the class type in the return type of D::f shall be
16943     //   complete at the point of declaration of D::f or shall be the class
16944     //   type D.
16945     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16946       if (!RT->isBeingDefined() &&
16947           RequireCompleteType(New->getLocation(), NewClassTy,
16948                               diag::err_covariant_return_incomplete,
16949                               New->getDeclName()))
16950         return true;
16951     }
16952 
16953     // Check if the new class derives from the old class.
16954     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16955       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16956           << New->getDeclName() << NewTy << OldTy
16957           << New->getReturnTypeSourceRange();
16958       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16959           << Old->getReturnTypeSourceRange();
16960       return true;
16961     }
16962 
16963     // Check if we the conversion from derived to base is valid.
16964     if (CheckDerivedToBaseConversion(
16965             NewClassTy, OldClassTy,
16966             diag::err_covariant_return_inaccessible_base,
16967             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16968             New->getLocation(), New->getReturnTypeSourceRange(),
16969             New->getDeclName(), nullptr)) {
16970       // FIXME: this note won't trigger for delayed access control
16971       // diagnostics, and it's impossible to get an undelayed error
16972       // here from access control during the original parse because
16973       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16974       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16975           << Old->getReturnTypeSourceRange();
16976       return true;
16977     }
16978   }
16979 
16980   // The qualifiers of the return types must be the same.
16981   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16982     Diag(New->getLocation(),
16983          diag::err_covariant_return_type_different_qualifications)
16984         << New->getDeclName() << NewTy << OldTy
16985         << New->getReturnTypeSourceRange();
16986     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16987         << Old->getReturnTypeSourceRange();
16988     return true;
16989   }
16990 
16991 
16992   // The new class type must have the same or less qualifiers as the old type.
16993   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16994     Diag(New->getLocation(),
16995          diag::err_covariant_return_type_class_type_more_qualified)
16996         << New->getDeclName() << NewTy << OldTy
16997         << New->getReturnTypeSourceRange();
16998     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16999         << Old->getReturnTypeSourceRange();
17000     return true;
17001   }
17002 
17003   return false;
17004 }
17005 
17006 /// Mark the given method pure.
17007 ///
17008 /// \param Method the method to be marked pure.
17009 ///
17010 /// \param InitRange the source range that covers the "0" initializer.
17011 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17012   SourceLocation EndLoc = InitRange.getEnd();
17013   if (EndLoc.isValid())
17014     Method->setRangeEnd(EndLoc);
17015 
17016   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17017     Method->setPure();
17018     return false;
17019   }
17020 
17021   if (!Method->isInvalidDecl())
17022     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17023       << Method->getDeclName() << InitRange;
17024   return true;
17025 }
17026 
17027 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17028   if (D->getFriendObjectKind())
17029     Diag(D->getLocation(), diag::err_pure_friend);
17030   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17031     CheckPureMethod(M, ZeroLoc);
17032   else
17033     Diag(D->getLocation(), diag::err_illegal_initializer);
17034 }
17035 
17036 /// Determine whether the given declaration is a global variable or
17037 /// static data member.
17038 static bool isNonlocalVariable(const Decl *D) {
17039   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17040     return Var->hasGlobalStorage();
17041 
17042   return false;
17043 }
17044 
17045 /// Invoked when we are about to parse an initializer for the declaration
17046 /// 'Dcl'.
17047 ///
17048 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17049 /// static data member of class X, names should be looked up in the scope of
17050 /// class X. If the declaration had a scope specifier, a scope will have
17051 /// been created and passed in for this purpose. Otherwise, S will be null.
17052 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17053   // If there is no declaration, there was an error parsing it.
17054   if (!D || D->isInvalidDecl())
17055     return;
17056 
17057   // We will always have a nested name specifier here, but this declaration
17058   // might not be out of line if the specifier names the current namespace:
17059   //   extern int n;
17060   //   int ::n = 0;
17061   if (S && D->isOutOfLine())
17062     EnterDeclaratorContext(S, D->getDeclContext());
17063 
17064   // If we are parsing the initializer for a static data member, push a
17065   // new expression evaluation context that is associated with this static
17066   // data member.
17067   if (isNonlocalVariable(D))
17068     PushExpressionEvaluationContext(
17069         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17070 }
17071 
17072 /// Invoked after we are finished parsing an initializer for the declaration D.
17073 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17074   // If there is no declaration, there was an error parsing it.
17075   if (!D || D->isInvalidDecl())
17076     return;
17077 
17078   if (isNonlocalVariable(D))
17079     PopExpressionEvaluationContext();
17080 
17081   if (S && D->isOutOfLine())
17082     ExitDeclaratorContext(S);
17083 }
17084 
17085 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17086 /// C++ if/switch/while/for statement.
17087 /// e.g: "if (int x = f()) {...}"
17088 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17089   // C++ 6.4p2:
17090   // The declarator shall not specify a function or an array.
17091   // The type-specifier-seq shall not contain typedef and shall not declare a
17092   // new class or enumeration.
17093   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17094          "Parser allowed 'typedef' as storage class of condition decl.");
17095 
17096   Decl *Dcl = ActOnDeclarator(S, D);
17097   if (!Dcl)
17098     return true;
17099 
17100   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17101     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17102       << D.getSourceRange();
17103     return true;
17104   }
17105 
17106   return Dcl;
17107 }
17108 
17109 void Sema::LoadExternalVTableUses() {
17110   if (!ExternalSource)
17111     return;
17112 
17113   SmallVector<ExternalVTableUse, 4> VTables;
17114   ExternalSource->ReadUsedVTables(VTables);
17115   SmallVector<VTableUse, 4> NewUses;
17116   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17117     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17118       = VTablesUsed.find(VTables[I].Record);
17119     // Even if a definition wasn't required before, it may be required now.
17120     if (Pos != VTablesUsed.end()) {
17121       if (!Pos->second && VTables[I].DefinitionRequired)
17122         Pos->second = true;
17123       continue;
17124     }
17125 
17126     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17127     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17128   }
17129 
17130   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17131 }
17132 
17133 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17134                           bool DefinitionRequired) {
17135   // Ignore any vtable uses in unevaluated operands or for classes that do
17136   // not have a vtable.
17137   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17138       CurContext->isDependentContext() || isUnevaluatedContext())
17139     return;
17140   // Do not mark as used if compiling for the device outside of the target
17141   // region.
17142   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17143       !isInOpenMPDeclareTargetContext() &&
17144       !isInOpenMPTargetExecutionDirective()) {
17145     if (!DefinitionRequired)
17146       MarkVirtualMembersReferenced(Loc, Class);
17147     return;
17148   }
17149 
17150   // Try to insert this class into the map.
17151   LoadExternalVTableUses();
17152   Class = Class->getCanonicalDecl();
17153   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17154     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17155   if (!Pos.second) {
17156     // If we already had an entry, check to see if we are promoting this vtable
17157     // to require a definition. If so, we need to reappend to the VTableUses
17158     // list, since we may have already processed the first entry.
17159     if (DefinitionRequired && !Pos.first->second) {
17160       Pos.first->second = true;
17161     } else {
17162       // Otherwise, we can early exit.
17163       return;
17164     }
17165   } else {
17166     // The Microsoft ABI requires that we perform the destructor body
17167     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17168     // the deleting destructor is emitted with the vtable, not with the
17169     // destructor definition as in the Itanium ABI.
17170     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17171       CXXDestructorDecl *DD = Class->getDestructor();
17172       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17173         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17174           // If this is an out-of-line declaration, marking it referenced will
17175           // not do anything. Manually call CheckDestructor to look up operator
17176           // delete().
17177           ContextRAII SavedContext(*this, DD);
17178           CheckDestructor(DD);
17179         } else {
17180           MarkFunctionReferenced(Loc, Class->getDestructor());
17181         }
17182       }
17183     }
17184   }
17185 
17186   // Local classes need to have their virtual members marked
17187   // immediately. For all other classes, we mark their virtual members
17188   // at the end of the translation unit.
17189   if (Class->isLocalClass())
17190     MarkVirtualMembersReferenced(Loc, Class);
17191   else
17192     VTableUses.push_back(std::make_pair(Class, Loc));
17193 }
17194 
17195 bool Sema::DefineUsedVTables() {
17196   LoadExternalVTableUses();
17197   if (VTableUses.empty())
17198     return false;
17199 
17200   // Note: The VTableUses vector could grow as a result of marking
17201   // the members of a class as "used", so we check the size each
17202   // time through the loop and prefer indices (which are stable) to
17203   // iterators (which are not).
17204   bool DefinedAnything = false;
17205   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17206     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17207     if (!Class)
17208       continue;
17209     TemplateSpecializationKind ClassTSK =
17210         Class->getTemplateSpecializationKind();
17211 
17212     SourceLocation Loc = VTableUses[I].second;
17213 
17214     bool DefineVTable = true;
17215 
17216     // If this class has a key function, but that key function is
17217     // defined in another translation unit, we don't need to emit the
17218     // vtable even though we're using it.
17219     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17220     if (KeyFunction && !KeyFunction->hasBody()) {
17221       // The key function is in another translation unit.
17222       DefineVTable = false;
17223       TemplateSpecializationKind TSK =
17224           KeyFunction->getTemplateSpecializationKind();
17225       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17226              TSK != TSK_ImplicitInstantiation &&
17227              "Instantiations don't have key functions");
17228       (void)TSK;
17229     } else if (!KeyFunction) {
17230       // If we have a class with no key function that is the subject
17231       // of an explicit instantiation declaration, suppress the
17232       // vtable; it will live with the explicit instantiation
17233       // definition.
17234       bool IsExplicitInstantiationDeclaration =
17235           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17236       for (auto R : Class->redecls()) {
17237         TemplateSpecializationKind TSK
17238           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17239         if (TSK == TSK_ExplicitInstantiationDeclaration)
17240           IsExplicitInstantiationDeclaration = true;
17241         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17242           IsExplicitInstantiationDeclaration = false;
17243           break;
17244         }
17245       }
17246 
17247       if (IsExplicitInstantiationDeclaration)
17248         DefineVTable = false;
17249     }
17250 
17251     // The exception specifications for all virtual members may be needed even
17252     // if we are not providing an authoritative form of the vtable in this TU.
17253     // We may choose to emit it available_externally anyway.
17254     if (!DefineVTable) {
17255       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17256       continue;
17257     }
17258 
17259     // Mark all of the virtual members of this class as referenced, so
17260     // that we can build a vtable. Then, tell the AST consumer that a
17261     // vtable for this class is required.
17262     DefinedAnything = true;
17263     MarkVirtualMembersReferenced(Loc, Class);
17264     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17265     if (VTablesUsed[Canonical])
17266       Consumer.HandleVTable(Class);
17267 
17268     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17269     // no key function or the key function is inlined. Don't warn in C++ ABIs
17270     // that lack key functions, since the user won't be able to make one.
17271     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17272         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17273       const FunctionDecl *KeyFunctionDef = nullptr;
17274       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17275                            KeyFunctionDef->isInlined())) {
17276         Diag(Class->getLocation(),
17277              ClassTSK == TSK_ExplicitInstantiationDefinition
17278                  ? diag::warn_weak_template_vtable
17279                  : diag::warn_weak_vtable)
17280             << Class;
17281       }
17282     }
17283   }
17284   VTableUses.clear();
17285 
17286   return DefinedAnything;
17287 }
17288 
17289 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17290                                                  const CXXRecordDecl *RD) {
17291   for (const auto *I : RD->methods())
17292     if (I->isVirtual() && !I->isPure())
17293       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17294 }
17295 
17296 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17297                                         const CXXRecordDecl *RD,
17298                                         bool ConstexprOnly) {
17299   // Mark all functions which will appear in RD's vtable as used.
17300   CXXFinalOverriderMap FinalOverriders;
17301   RD->getFinalOverriders(FinalOverriders);
17302   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17303                                             E = FinalOverriders.end();
17304        I != E; ++I) {
17305     for (OverridingMethods::const_iterator OI = I->second.begin(),
17306                                            OE = I->second.end();
17307          OI != OE; ++OI) {
17308       assert(OI->second.size() > 0 && "no final overrider");
17309       CXXMethodDecl *Overrider = OI->second.front().Method;
17310 
17311       // C++ [basic.def.odr]p2:
17312       //   [...] A virtual member function is used if it is not pure. [...]
17313       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17314         MarkFunctionReferenced(Loc, Overrider);
17315     }
17316   }
17317 
17318   // Only classes that have virtual bases need a VTT.
17319   if (RD->getNumVBases() == 0)
17320     return;
17321 
17322   for (const auto &I : RD->bases()) {
17323     const auto *Base =
17324         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17325     if (Base->getNumVBases() == 0)
17326       continue;
17327     MarkVirtualMembersReferenced(Loc, Base);
17328   }
17329 }
17330 
17331 /// SetIvarInitializers - This routine builds initialization ASTs for the
17332 /// Objective-C implementation whose ivars need be initialized.
17333 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17334   if (!getLangOpts().CPlusPlus)
17335     return;
17336   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17337     SmallVector<ObjCIvarDecl*, 8> ivars;
17338     CollectIvarsToConstructOrDestruct(OID, ivars);
17339     if (ivars.empty())
17340       return;
17341     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17342     for (unsigned i = 0; i < ivars.size(); i++) {
17343       FieldDecl *Field = ivars[i];
17344       if (Field->isInvalidDecl())
17345         continue;
17346 
17347       CXXCtorInitializer *Member;
17348       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17349       InitializationKind InitKind =
17350         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17351 
17352       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17353       ExprResult MemberInit =
17354         InitSeq.Perform(*this, InitEntity, InitKind, None);
17355       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17356       // Note, MemberInit could actually come back empty if no initialization
17357       // is required (e.g., because it would call a trivial default constructor)
17358       if (!MemberInit.get() || MemberInit.isInvalid())
17359         continue;
17360 
17361       Member =
17362         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17363                                          SourceLocation(),
17364                                          MemberInit.getAs<Expr>(),
17365                                          SourceLocation());
17366       AllToInit.push_back(Member);
17367 
17368       // Be sure that the destructor is accessible and is marked as referenced.
17369       if (const RecordType *RecordTy =
17370               Context.getBaseElementType(Field->getType())
17371                   ->getAs<RecordType>()) {
17372         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17373         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17374           MarkFunctionReferenced(Field->getLocation(), Destructor);
17375           CheckDestructorAccess(Field->getLocation(), Destructor,
17376                             PDiag(diag::err_access_dtor_ivar)
17377                               << Context.getBaseElementType(Field->getType()));
17378         }
17379       }
17380     }
17381     ObjCImplementation->setIvarInitializers(Context,
17382                                             AllToInit.data(), AllToInit.size());
17383   }
17384 }
17385 
17386 static
17387 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17388                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17389                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17390                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17391                            Sema &S) {
17392   if (Ctor->isInvalidDecl())
17393     return;
17394 
17395   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17396 
17397   // Target may not be determinable yet, for instance if this is a dependent
17398   // call in an uninstantiated template.
17399   if (Target) {
17400     const FunctionDecl *FNTarget = nullptr;
17401     (void)Target->hasBody(FNTarget);
17402     Target = const_cast<CXXConstructorDecl*>(
17403       cast_or_null<CXXConstructorDecl>(FNTarget));
17404   }
17405 
17406   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17407                      // Avoid dereferencing a null pointer here.
17408                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17409 
17410   if (!Current.insert(Canonical).second)
17411     return;
17412 
17413   // We know that beyond here, we aren't chaining into a cycle.
17414   if (!Target || !Target->isDelegatingConstructor() ||
17415       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17416     Valid.insert(Current.begin(), Current.end());
17417     Current.clear();
17418   // We've hit a cycle.
17419   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17420              Current.count(TCanonical)) {
17421     // If we haven't diagnosed this cycle yet, do so now.
17422     if (!Invalid.count(TCanonical)) {
17423       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17424              diag::warn_delegating_ctor_cycle)
17425         << Ctor;
17426 
17427       // Don't add a note for a function delegating directly to itself.
17428       if (TCanonical != Canonical)
17429         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17430 
17431       CXXConstructorDecl *C = Target;
17432       while (C->getCanonicalDecl() != Canonical) {
17433         const FunctionDecl *FNTarget = nullptr;
17434         (void)C->getTargetConstructor()->hasBody(FNTarget);
17435         assert(FNTarget && "Ctor cycle through bodiless function");
17436 
17437         C = const_cast<CXXConstructorDecl*>(
17438           cast<CXXConstructorDecl>(FNTarget));
17439         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17440       }
17441     }
17442 
17443     Invalid.insert(Current.begin(), Current.end());
17444     Current.clear();
17445   } else {
17446     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17447   }
17448 }
17449 
17450 
17451 void Sema::CheckDelegatingCtorCycles() {
17452   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17453 
17454   for (DelegatingCtorDeclsType::iterator
17455          I = DelegatingCtorDecls.begin(ExternalSource),
17456          E = DelegatingCtorDecls.end();
17457        I != E; ++I)
17458     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17459 
17460   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17461     (*CI)->setInvalidDecl();
17462 }
17463 
17464 namespace {
17465   /// AST visitor that finds references to the 'this' expression.
17466   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17467     Sema &S;
17468 
17469   public:
17470     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17471 
17472     bool VisitCXXThisExpr(CXXThisExpr *E) {
17473       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17474         << E->isImplicit();
17475       return false;
17476     }
17477   };
17478 }
17479 
17480 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17481   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17482   if (!TSInfo)
17483     return false;
17484 
17485   TypeLoc TL = TSInfo->getTypeLoc();
17486   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17487   if (!ProtoTL)
17488     return false;
17489 
17490   // C++11 [expr.prim.general]p3:
17491   //   [The expression this] shall not appear before the optional
17492   //   cv-qualifier-seq and it shall not appear within the declaration of a
17493   //   static member function (although its type and value category are defined
17494   //   within a static member function as they are within a non-static member
17495   //   function). [ Note: this is because declaration matching does not occur
17496   //  until the complete declarator is known. - end note ]
17497   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17498   FindCXXThisExpr Finder(*this);
17499 
17500   // If the return type came after the cv-qualifier-seq, check it now.
17501   if (Proto->hasTrailingReturn() &&
17502       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17503     return true;
17504 
17505   // Check the exception specification.
17506   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17507     return true;
17508 
17509   // Check the trailing requires clause
17510   if (Expr *E = Method->getTrailingRequiresClause())
17511     if (!Finder.TraverseStmt(E))
17512       return true;
17513 
17514   return checkThisInStaticMemberFunctionAttributes(Method);
17515 }
17516 
17517 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17518   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17519   if (!TSInfo)
17520     return false;
17521 
17522   TypeLoc TL = TSInfo->getTypeLoc();
17523   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17524   if (!ProtoTL)
17525     return false;
17526 
17527   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17528   FindCXXThisExpr Finder(*this);
17529 
17530   switch (Proto->getExceptionSpecType()) {
17531   case EST_Unparsed:
17532   case EST_Uninstantiated:
17533   case EST_Unevaluated:
17534   case EST_BasicNoexcept:
17535   case EST_NoThrow:
17536   case EST_DynamicNone:
17537   case EST_MSAny:
17538   case EST_None:
17539     break;
17540 
17541   case EST_DependentNoexcept:
17542   case EST_NoexceptFalse:
17543   case EST_NoexceptTrue:
17544     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17545       return true;
17546     LLVM_FALLTHROUGH;
17547 
17548   case EST_Dynamic:
17549     for (const auto &E : Proto->exceptions()) {
17550       if (!Finder.TraverseType(E))
17551         return true;
17552     }
17553     break;
17554   }
17555 
17556   return false;
17557 }
17558 
17559 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17560   FindCXXThisExpr Finder(*this);
17561 
17562   // Check attributes.
17563   for (const auto *A : Method->attrs()) {
17564     // FIXME: This should be emitted by tblgen.
17565     Expr *Arg = nullptr;
17566     ArrayRef<Expr *> Args;
17567     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17568       Arg = G->getArg();
17569     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17570       Arg = G->getArg();
17571     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17572       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17573     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17574       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17575     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17576       Arg = ETLF->getSuccessValue();
17577       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17578     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17579       Arg = STLF->getSuccessValue();
17580       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17581     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17582       Arg = LR->getArg();
17583     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17584       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17585     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17586       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17587     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17588       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17589     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17590       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17591     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17592       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17593 
17594     if (Arg && !Finder.TraverseStmt(Arg))
17595       return true;
17596 
17597     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17598       if (!Finder.TraverseStmt(Args[I]))
17599         return true;
17600     }
17601   }
17602 
17603   return false;
17604 }
17605 
17606 void Sema::checkExceptionSpecification(
17607     bool IsTopLevel, ExceptionSpecificationType EST,
17608     ArrayRef<ParsedType> DynamicExceptions,
17609     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17610     SmallVectorImpl<QualType> &Exceptions,
17611     FunctionProtoType::ExceptionSpecInfo &ESI) {
17612   Exceptions.clear();
17613   ESI.Type = EST;
17614   if (EST == EST_Dynamic) {
17615     Exceptions.reserve(DynamicExceptions.size());
17616     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17617       // FIXME: Preserve type source info.
17618       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17619 
17620       if (IsTopLevel) {
17621         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17622         collectUnexpandedParameterPacks(ET, Unexpanded);
17623         if (!Unexpanded.empty()) {
17624           DiagnoseUnexpandedParameterPacks(
17625               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17626               Unexpanded);
17627           continue;
17628         }
17629       }
17630 
17631       // Check that the type is valid for an exception spec, and
17632       // drop it if not.
17633       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17634         Exceptions.push_back(ET);
17635     }
17636     ESI.Exceptions = Exceptions;
17637     return;
17638   }
17639 
17640   if (isComputedNoexcept(EST)) {
17641     assert((NoexceptExpr->isTypeDependent() ||
17642             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17643             Context.BoolTy) &&
17644            "Parser should have made sure that the expression is boolean");
17645     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17646       ESI.Type = EST_BasicNoexcept;
17647       return;
17648     }
17649 
17650     ESI.NoexceptExpr = NoexceptExpr;
17651     return;
17652   }
17653 }
17654 
17655 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17656              ExceptionSpecificationType EST,
17657              SourceRange SpecificationRange,
17658              ArrayRef<ParsedType> DynamicExceptions,
17659              ArrayRef<SourceRange> DynamicExceptionRanges,
17660              Expr *NoexceptExpr) {
17661   if (!MethodD)
17662     return;
17663 
17664   // Dig out the method we're referring to.
17665   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17666     MethodD = FunTmpl->getTemplatedDecl();
17667 
17668   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17669   if (!Method)
17670     return;
17671 
17672   // Check the exception specification.
17673   llvm::SmallVector<QualType, 4> Exceptions;
17674   FunctionProtoType::ExceptionSpecInfo ESI;
17675   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17676                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17677                               ESI);
17678 
17679   // Update the exception specification on the function type.
17680   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17681 
17682   if (Method->isStatic())
17683     checkThisInStaticMemberFunctionExceptionSpec(Method);
17684 
17685   if (Method->isVirtual()) {
17686     // Check overrides, which we previously had to delay.
17687     for (const CXXMethodDecl *O : Method->overridden_methods())
17688       CheckOverridingFunctionExceptionSpec(Method, O);
17689   }
17690 }
17691 
17692 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17693 ///
17694 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17695                                        SourceLocation DeclStart, Declarator &D,
17696                                        Expr *BitWidth,
17697                                        InClassInitStyle InitStyle,
17698                                        AccessSpecifier AS,
17699                                        const ParsedAttr &MSPropertyAttr) {
17700   IdentifierInfo *II = D.getIdentifier();
17701   if (!II) {
17702     Diag(DeclStart, diag::err_anonymous_property);
17703     return nullptr;
17704   }
17705   SourceLocation Loc = D.getIdentifierLoc();
17706 
17707   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17708   QualType T = TInfo->getType();
17709   if (getLangOpts().CPlusPlus) {
17710     CheckExtraCXXDefaultArguments(D);
17711 
17712     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17713                                         UPPC_DataMemberType)) {
17714       D.setInvalidType();
17715       T = Context.IntTy;
17716       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17717     }
17718   }
17719 
17720   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17721 
17722   if (D.getDeclSpec().isInlineSpecified())
17723     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17724         << getLangOpts().CPlusPlus17;
17725   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17726     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17727          diag::err_invalid_thread)
17728       << DeclSpec::getSpecifierName(TSCS);
17729 
17730   // Check to see if this name was declared as a member previously
17731   NamedDecl *PrevDecl = nullptr;
17732   LookupResult Previous(*this, II, Loc, LookupMemberName,
17733                         ForVisibleRedeclaration);
17734   LookupName(Previous, S);
17735   switch (Previous.getResultKind()) {
17736   case LookupResult::Found:
17737   case LookupResult::FoundUnresolvedValue:
17738     PrevDecl = Previous.getAsSingle<NamedDecl>();
17739     break;
17740 
17741   case LookupResult::FoundOverloaded:
17742     PrevDecl = Previous.getRepresentativeDecl();
17743     break;
17744 
17745   case LookupResult::NotFound:
17746   case LookupResult::NotFoundInCurrentInstantiation:
17747   case LookupResult::Ambiguous:
17748     break;
17749   }
17750 
17751   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17752     // Maybe we will complain about the shadowed template parameter.
17753     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17754     // Just pretend that we didn't see the previous declaration.
17755     PrevDecl = nullptr;
17756   }
17757 
17758   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17759     PrevDecl = nullptr;
17760 
17761   SourceLocation TSSL = D.getBeginLoc();
17762   MSPropertyDecl *NewPD =
17763       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17764                              MSPropertyAttr.getPropertyDataGetter(),
17765                              MSPropertyAttr.getPropertyDataSetter());
17766   ProcessDeclAttributes(TUScope, NewPD, D);
17767   NewPD->setAccess(AS);
17768 
17769   if (NewPD->isInvalidDecl())
17770     Record->setInvalidDecl();
17771 
17772   if (D.getDeclSpec().isModulePrivateSpecified())
17773     NewPD->setModulePrivate();
17774 
17775   if (NewPD->isInvalidDecl() && PrevDecl) {
17776     // Don't introduce NewFD into scope; there's already something
17777     // with the same name in the same scope.
17778   } else if (II) {
17779     PushOnScopeChains(NewPD, S);
17780   } else
17781     Record->addDecl(NewPD);
17782 
17783   return NewPD;
17784 }
17785 
17786 void Sema::ActOnStartFunctionDeclarationDeclarator(
17787     Declarator &Declarator, unsigned TemplateParameterDepth) {
17788   auto &Info = InventedParameterInfos.emplace_back();
17789   TemplateParameterList *ExplicitParams = nullptr;
17790   ArrayRef<TemplateParameterList *> ExplicitLists =
17791       Declarator.getTemplateParameterLists();
17792   if (!ExplicitLists.empty()) {
17793     bool IsMemberSpecialization, IsInvalid;
17794     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17795         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17796         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17797         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17798         /*SuppressDiagnostic=*/true);
17799   }
17800   if (ExplicitParams) {
17801     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17802     for (NamedDecl *Param : *ExplicitParams)
17803       Info.TemplateParams.push_back(Param);
17804     Info.NumExplicitTemplateParams = ExplicitParams->size();
17805   } else {
17806     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17807     Info.NumExplicitTemplateParams = 0;
17808   }
17809 }
17810 
17811 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17812   auto &FSI = InventedParameterInfos.back();
17813   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17814     if (FSI.NumExplicitTemplateParams != 0) {
17815       TemplateParameterList *ExplicitParams =
17816           Declarator.getTemplateParameterLists().back();
17817       Declarator.setInventedTemplateParameterList(
17818           TemplateParameterList::Create(
17819               Context, ExplicitParams->getTemplateLoc(),
17820               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17821               ExplicitParams->getRAngleLoc(),
17822               ExplicitParams->getRequiresClause()));
17823     } else {
17824       Declarator.setInventedTemplateParameterList(
17825           TemplateParameterList::Create(
17826               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17827               SourceLocation(), /*RequiresClause=*/nullptr));
17828     }
17829   }
17830   InventedParameterInfos.pop_back();
17831 }
17832