1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include <map>
46 #include <set>
47 
48 using namespace clang;
49 
50 //===----------------------------------------------------------------------===//
51 // CheckDefaultArgumentVisitor
52 //===----------------------------------------------------------------------===//
53 
54 namespace {
55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56 /// the default argument of a parameter to determine whether it
57 /// contains any ill-formed subexpressions. For example, this will
58 /// diagnose the use of local variables or parameters within the
59 /// default argument expression.
60 class CheckDefaultArgumentVisitor
61     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62   Sema &S;
63   const Expr *DefaultArg;
64 
65 public:
66   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67       : S(S), DefaultArg(DefaultArg) {}
68 
69   bool VisitExpr(const Expr *Node);
70   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72   bool VisitLambdaExpr(const LambdaExpr *Lambda);
73   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74 };
75 
76 /// VisitExpr - Visit all of the children of this expression.
77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78   bool IsInvalid = false;
79   for (const Stmt *SubStmt : Node->children())
80     IsInvalid |= Visit(SubStmt);
81   return IsInvalid;
82 }
83 
84 /// VisitDeclRefExpr - Visit a reference to a declaration, to
85 /// determine whether this declaration can be used in the default
86 /// argument expression.
87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88   const NamedDecl *Decl = DRE->getDecl();
89   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90     // C++ [dcl.fct.default]p9:
91     //   [...] parameters of a function shall not be used in default
92     //   argument expressions, even if they are not evaluated. [...]
93     //
94     // C++17 [dcl.fct.default]p9 (by CWG 2082):
95     //   [...] A parameter shall not appear as a potentially-evaluated
96     //   expression in a default argument. [...]
97     //
98     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99       return S.Diag(DRE->getBeginLoc(),
100                     diag::err_param_default_argument_references_param)
101              << Param->getDeclName() << DefaultArg->getSourceRange();
102   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103     // C++ [dcl.fct.default]p7:
104     //   Local variables shall not be used in default argument
105     //   expressions.
106     //
107     // C++17 [dcl.fct.default]p7 (by CWG 2082):
108     //   A local variable shall not appear as a potentially-evaluated
109     //   expression in a default argument.
110     //
111     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113     //
114     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115       return S.Diag(DRE->getBeginLoc(),
116                     diag::err_param_default_argument_references_local)
117              << VDecl->getDeclName() << DefaultArg->getSourceRange();
118   }
119 
120   return false;
121 }
122 
123 /// VisitCXXThisExpr - Visit a C++ "this" expression.
124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125   // C++ [dcl.fct.default]p8:
126   //   The keyword this shall not be used in a default argument of a
127   //   member function.
128   return S.Diag(ThisE->getBeginLoc(),
129                 diag::err_param_default_argument_references_this)
130          << ThisE->getSourceRange();
131 }
132 
133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134     const PseudoObjectExpr *POE) {
135   bool Invalid = false;
136   for (const Expr *E : POE->semantics()) {
137     // Look through bindings.
138     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139       E = OVE->getSourceExpr();
140       assert(E && "pseudo-object binding without source expression?");
141     }
142 
143     Invalid |= Visit(E);
144   }
145   return Invalid;
146 }
147 
148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149   // C++11 [expr.lambda.prim]p13:
150   //   A lambda-expression appearing in a default argument shall not
151   //   implicitly or explicitly capture any entity.
152   if (Lambda->capture_begin() == Lambda->capture_end())
153     return false;
154 
155   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156 }
157 } // namespace
158 
159 void
160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161                                                  const CXXMethodDecl *Method) {
162   // If we have an MSAny spec already, don't bother.
163   if (!Method || ComputedEST == EST_MSAny)
164     return;
165 
166   const FunctionProtoType *Proto
167     = Method->getType()->getAs<FunctionProtoType>();
168   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169   if (!Proto)
170     return;
171 
172   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173 
174   // If we have a throw-all spec at this point, ignore the function.
175   if (ComputedEST == EST_None)
176     return;
177 
178   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179     EST = EST_BasicNoexcept;
180 
181   switch (EST) {
182   case EST_Unparsed:
183   case EST_Uninstantiated:
184   case EST_Unevaluated:
185     llvm_unreachable("should not see unresolved exception specs here");
186 
187   // If this function can throw any exceptions, make a note of that.
188   case EST_MSAny:
189   case EST_None:
190     // FIXME: Whichever we see last of MSAny and None determines our result.
191     // We should make a consistent, order-independent choice here.
192     ClearExceptions();
193     ComputedEST = EST;
194     return;
195   case EST_NoexceptFalse:
196     ClearExceptions();
197     ComputedEST = EST_None;
198     return;
199   // FIXME: If the call to this decl is using any of its default arguments, we
200   // need to search them for potentially-throwing calls.
201   // If this function has a basic noexcept, it doesn't affect the outcome.
202   case EST_BasicNoexcept:
203   case EST_NoexceptTrue:
204   case EST_NoThrow:
205     return;
206   // If we're still at noexcept(true) and there's a throw() callee,
207   // change to that specification.
208   case EST_DynamicNone:
209     if (ComputedEST == EST_BasicNoexcept)
210       ComputedEST = EST_DynamicNone;
211     return;
212   case EST_DependentNoexcept:
213     llvm_unreachable(
214         "should not generate implicit declarations for dependent cases");
215   case EST_Dynamic:
216     break;
217   }
218   assert(EST == EST_Dynamic && "EST case not considered earlier.");
219   assert(ComputedEST != EST_None &&
220          "Shouldn't collect exceptions when throw-all is guaranteed.");
221   ComputedEST = EST_Dynamic;
222   // Record the exceptions in this function's exception specification.
223   for (const auto &E : Proto->exceptions())
224     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225       Exceptions.push_back(E);
226 }
227 
228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229   if (!S || ComputedEST == EST_MSAny)
230     return;
231 
232   // FIXME:
233   //
234   // C++0x [except.spec]p14:
235   //   [An] implicit exception-specification specifies the type-id T if and
236   // only if T is allowed by the exception-specification of a function directly
237   // invoked by f's implicit definition; f shall allow all exceptions if any
238   // function it directly invokes allows all exceptions, and f shall allow no
239   // exceptions if every function it directly invokes allows no exceptions.
240   //
241   // Note in particular that if an implicit exception-specification is generated
242   // for a function containing a throw-expression, that specification can still
243   // be noexcept(true).
244   //
245   // Note also that 'directly invoked' is not defined in the standard, and there
246   // is no indication that we should only consider potentially-evaluated calls.
247   //
248   // Ultimately we should implement the intent of the standard: the exception
249   // specification should be the set of exceptions which can be thrown by the
250   // implicit definition. For now, we assume that any non-nothrow expression can
251   // throw any exception.
252 
253   if (Self->canThrow(S))
254     ComputedEST = EST_None;
255 }
256 
257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258                                              Expr *Arg,
259                                              SourceLocation EqualLoc) {
260   if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                           diag::err_typecheck_decl_incomplete_type))
262     return true;
263 
264   // C++ [dcl.fct.default]p5
265   //   A default argument expression is implicitly converted (clause
266   //   4) to the parameter type. The default argument expression has
267   //   the same semantic constraints as the initializer expression in
268   //   a declaration of a variable of the parameter type, using the
269   //   copy-initialization semantics (8.5).
270   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                     Param);
272   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                            EqualLoc);
274   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276   if (Result.isInvalid())
277     return true;
278   Arg = Result.getAs<Expr>();
279 
280   CheckCompletedExpr(Arg, EqualLoc);
281   Arg = MaybeCreateExprWithCleanups(Arg);
282 
283   return Arg;
284 }
285 
286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                    SourceLocation EqualLoc) {
288   // Add the default argument to the parameter
289   Param->setDefaultArg(Arg);
290 
291   // We have already instantiated this parameter; provide each of the
292   // instantiations with the uninstantiated default argument.
293   UnparsedDefaultArgInstantiationsMap::iterator InstPos
294     = UnparsedDefaultArgInstantiations.find(Param);
295   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299     // We're done tracking this parameter's instantiations.
300     UnparsedDefaultArgInstantiations.erase(InstPos);
301   }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                 Expr *DefaultArg) {
310   if (!param || !DefaultArg)
311     return;
312 
313   ParmVarDecl *Param = cast<ParmVarDecl>(param);
314   UnparsedDefaultArgLocs.erase(Param);
315 
316   auto Fail = [&] {
317     Param->setInvalidDecl();
318     Param->setDefaultArg(new (Context) OpaqueValueExpr(
319         EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
320   };
321 
322   // Default arguments are only permitted in C++
323   if (!getLangOpts().CPlusPlus) {
324     Diag(EqualLoc, diag::err_param_default_argument)
325       << DefaultArg->getSourceRange();
326     return Fail();
327   }
328 
329   // Check for unexpanded parameter packs.
330   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331     return Fail();
332   }
333 
334   // C++11 [dcl.fct.default]p3
335   //   A default argument expression [...] shall not be specified for a
336   //   parameter pack.
337   if (Param->isParameterPack()) {
338     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339         << DefaultArg->getSourceRange();
340     // Recover by discarding the default argument.
341     Param->setDefaultArg(nullptr);
342     return;
343   }
344 
345   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346   if (Result.isInvalid())
347     return Fail();
348 
349   DefaultArg = Result.getAs<Expr>();
350 
351   // Check that the default argument is well-formed
352   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353   if (DefaultArgChecker.Visit(DefaultArg))
354     return Fail();
355 
356   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                              SourceLocation EqualLoc,
365                                              SourceLocation ArgLoc) {
366   if (!param)
367     return;
368 
369   ParmVarDecl *Param = cast<ParmVarDecl>(param);
370   Param->setUnparsedDefaultArg();
371   UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                           SourceLocation EqualLoc) {
378   if (!param)
379     return;
380 
381   ParmVarDecl *Param = cast<ParmVarDecl>(param);
382   Param->setInvalidDecl();
383   UnparsedDefaultArgLocs.erase(Param);
384   Param->setDefaultArg(new(Context)
385                        OpaqueValueExpr(EqualLoc,
386                                        Param->getType().getNonReferenceType(),
387                                        VK_RValue));
388 }
389 
390 /// CheckExtraCXXDefaultArguments - Check for any extra default
391 /// arguments in the declarator, which is not a function declaration
392 /// or definition and therefore is not permitted to have default
393 /// arguments. This routine should be invoked for every declarator
394 /// that is not a function declaration or definition.
395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396   // C++ [dcl.fct.default]p3
397   //   A default argument expression shall be specified only in the
398   //   parameter-declaration-clause of a function declaration or in a
399   //   template-parameter (14.1). It shall not be specified for a
400   //   parameter pack. If it is specified in a
401   //   parameter-declaration-clause, it shall not occur within a
402   //   declarator or abstract-declarator of a parameter-declaration.
403   bool MightBeFunction = D.isFunctionDeclarationContext();
404   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405     DeclaratorChunk &chunk = D.getTypeObject(i);
406     if (chunk.Kind == DeclaratorChunk::Function) {
407       if (MightBeFunction) {
408         // This is a function declaration. It can have default arguments, but
409         // keep looking in case its return type is a function type with default
410         // arguments.
411         MightBeFunction = false;
412         continue;
413       }
414       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415            ++argIdx) {
416         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417         if (Param->hasUnparsedDefaultArg()) {
418           std::unique_ptr<CachedTokens> Toks =
419               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420           SourceRange SR;
421           if (Toks->size() > 1)
422             SR = SourceRange((*Toks)[1].getLocation(),
423                              Toks->back().getLocation());
424           else
425             SR = UnparsedDefaultArgLocs[Param];
426           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427             << SR;
428         } else if (Param->getDefaultArg()) {
429           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430             << Param->getDefaultArg()->getSourceRange();
431           Param->setDefaultArg(nullptr);
432         }
433       }
434     } else if (chunk.Kind != DeclaratorChunk::Paren) {
435       MightBeFunction = false;
436     }
437   }
438 }
439 
440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441   return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443   });
444 }
445 
446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
447 /// function, once we already know that they have the same
448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449 /// error, false otherwise.
450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451                                 Scope *S) {
452   bool Invalid = false;
453 
454   // The declaration context corresponding to the scope is the semantic
455   // parent, unless this is a local function declaration, in which case
456   // it is that surrounding function.
457   DeclContext *ScopeDC = New->isLocalExternDecl()
458                              ? New->getLexicalDeclContext()
459                              : New->getDeclContext();
460 
461   // Find the previous declaration for the purpose of default arguments.
462   FunctionDecl *PrevForDefaultArgs = Old;
463   for (/**/; PrevForDefaultArgs;
464        // Don't bother looking back past the latest decl if this is a local
465        // extern declaration; nothing else could work.
466        PrevForDefaultArgs = New->isLocalExternDecl()
467                                 ? nullptr
468                                 : PrevForDefaultArgs->getPreviousDecl()) {
469     // Ignore hidden declarations.
470     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471       continue;
472 
473     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474         !New->isCXXClassMember()) {
475       // Ignore default arguments of old decl if they are not in
476       // the same scope and this is not an out-of-line definition of
477       // a member function.
478       continue;
479     }
480 
481     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482       // If only one of these is a local function declaration, then they are
483       // declared in different scopes, even though isDeclInScope may think
484       // they're in the same scope. (If both are local, the scope check is
485       // sufficient, and if neither is local, then they are in the same scope.)
486       continue;
487     }
488 
489     // We found the right previous declaration.
490     break;
491   }
492 
493   // C++ [dcl.fct.default]p4:
494   //   For non-template functions, default arguments can be added in
495   //   later declarations of a function in the same
496   //   scope. Declarations in different scopes have completely
497   //   distinct sets of default arguments. That is, declarations in
498   //   inner scopes do not acquire default arguments from
499   //   declarations in outer scopes, and vice versa. In a given
500   //   function declaration, all parameters subsequent to a
501   //   parameter with a default argument shall have default
502   //   arguments supplied in this or previous declarations. A
503   //   default argument shall not be redefined by a later
504   //   declaration (not even to the same value).
505   //
506   // C++ [dcl.fct.default]p6:
507   //   Except for member functions of class templates, the default arguments
508   //   in a member function definition that appears outside of the class
509   //   definition are added to the set of default arguments provided by the
510   //   member function declaration in the class definition.
511   for (unsigned p = 0, NumParams = PrevForDefaultArgs
512                                        ? PrevForDefaultArgs->getNumParams()
513                                        : 0;
514        p < NumParams; ++p) {
515     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516     ParmVarDecl *NewParam = New->getParamDecl(p);
517 
518     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519     bool NewParamHasDfl = NewParam->hasDefaultArg();
520 
521     if (OldParamHasDfl && NewParamHasDfl) {
522       unsigned DiagDefaultParamID =
523         diag::err_param_default_argument_redefinition;
524 
525       // MSVC accepts that default parameters be redefined for member functions
526       // of template class. The new default parameter's value is ignored.
527       Invalid = true;
528       if (getLangOpts().MicrosoftExt) {
529         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530         if (MD && MD->getParent()->getDescribedClassTemplate()) {
531           // Merge the old default argument into the new parameter.
532           NewParam->setHasInheritedDefaultArg();
533           if (OldParam->hasUninstantiatedDefaultArg())
534             NewParam->setUninstantiatedDefaultArg(
535                                       OldParam->getUninstantiatedDefaultArg());
536           else
537             NewParam->setDefaultArg(OldParam->getInit());
538           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539           Invalid = false;
540         }
541       }
542 
543       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544       // hint here. Alternatively, we could walk the type-source information
545       // for NewParam to find the last source location in the type... but it
546       // isn't worth the effort right now. This is the kind of test case that
547       // is hard to get right:
548       //   int f(int);
549       //   void g(int (*fp)(int) = f);
550       //   void g(int (*fp)(int) = &f);
551       Diag(NewParam->getLocation(), DiagDefaultParamID)
552         << NewParam->getDefaultArgRange();
553 
554       // Look for the function declaration where the default argument was
555       // actually written, which may be a declaration prior to Old.
556       for (auto Older = PrevForDefaultArgs;
557            OldParam->hasInheritedDefaultArg(); /**/) {
558         Older = Older->getPreviousDecl();
559         OldParam = Older->getParamDecl(p);
560       }
561 
562       Diag(OldParam->getLocation(), diag::note_previous_definition)
563         << OldParam->getDefaultArgRange();
564     } else if (OldParamHasDfl) {
565       // Merge the old default argument into the new parameter unless the new
566       // function is a friend declaration in a template class. In the latter
567       // case the default arguments will be inherited when the friend
568       // declaration will be instantiated.
569       if (New->getFriendObjectKind() == Decl::FOK_None ||
570           !New->getLexicalDeclContext()->isDependentContext()) {
571         // It's important to use getInit() here;  getDefaultArg()
572         // strips off any top-level ExprWithCleanups.
573         NewParam->setHasInheritedDefaultArg();
574         if (OldParam->hasUnparsedDefaultArg())
575           NewParam->setUnparsedDefaultArg();
576         else if (OldParam->hasUninstantiatedDefaultArg())
577           NewParam->setUninstantiatedDefaultArg(
578                                        OldParam->getUninstantiatedDefaultArg());
579         else
580           NewParam->setDefaultArg(OldParam->getInit());
581       }
582     } else if (NewParamHasDfl) {
583       if (New->getDescribedFunctionTemplate()) {
584         // Paragraph 4, quoted above, only applies to non-template functions.
585         Diag(NewParam->getLocation(),
586              diag::err_param_default_argument_template_redecl)
587           << NewParam->getDefaultArgRange();
588         Diag(PrevForDefaultArgs->getLocation(),
589              diag::note_template_prev_declaration)
590             << false;
591       } else if (New->getTemplateSpecializationKind()
592                    != TSK_ImplicitInstantiation &&
593                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
594         // C++ [temp.expr.spec]p21:
595         //   Default function arguments shall not be specified in a declaration
596         //   or a definition for one of the following explicit specializations:
597         //     - the explicit specialization of a function template;
598         //     - the explicit specialization of a member function template;
599         //     - the explicit specialization of a member function of a class
600         //       template where the class template specialization to which the
601         //       member function specialization belongs is implicitly
602         //       instantiated.
603         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605           << New->getDeclName()
606           << NewParam->getDefaultArgRange();
607       } else if (New->getDeclContext()->isDependentContext()) {
608         // C++ [dcl.fct.default]p6 (DR217):
609         //   Default arguments for a member function of a class template shall
610         //   be specified on the initial declaration of the member function
611         //   within the class template.
612         //
613         // Reading the tea leaves a bit in DR217 and its reference to DR205
614         // leads me to the conclusion that one cannot add default function
615         // arguments for an out-of-line definition of a member function of a
616         // dependent type.
617         int WhichKind = 2;
618         if (CXXRecordDecl *Record
619               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620           if (Record->getDescribedClassTemplate())
621             WhichKind = 0;
622           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623             WhichKind = 1;
624           else
625             WhichKind = 2;
626         }
627 
628         Diag(NewParam->getLocation(),
629              diag::err_param_default_argument_member_template_redecl)
630           << WhichKind
631           << NewParam->getDefaultArgRange();
632       }
633     }
634   }
635 
636   // DR1344: If a default argument is added outside a class definition and that
637   // default argument makes the function a special member function, the program
638   // is ill-formed. This can only happen for constructors.
639   if (isa<CXXConstructorDecl>(New) &&
640       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643     if (NewSM != OldSM) {
644       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645       assert(NewParam->hasDefaultArg());
646       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647         << NewParam->getDefaultArgRange() << NewSM;
648       Diag(Old->getLocation(), diag::note_previous_declaration);
649     }
650   }
651 
652   const FunctionDecl *Def;
653   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654   // template has a constexpr specifier then all its declarations shall
655   // contain the constexpr specifier.
656   if (New->getConstexprKind() != Old->getConstexprKind()) {
657     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658         << New << New->getConstexprKind() << Old->getConstexprKind();
659     Diag(Old->getLocation(), diag::note_previous_declaration);
660     Invalid = true;
661   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
662              Old->isDefined(Def) &&
663              // If a friend function is inlined but does not have 'inline'
664              // specifier, it is a definition. Do not report attribute conflict
665              // in this case, redefinition will be diagnosed later.
666              (New->isInlineSpecified() ||
667               New->getFriendObjectKind() == Decl::FOK_None)) {
668     // C++11 [dcl.fcn.spec]p4:
669     //   If the definition of a function appears in a translation unit before its
670     //   first declaration as inline, the program is ill-formed.
671     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672     Diag(Def->getLocation(), diag::note_previous_definition);
673     Invalid = true;
674   }
675 
676   // C++17 [temp.deduct.guide]p3:
677   //   Two deduction guide declarations in the same translation unit
678   //   for the same class template shall not have equivalent
679   //   parameter-declaration-clauses.
680   if (isa<CXXDeductionGuideDecl>(New) &&
681       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
682     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683     Diag(Old->getLocation(), diag::note_previous_declaration);
684   }
685 
686   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687   // argument expression, that declaration shall be a definition and shall be
688   // the only declaration of the function or function template in the
689   // translation unit.
690   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691       functionDeclHasDefaultArgument(Old)) {
692     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693     Diag(Old->getLocation(), diag::note_previous_declaration);
694     Invalid = true;
695   }
696 
697   return Invalid;
698 }
699 
700 NamedDecl *
701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
702                                    MultiTemplateParamsArg TemplateParamLists) {
703   assert(D.isDecompositionDeclarator());
704   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
705 
706   // The syntax only allows a decomposition declarator as a simple-declaration,
707   // a for-range-declaration, or a condition in Clang, but we parse it in more
708   // cases than that.
709   if (!D.mayHaveDecompositionDeclarator()) {
710     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
711       << Decomp.getSourceRange();
712     return nullptr;
713   }
714 
715   if (!TemplateParamLists.empty()) {
716     // FIXME: There's no rule against this, but there are also no rules that
717     // would actually make it usable, so we reject it for now.
718     Diag(TemplateParamLists.front()->getTemplateLoc(),
719          diag::err_decomp_decl_template);
720     return nullptr;
721   }
722 
723   Diag(Decomp.getLSquareLoc(),
724        !getLangOpts().CPlusPlus17
725            ? diag::ext_decomp_decl
726            : D.getContext() == DeclaratorContext::ConditionContext
727                  ? diag::ext_decomp_decl_cond
728                  : diag::warn_cxx14_compat_decomp_decl)
729       << Decomp.getSourceRange();
730 
731   // The semantic context is always just the current context.
732   DeclContext *const DC = CurContext;
733 
734   // C++17 [dcl.dcl]/8:
735   //   The decl-specifier-seq shall contain only the type-specifier auto
736   //   and cv-qualifiers.
737   // C++2a [dcl.dcl]/8:
738   //   If decl-specifier-seq contains any decl-specifier other than static,
739   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
740   auto &DS = D.getDeclSpec();
741   {
742     SmallVector<StringRef, 8> BadSpecifiers;
743     SmallVector<SourceLocation, 8> BadSpecifierLocs;
744     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
745     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
746     if (auto SCS = DS.getStorageClassSpec()) {
747       if (SCS == DeclSpec::SCS_static) {
748         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
749         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
750       } else {
751         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
752         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
753       }
754     }
755     if (auto TSCS = DS.getThreadStorageClassSpec()) {
756       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
757       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
758     }
759     if (DS.hasConstexprSpecifier()) {
760       BadSpecifiers.push_back(
761           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
762       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
763     }
764     if (DS.isInlineSpecified()) {
765       BadSpecifiers.push_back("inline");
766       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
767     }
768     if (!BadSpecifiers.empty()) {
769       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
770       Err << (int)BadSpecifiers.size()
771           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
772       // Don't add FixItHints to remove the specifiers; we do still respect
773       // them when building the underlying variable.
774       for (auto Loc : BadSpecifierLocs)
775         Err << SourceRange(Loc, Loc);
776     } else if (!CPlusPlus20Specifiers.empty()) {
777       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
778                          getLangOpts().CPlusPlus20
779                              ? diag::warn_cxx17_compat_decomp_decl_spec
780                              : diag::ext_decomp_decl_spec);
781       Warn << (int)CPlusPlus20Specifiers.size()
782            << llvm::join(CPlusPlus20Specifiers.begin(),
783                          CPlusPlus20Specifiers.end(), " ");
784       for (auto Loc : CPlusPlus20SpecifierLocs)
785         Warn << SourceRange(Loc, Loc);
786     }
787     // We can't recover from it being declared as a typedef.
788     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
789       return nullptr;
790   }
791 
792   // C++2a [dcl.struct.bind]p1:
793   //   A cv that includes volatile is deprecated
794   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
795       getLangOpts().CPlusPlus20)
796     Diag(DS.getVolatileSpecLoc(),
797          diag::warn_deprecated_volatile_structured_binding);
798 
799   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
800   QualType R = TInfo->getType();
801 
802   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
803                                       UPPC_DeclarationType))
804     D.setInvalidType();
805 
806   // The syntax only allows a single ref-qualifier prior to the decomposition
807   // declarator. No other declarator chunks are permitted. Also check the type
808   // specifier here.
809   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
810       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
811       (D.getNumTypeObjects() == 1 &&
812        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
813     Diag(Decomp.getLSquareLoc(),
814          (D.hasGroupingParens() ||
815           (D.getNumTypeObjects() &&
816            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
817              ? diag::err_decomp_decl_parens
818              : diag::err_decomp_decl_type)
819         << R;
820 
821     // In most cases, there's no actual problem with an explicitly-specified
822     // type, but a function type won't work here, and ActOnVariableDeclarator
823     // shouldn't be called for such a type.
824     if (R->isFunctionType())
825       D.setInvalidType();
826   }
827 
828   // Build the BindingDecls.
829   SmallVector<BindingDecl*, 8> Bindings;
830 
831   // Build the BindingDecls.
832   for (auto &B : D.getDecompositionDeclarator().bindings()) {
833     // Check for name conflicts.
834     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
835     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
836                           ForVisibleRedeclaration);
837     LookupName(Previous, S,
838                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
839 
840     // It's not permitted to shadow a template parameter name.
841     if (Previous.isSingleResult() &&
842         Previous.getFoundDecl()->isTemplateParameter()) {
843       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
844                                       Previous.getFoundDecl());
845       Previous.clear();
846     }
847 
848     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
849                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
850     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
851                          /*AllowInlineNamespace*/false);
852     if (!Previous.empty()) {
853       auto *Old = Previous.getRepresentativeDecl();
854       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
855       Diag(Old->getLocation(), diag::note_previous_definition);
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859     PushOnScopeChains(BD, S, true);
860     Bindings.push_back(BD);
861     ParsingInitForAutoVars.insert(BD);
862   }
863 
864   // There are no prior lookup results for the variable itself, because it
865   // is unnamed.
866   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
867                                Decomp.getLSquareLoc());
868   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
869                         ForVisibleRedeclaration);
870 
871   // Build the variable that holds the non-decomposed object.
872   bool AddToScope = true;
873   NamedDecl *New =
874       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
875                               MultiTemplateParamsArg(), AddToScope, Bindings);
876   if (AddToScope) {
877     S->AddDecl(New);
878     CurContext->addHiddenDecl(New);
879   }
880 
881   if (isInOpenMPDeclareTargetContext())
882     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
883 
884   return New;
885 }
886 
887 static bool checkSimpleDecomposition(
888     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
889     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
890     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
891   if ((int64_t)Bindings.size() != NumElems) {
892     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
893         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
894         << (NumElems < Bindings.size());
895     return true;
896   }
897 
898   unsigned I = 0;
899   for (auto *B : Bindings) {
900     SourceLocation Loc = B->getLocation();
901     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
902     if (E.isInvalid())
903       return true;
904     E = GetInit(Loc, E.get(), I++);
905     if (E.isInvalid())
906       return true;
907     B->setBinding(ElemType, E.get());
908   }
909 
910   return false;
911 }
912 
913 static bool checkArrayLikeDecomposition(Sema &S,
914                                         ArrayRef<BindingDecl *> Bindings,
915                                         ValueDecl *Src, QualType DecompType,
916                                         const llvm::APSInt &NumElems,
917                                         QualType ElemType) {
918   return checkSimpleDecomposition(
919       S, Bindings, Src, DecompType, NumElems, ElemType,
920       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
921         ExprResult E = S.ActOnIntegerConstant(Loc, I);
922         if (E.isInvalid())
923           return ExprError();
924         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
925       });
926 }
927 
928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
929                                     ValueDecl *Src, QualType DecompType,
930                                     const ConstantArrayType *CAT) {
931   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
932                                      llvm::APSInt(CAT->getSize()),
933                                      CAT->getElementType());
934 }
935 
936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
937                                      ValueDecl *Src, QualType DecompType,
938                                      const VectorType *VT) {
939   return checkArrayLikeDecomposition(
940       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
941       S.Context.getQualifiedType(VT->getElementType(),
942                                  DecompType.getQualifiers()));
943 }
944 
945 static bool checkComplexDecomposition(Sema &S,
946                                       ArrayRef<BindingDecl *> Bindings,
947                                       ValueDecl *Src, QualType DecompType,
948                                       const ComplexType *CT) {
949   return checkSimpleDecomposition(
950       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
951       S.Context.getQualifiedType(CT->getElementType(),
952                                  DecompType.getQualifiers()),
953       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
954         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
955       });
956 }
957 
958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
959                                      TemplateArgumentListInfo &Args) {
960   SmallString<128> SS;
961   llvm::raw_svector_ostream OS(SS);
962   bool First = true;
963   for (auto &Arg : Args.arguments()) {
964     if (!First)
965       OS << ", ";
966     Arg.getArgument().print(PrintingPolicy, OS);
967     First = false;
968   }
969   return std::string(OS.str());
970 }
971 
972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
973                                      SourceLocation Loc, StringRef Trait,
974                                      TemplateArgumentListInfo &Args,
975                                      unsigned DiagID) {
976   auto DiagnoseMissing = [&] {
977     if (DiagID)
978       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
979                                                Args);
980     return true;
981   };
982 
983   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
984   NamespaceDecl *Std = S.getStdNamespace();
985   if (!Std)
986     return DiagnoseMissing();
987 
988   // Look up the trait itself, within namespace std. We can diagnose various
989   // problems with this lookup even if we've been asked to not diagnose a
990   // missing specialization, because this can only fail if the user has been
991   // declaring their own names in namespace std or we don't support the
992   // standard library implementation in use.
993   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
994                       Loc, Sema::LookupOrdinaryName);
995   if (!S.LookupQualifiedName(Result, Std))
996     return DiagnoseMissing();
997   if (Result.isAmbiguous())
998     return true;
999 
1000   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1001   if (!TraitTD) {
1002     Result.suppressDiagnostics();
1003     NamedDecl *Found = *Result.begin();
1004     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1005     S.Diag(Found->getLocation(), diag::note_declared_at);
1006     return true;
1007   }
1008 
1009   // Build the template-id.
1010   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1011   if (TraitTy.isNull())
1012     return true;
1013   if (!S.isCompleteType(Loc, TraitTy)) {
1014     if (DiagID)
1015       S.RequireCompleteType(
1016           Loc, TraitTy, DiagID,
1017           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1018     return true;
1019   }
1020 
1021   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1022   assert(RD && "specialization of class template is not a class?");
1023 
1024   // Look up the member of the trait type.
1025   S.LookupQualifiedName(TraitMemberLookup, RD);
1026   return TraitMemberLookup.isAmbiguous();
1027 }
1028 
1029 static TemplateArgumentLoc
1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1031                                    uint64_t I) {
1032   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1033   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1034 }
1035 
1036 static TemplateArgumentLoc
1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1038   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1039 }
1040 
1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1042 
1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1044                                llvm::APSInt &Size) {
1045   EnterExpressionEvaluationContext ContextRAII(
1046       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1047 
1048   DeclarationName Value = S.PP.getIdentifierInfo("value");
1049   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1050 
1051   // Form template argument list for tuple_size<T>.
1052   TemplateArgumentListInfo Args(Loc, Loc);
1053   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1054 
1055   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1056   // it's not tuple-like.
1057   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1058       R.empty())
1059     return IsTupleLike::NotTupleLike;
1060 
1061   // If we get this far, we've committed to the tuple interpretation, but
1062   // we can still fail if there actually isn't a usable ::value.
1063 
1064   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1065     LookupResult &R;
1066     TemplateArgumentListInfo &Args;
1067     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1068         : R(R), Args(Args) {}
1069     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1070       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1071           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1072     }
1073   } Diagnoser(R, Args);
1074 
1075   ExprResult E =
1076       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1077   if (E.isInvalid())
1078     return IsTupleLike::Error;
1079 
1080   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1081   if (E.isInvalid())
1082     return IsTupleLike::Error;
1083 
1084   return IsTupleLike::TupleLike;
1085 }
1086 
1087 /// \return std::tuple_element<I, T>::type.
1088 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1089                                         unsigned I, QualType T) {
1090   // Form template argument list for tuple_element<I, T>.
1091   TemplateArgumentListInfo Args(Loc, Loc);
1092   Args.addArgument(
1093       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1094   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1095 
1096   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1097   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1098   if (lookupStdTypeTraitMember(
1099           S, R, Loc, "tuple_element", Args,
1100           diag::err_decomp_decl_std_tuple_element_not_specialized))
1101     return QualType();
1102 
1103   auto *TD = R.getAsSingle<TypeDecl>();
1104   if (!TD) {
1105     R.suppressDiagnostics();
1106     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1107       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1108     if (!R.empty())
1109       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1110     return QualType();
1111   }
1112 
1113   return S.Context.getTypeDeclType(TD);
1114 }
1115 
1116 namespace {
1117 struct InitializingBinding {
1118   Sema &S;
1119   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1120     Sema::CodeSynthesisContext Ctx;
1121     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1122     Ctx.PointOfInstantiation = BD->getLocation();
1123     Ctx.Entity = BD;
1124     S.pushCodeSynthesisContext(Ctx);
1125   }
1126   ~InitializingBinding() {
1127     S.popCodeSynthesisContext();
1128   }
1129 };
1130 }
1131 
1132 static bool checkTupleLikeDecomposition(Sema &S,
1133                                         ArrayRef<BindingDecl *> Bindings,
1134                                         VarDecl *Src, QualType DecompType,
1135                                         const llvm::APSInt &TupleSize) {
1136   if ((int64_t)Bindings.size() != TupleSize) {
1137     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1138         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1139         << (TupleSize < Bindings.size());
1140     return true;
1141   }
1142 
1143   if (Bindings.empty())
1144     return false;
1145 
1146   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1147 
1148   // [dcl.decomp]p3:
1149   //   The unqualified-id get is looked up in the scope of E by class member
1150   //   access lookup ...
1151   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1152   bool UseMemberGet = false;
1153   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1154     if (auto *RD = DecompType->getAsCXXRecordDecl())
1155       S.LookupQualifiedName(MemberGet, RD);
1156     if (MemberGet.isAmbiguous())
1157       return true;
1158     //   ... and if that finds at least one declaration that is a function
1159     //   template whose first template parameter is a non-type parameter ...
1160     for (NamedDecl *D : MemberGet) {
1161       if (FunctionTemplateDecl *FTD =
1162               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1163         TemplateParameterList *TPL = FTD->getTemplateParameters();
1164         if (TPL->size() != 0 &&
1165             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1166           //   ... the initializer is e.get<i>().
1167           UseMemberGet = true;
1168           break;
1169         }
1170       }
1171     }
1172   }
1173 
1174   unsigned I = 0;
1175   for (auto *B : Bindings) {
1176     InitializingBinding InitContext(S, B);
1177     SourceLocation Loc = B->getLocation();
1178 
1179     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1180     if (E.isInvalid())
1181       return true;
1182 
1183     //   e is an lvalue if the type of the entity is an lvalue reference and
1184     //   an xvalue otherwise
1185     if (!Src->getType()->isLValueReferenceType())
1186       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1187                                    E.get(), nullptr, VK_XValue);
1188 
1189     TemplateArgumentListInfo Args(Loc, Loc);
1190     Args.addArgument(
1191         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1192 
1193     if (UseMemberGet) {
1194       //   if [lookup of member get] finds at least one declaration, the
1195       //   initializer is e.get<i-1>().
1196       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1197                                      CXXScopeSpec(), SourceLocation(), nullptr,
1198                                      MemberGet, &Args, nullptr);
1199       if (E.isInvalid())
1200         return true;
1201 
1202       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1203     } else {
1204       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1205       //   in the associated namespaces.
1206       Expr *Get = UnresolvedLookupExpr::Create(
1207           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1208           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1209           UnresolvedSetIterator(), UnresolvedSetIterator());
1210 
1211       Expr *Arg = E.get();
1212       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1213     }
1214     if (E.isInvalid())
1215       return true;
1216     Expr *Init = E.get();
1217 
1218     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1219     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1220     if (T.isNull())
1221       return true;
1222 
1223     //   each vi is a variable of type "reference to T" initialized with the
1224     //   initializer, where the reference is an lvalue reference if the
1225     //   initializer is an lvalue and an rvalue reference otherwise
1226     QualType RefType =
1227         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1228     if (RefType.isNull())
1229       return true;
1230     auto *RefVD = VarDecl::Create(
1231         S.Context, Src->getDeclContext(), Loc, Loc,
1232         B->getDeclName().getAsIdentifierInfo(), RefType,
1233         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1234     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1235     RefVD->setTSCSpec(Src->getTSCSpec());
1236     RefVD->setImplicit();
1237     if (Src->isInlineSpecified())
1238       RefVD->setInlineSpecified();
1239     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1240 
1241     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1242     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1243     InitializationSequence Seq(S, Entity, Kind, Init);
1244     E = Seq.Perform(S, Entity, Kind, Init);
1245     if (E.isInvalid())
1246       return true;
1247     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1248     if (E.isInvalid())
1249       return true;
1250     RefVD->setInit(E.get());
1251     if (!E.get()->isValueDependent())
1252       RefVD->checkInitIsICE();
1253 
1254     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1255                                    DeclarationNameInfo(B->getDeclName(), Loc),
1256                                    RefVD);
1257     if (E.isInvalid())
1258       return true;
1259 
1260     B->setBinding(T, E.get());
1261     I++;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 /// Find the base class to decompose in a built-in decomposition of a class type.
1268 /// This base class search is, unfortunately, not quite like any other that we
1269 /// perform anywhere else in C++.
1270 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1271                                                 const CXXRecordDecl *RD,
1272                                                 CXXCastPath &BasePath) {
1273   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1274                           CXXBasePath &Path) {
1275     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1276   };
1277 
1278   const CXXRecordDecl *ClassWithFields = nullptr;
1279   AccessSpecifier AS = AS_public;
1280   if (RD->hasDirectFields())
1281     // [dcl.decomp]p4:
1282     //   Otherwise, all of E's non-static data members shall be public direct
1283     //   members of E ...
1284     ClassWithFields = RD;
1285   else {
1286     //   ... or of ...
1287     CXXBasePaths Paths;
1288     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1289     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1290       // If no classes have fields, just decompose RD itself. (This will work
1291       // if and only if zero bindings were provided.)
1292       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1293     }
1294 
1295     CXXBasePath *BestPath = nullptr;
1296     for (auto &P : Paths) {
1297       if (!BestPath)
1298         BestPath = &P;
1299       else if (!S.Context.hasSameType(P.back().Base->getType(),
1300                                       BestPath->back().Base->getType())) {
1301         //   ... the same ...
1302         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1303           << false << RD << BestPath->back().Base->getType()
1304           << P.back().Base->getType();
1305         return DeclAccessPair();
1306       } else if (P.Access < BestPath->Access) {
1307         BestPath = &P;
1308       }
1309     }
1310 
1311     //   ... unambiguous ...
1312     QualType BaseType = BestPath->back().Base->getType();
1313     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1314       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1315         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1316       return DeclAccessPair();
1317     }
1318 
1319     //   ... [accessible, implied by other rules] base class of E.
1320     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1321                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1322     AS = BestPath->Access;
1323 
1324     ClassWithFields = BaseType->getAsCXXRecordDecl();
1325     S.BuildBasePathArray(Paths, BasePath);
1326   }
1327 
1328   // The above search did not check whether the selected class itself has base
1329   // classes with fields, so check that now.
1330   CXXBasePaths Paths;
1331   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1332     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1333       << (ClassWithFields == RD) << RD << ClassWithFields
1334       << Paths.front().back().Base->getType();
1335     return DeclAccessPair();
1336   }
1337 
1338   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1339 }
1340 
1341 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1342                                      ValueDecl *Src, QualType DecompType,
1343                                      const CXXRecordDecl *OrigRD) {
1344   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1345                             diag::err_incomplete_type))
1346     return true;
1347 
1348   CXXCastPath BasePath;
1349   DeclAccessPair BasePair =
1350       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1351   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1352   if (!RD)
1353     return true;
1354   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1355                                                  DecompType.getQualifiers());
1356 
1357   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1358     unsigned NumFields =
1359         std::count_if(RD->field_begin(), RD->field_end(),
1360                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1361     assert(Bindings.size() != NumFields);
1362     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1363         << DecompType << (unsigned)Bindings.size() << NumFields
1364         << (NumFields < Bindings.size());
1365     return true;
1366   };
1367 
1368   //   all of E's non-static data members shall be [...] well-formed
1369   //   when named as e.name in the context of the structured binding,
1370   //   E shall not have an anonymous union member, ...
1371   unsigned I = 0;
1372   for (auto *FD : RD->fields()) {
1373     if (FD->isUnnamedBitfield())
1374       continue;
1375 
1376     if (FD->isAnonymousStructOrUnion()) {
1377       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1378         << DecompType << FD->getType()->isUnionType();
1379       S.Diag(FD->getLocation(), diag::note_declared_at);
1380       return true;
1381     }
1382 
1383     // We have a real field to bind.
1384     if (I >= Bindings.size())
1385       return DiagnoseBadNumberOfBindings();
1386     auto *B = Bindings[I++];
1387     SourceLocation Loc = B->getLocation();
1388 
1389     // The field must be accessible in the context of the structured binding.
1390     // We already checked that the base class is accessible.
1391     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1392     // const_cast here.
1393     S.CheckStructuredBindingMemberAccess(
1394         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1395         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1396                                      BasePair.getAccess(), FD->getAccess())));
1397 
1398     // Initialize the binding to Src.FD.
1399     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1400     if (E.isInvalid())
1401       return true;
1402     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1403                             VK_LValue, &BasePath);
1404     if (E.isInvalid())
1405       return true;
1406     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1407                                   CXXScopeSpec(), FD,
1408                                   DeclAccessPair::make(FD, FD->getAccess()),
1409                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1410     if (E.isInvalid())
1411       return true;
1412 
1413     // If the type of the member is T, the referenced type is cv T, where cv is
1414     // the cv-qualification of the decomposition expression.
1415     //
1416     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1417     // 'const' to the type of the field.
1418     Qualifiers Q = DecompType.getQualifiers();
1419     if (FD->isMutable())
1420       Q.removeConst();
1421     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1422   }
1423 
1424   if (I != Bindings.size())
1425     return DiagnoseBadNumberOfBindings();
1426 
1427   return false;
1428 }
1429 
1430 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1431   QualType DecompType = DD->getType();
1432 
1433   // If the type of the decomposition is dependent, then so is the type of
1434   // each binding.
1435   if (DecompType->isDependentType()) {
1436     for (auto *B : DD->bindings())
1437       B->setType(Context.DependentTy);
1438     return;
1439   }
1440 
1441   DecompType = DecompType.getNonReferenceType();
1442   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1443 
1444   // C++1z [dcl.decomp]/2:
1445   //   If E is an array type [...]
1446   // As an extension, we also support decomposition of built-in complex and
1447   // vector types.
1448   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1449     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1450       DD->setInvalidDecl();
1451     return;
1452   }
1453   if (auto *VT = DecompType->getAs<VectorType>()) {
1454     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1455       DD->setInvalidDecl();
1456     return;
1457   }
1458   if (auto *CT = DecompType->getAs<ComplexType>()) {
1459     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1460       DD->setInvalidDecl();
1461     return;
1462   }
1463 
1464   // C++1z [dcl.decomp]/3:
1465   //   if the expression std::tuple_size<E>::value is a well-formed integral
1466   //   constant expression, [...]
1467   llvm::APSInt TupleSize(32);
1468   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1469   case IsTupleLike::Error:
1470     DD->setInvalidDecl();
1471     return;
1472 
1473   case IsTupleLike::TupleLike:
1474     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1475       DD->setInvalidDecl();
1476     return;
1477 
1478   case IsTupleLike::NotTupleLike:
1479     break;
1480   }
1481 
1482   // C++1z [dcl.dcl]/8:
1483   //   [E shall be of array or non-union class type]
1484   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1485   if (!RD || RD->isUnion()) {
1486     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1487         << DD << !RD << DecompType;
1488     DD->setInvalidDecl();
1489     return;
1490   }
1491 
1492   // C++1z [dcl.decomp]/4:
1493   //   all of E's non-static data members shall be [...] direct members of
1494   //   E or of the same unambiguous public base class of E, ...
1495   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1496     DD->setInvalidDecl();
1497 }
1498 
1499 /// Merge the exception specifications of two variable declarations.
1500 ///
1501 /// This is called when there's a redeclaration of a VarDecl. The function
1502 /// checks if the redeclaration might have an exception specification and
1503 /// validates compatibility and merges the specs if necessary.
1504 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1505   // Shortcut if exceptions are disabled.
1506   if (!getLangOpts().CXXExceptions)
1507     return;
1508 
1509   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1510          "Should only be called if types are otherwise the same.");
1511 
1512   QualType NewType = New->getType();
1513   QualType OldType = Old->getType();
1514 
1515   // We're only interested in pointers and references to functions, as well
1516   // as pointers to member functions.
1517   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1518     NewType = R->getPointeeType();
1519     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1520   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1521     NewType = P->getPointeeType();
1522     OldType = OldType->castAs<PointerType>()->getPointeeType();
1523   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1524     NewType = M->getPointeeType();
1525     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1526   }
1527 
1528   if (!NewType->isFunctionProtoType())
1529     return;
1530 
1531   // There's lots of special cases for functions. For function pointers, system
1532   // libraries are hopefully not as broken so that we don't need these
1533   // workarounds.
1534   if (CheckEquivalentExceptionSpec(
1535         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1536         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1537     New->setInvalidDecl();
1538   }
1539 }
1540 
1541 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1542 /// function declaration are well-formed according to C++
1543 /// [dcl.fct.default].
1544 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1545   unsigned NumParams = FD->getNumParams();
1546   unsigned ParamIdx = 0;
1547 
1548   // This checking doesn't make sense for explicit specializations; their
1549   // default arguments are determined by the declaration we're specializing,
1550   // not by FD.
1551   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1552     return;
1553   if (auto *FTD = FD->getDescribedFunctionTemplate())
1554     if (FTD->isMemberSpecialization())
1555       return;
1556 
1557   // Find first parameter with a default argument
1558   for (; ParamIdx < NumParams; ++ParamIdx) {
1559     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1560     if (Param->hasDefaultArg())
1561       break;
1562   }
1563 
1564   // C++20 [dcl.fct.default]p4:
1565   //   In a given function declaration, each parameter subsequent to a parameter
1566   //   with a default argument shall have a default argument supplied in this or
1567   //   a previous declaration, unless the parameter was expanded from a
1568   //   parameter pack, or shall be a function parameter pack.
1569   for (; ParamIdx < NumParams; ++ParamIdx) {
1570     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1571     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1572         !(CurrentInstantiationScope &&
1573           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1574       if (Param->isInvalidDecl())
1575         /* We already complained about this parameter. */;
1576       else if (Param->getIdentifier())
1577         Diag(Param->getLocation(),
1578              diag::err_param_default_argument_missing_name)
1579           << Param->getIdentifier();
1580       else
1581         Diag(Param->getLocation(),
1582              diag::err_param_default_argument_missing);
1583     }
1584   }
1585 }
1586 
1587 /// Check that the given type is a literal type. Issue a diagnostic if not,
1588 /// if Kind is Diagnose.
1589 /// \return \c true if a problem has been found (and optionally diagnosed).
1590 template <typename... Ts>
1591 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1592                              SourceLocation Loc, QualType T, unsigned DiagID,
1593                              Ts &&...DiagArgs) {
1594   if (T->isDependentType())
1595     return false;
1596 
1597   switch (Kind) {
1598   case Sema::CheckConstexprKind::Diagnose:
1599     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1600                                       std::forward<Ts>(DiagArgs)...);
1601 
1602   case Sema::CheckConstexprKind::CheckValid:
1603     return !T->isLiteralType(SemaRef.Context);
1604   }
1605 
1606   llvm_unreachable("unknown CheckConstexprKind");
1607 }
1608 
1609 /// Determine whether a destructor cannot be constexpr due to
1610 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1611                                                const CXXDestructorDecl *DD,
1612                                                Sema::CheckConstexprKind Kind) {
1613   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1614     const CXXRecordDecl *RD =
1615         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1616     if (!RD || RD->hasConstexprDestructor())
1617       return true;
1618 
1619     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1620       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1621           << DD->getConstexprKind() << !FD
1622           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1623       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1624           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1625     }
1626     return false;
1627   };
1628 
1629   const CXXRecordDecl *RD = DD->getParent();
1630   for (const CXXBaseSpecifier &B : RD->bases())
1631     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1632       return false;
1633   for (const FieldDecl *FD : RD->fields())
1634     if (!Check(FD->getLocation(), FD->getType(), FD))
1635       return false;
1636   return true;
1637 }
1638 
1639 /// Check whether a function's parameter types are all literal types. If so,
1640 /// return true. If not, produce a suitable diagnostic and return false.
1641 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1642                                          const FunctionDecl *FD,
1643                                          Sema::CheckConstexprKind Kind) {
1644   unsigned ArgIndex = 0;
1645   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1646   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1647                                               e = FT->param_type_end();
1648        i != e; ++i, ++ArgIndex) {
1649     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1650     SourceLocation ParamLoc = PD->getLocation();
1651     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1652                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1653                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1654                          FD->isConsteval()))
1655       return false;
1656   }
1657   return true;
1658 }
1659 
1660 /// Check whether a function's return type is a literal type. If so, return
1661 /// true. If not, produce a suitable diagnostic and return false.
1662 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1663                                      Sema::CheckConstexprKind Kind) {
1664   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1665                        diag::err_constexpr_non_literal_return,
1666                        FD->isConsteval()))
1667     return false;
1668   return true;
1669 }
1670 
1671 /// Get diagnostic %select index for tag kind for
1672 /// record diagnostic message.
1673 /// WARNING: Indexes apply to particular diagnostics only!
1674 ///
1675 /// \returns diagnostic %select index.
1676 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1677   switch (Tag) {
1678   case TTK_Struct: return 0;
1679   case TTK_Interface: return 1;
1680   case TTK_Class:  return 2;
1681   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1682   }
1683 }
1684 
1685 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1686                                        Stmt *Body,
1687                                        Sema::CheckConstexprKind Kind);
1688 
1689 // Check whether a function declaration satisfies the requirements of a
1690 // constexpr function definition or a constexpr constructor definition. If so,
1691 // return true. If not, produce appropriate diagnostics (unless asked not to by
1692 // Kind) and return false.
1693 //
1694 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1695 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1696                                             CheckConstexprKind Kind) {
1697   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1698   if (MD && MD->isInstance()) {
1699     // C++11 [dcl.constexpr]p4:
1700     //  The definition of a constexpr constructor shall satisfy the following
1701     //  constraints:
1702     //  - the class shall not have any virtual base classes;
1703     //
1704     // FIXME: This only applies to constructors and destructors, not arbitrary
1705     // member functions.
1706     const CXXRecordDecl *RD = MD->getParent();
1707     if (RD->getNumVBases()) {
1708       if (Kind == CheckConstexprKind::CheckValid)
1709         return false;
1710 
1711       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1712         << isa<CXXConstructorDecl>(NewFD)
1713         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1714       for (const auto &I : RD->vbases())
1715         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1716             << I.getSourceRange();
1717       return false;
1718     }
1719   }
1720 
1721   if (!isa<CXXConstructorDecl>(NewFD)) {
1722     // C++11 [dcl.constexpr]p3:
1723     //  The definition of a constexpr function shall satisfy the following
1724     //  constraints:
1725     // - it shall not be virtual; (removed in C++20)
1726     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1727     if (Method && Method->isVirtual()) {
1728       if (getLangOpts().CPlusPlus20) {
1729         if (Kind == CheckConstexprKind::Diagnose)
1730           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1731       } else {
1732         if (Kind == CheckConstexprKind::CheckValid)
1733           return false;
1734 
1735         Method = Method->getCanonicalDecl();
1736         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1737 
1738         // If it's not obvious why this function is virtual, find an overridden
1739         // function which uses the 'virtual' keyword.
1740         const CXXMethodDecl *WrittenVirtual = Method;
1741         while (!WrittenVirtual->isVirtualAsWritten())
1742           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1743         if (WrittenVirtual != Method)
1744           Diag(WrittenVirtual->getLocation(),
1745                diag::note_overridden_virtual_function);
1746         return false;
1747       }
1748     }
1749 
1750     // - its return type shall be a literal type;
1751     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1752       return false;
1753   }
1754 
1755   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1756     // A destructor can be constexpr only if the defaulted destructor could be;
1757     // we don't need to check the members and bases if we already know they all
1758     // have constexpr destructors.
1759     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1760       if (Kind == CheckConstexprKind::CheckValid)
1761         return false;
1762       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1763         return false;
1764     }
1765   }
1766 
1767   // - each of its parameter types shall be a literal type;
1768   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1769     return false;
1770 
1771   Stmt *Body = NewFD->getBody();
1772   assert(Body &&
1773          "CheckConstexprFunctionDefinition called on function with no body");
1774   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1775 }
1776 
1777 /// Check the given declaration statement is legal within a constexpr function
1778 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1779 ///
1780 /// \return true if the body is OK (maybe only as an extension), false if we
1781 ///         have diagnosed a problem.
1782 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1783                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1784                                    Sema::CheckConstexprKind Kind) {
1785   // C++11 [dcl.constexpr]p3 and p4:
1786   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1787   //  contain only
1788   for (const auto *DclIt : DS->decls()) {
1789     switch (DclIt->getKind()) {
1790     case Decl::StaticAssert:
1791     case Decl::Using:
1792     case Decl::UsingShadow:
1793     case Decl::UsingDirective:
1794     case Decl::UnresolvedUsingTypename:
1795     case Decl::UnresolvedUsingValue:
1796       //   - static_assert-declarations
1797       //   - using-declarations,
1798       //   - using-directives,
1799       continue;
1800 
1801     case Decl::Typedef:
1802     case Decl::TypeAlias: {
1803       //   - typedef declarations and alias-declarations that do not define
1804       //     classes or enumerations,
1805       const auto *TN = cast<TypedefNameDecl>(DclIt);
1806       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1807         // Don't allow variably-modified types in constexpr functions.
1808         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1809           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1810           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1811             << TL.getSourceRange() << TL.getType()
1812             << isa<CXXConstructorDecl>(Dcl);
1813         }
1814         return false;
1815       }
1816       continue;
1817     }
1818 
1819     case Decl::Enum:
1820     case Decl::CXXRecord:
1821       // C++1y allows types to be defined, not just declared.
1822       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1823         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1824           SemaRef.Diag(DS->getBeginLoc(),
1825                        SemaRef.getLangOpts().CPlusPlus14
1826                            ? diag::warn_cxx11_compat_constexpr_type_definition
1827                            : diag::ext_constexpr_type_definition)
1828               << isa<CXXConstructorDecl>(Dcl);
1829         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1830           return false;
1831         }
1832       }
1833       continue;
1834 
1835     case Decl::EnumConstant:
1836     case Decl::IndirectField:
1837     case Decl::ParmVar:
1838       // These can only appear with other declarations which are banned in
1839       // C++11 and permitted in C++1y, so ignore them.
1840       continue;
1841 
1842     case Decl::Var:
1843     case Decl::Decomposition: {
1844       // C++1y [dcl.constexpr]p3 allows anything except:
1845       //   a definition of a variable of non-literal type or of static or
1846       //   thread storage duration or [before C++2a] for which no
1847       //   initialization is performed.
1848       const auto *VD = cast<VarDecl>(DclIt);
1849       if (VD->isThisDeclarationADefinition()) {
1850         if (VD->isStaticLocal()) {
1851           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1852             SemaRef.Diag(VD->getLocation(),
1853                          diag::err_constexpr_local_var_static)
1854               << isa<CXXConstructorDecl>(Dcl)
1855               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1856           }
1857           return false;
1858         }
1859         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1860                              diag::err_constexpr_local_var_non_literal_type,
1861                              isa<CXXConstructorDecl>(Dcl)))
1862           return false;
1863         if (!VD->getType()->isDependentType() &&
1864             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1865           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866             SemaRef.Diag(
1867                 VD->getLocation(),
1868                 SemaRef.getLangOpts().CPlusPlus20
1869                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1870                     : diag::ext_constexpr_local_var_no_init)
1871                 << isa<CXXConstructorDecl>(Dcl);
1872           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1873             return false;
1874           }
1875           continue;
1876         }
1877       }
1878       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879         SemaRef.Diag(VD->getLocation(),
1880                      SemaRef.getLangOpts().CPlusPlus14
1881                       ? diag::warn_cxx11_compat_constexpr_local_var
1882                       : diag::ext_constexpr_local_var)
1883           << isa<CXXConstructorDecl>(Dcl);
1884       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1885         return false;
1886       }
1887       continue;
1888     }
1889 
1890     case Decl::NamespaceAlias:
1891     case Decl::Function:
1892       // These are disallowed in C++11 and permitted in C++1y. Allow them
1893       // everywhere as an extension.
1894       if (!Cxx1yLoc.isValid())
1895         Cxx1yLoc = DS->getBeginLoc();
1896       continue;
1897 
1898     default:
1899       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1901             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1902       }
1903       return false;
1904     }
1905   }
1906 
1907   return true;
1908 }
1909 
1910 /// Check that the given field is initialized within a constexpr constructor.
1911 ///
1912 /// \param Dcl The constexpr constructor being checked.
1913 /// \param Field The field being checked. This may be a member of an anonymous
1914 ///        struct or union nested within the class being checked.
1915 /// \param Inits All declarations, including anonymous struct/union members and
1916 ///        indirect members, for which any initialization was provided.
1917 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1918 ///        multiple notes for different members to the same error.
1919 /// \param Kind Whether we're diagnosing a constructor as written or determining
1920 ///        whether the formal requirements are satisfied.
1921 /// \return \c false if we're checking for validity and the constructor does
1922 ///         not satisfy the requirements on a constexpr constructor.
1923 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1924                                           const FunctionDecl *Dcl,
1925                                           FieldDecl *Field,
1926                                           llvm::SmallSet<Decl*, 16> &Inits,
1927                                           bool &Diagnosed,
1928                                           Sema::CheckConstexprKind Kind) {
1929   // In C++20 onwards, there's nothing to check for validity.
1930   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1931       SemaRef.getLangOpts().CPlusPlus20)
1932     return true;
1933 
1934   if (Field->isInvalidDecl())
1935     return true;
1936 
1937   if (Field->isUnnamedBitfield())
1938     return true;
1939 
1940   // Anonymous unions with no variant members and empty anonymous structs do not
1941   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1942   // indirect fields don't need initializing.
1943   if (Field->isAnonymousStructOrUnion() &&
1944       (Field->getType()->isUnionType()
1945            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1946            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1947     return true;
1948 
1949   if (!Inits.count(Field)) {
1950     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1951       if (!Diagnosed) {
1952         SemaRef.Diag(Dcl->getLocation(),
1953                      SemaRef.getLangOpts().CPlusPlus20
1954                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1955                          : diag::ext_constexpr_ctor_missing_init);
1956         Diagnosed = true;
1957       }
1958       SemaRef.Diag(Field->getLocation(),
1959                    diag::note_constexpr_ctor_missing_init);
1960     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1961       return false;
1962     }
1963   } else if (Field->isAnonymousStructOrUnion()) {
1964     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1965     for (auto *I : RD->fields())
1966       // If an anonymous union contains an anonymous struct of which any member
1967       // is initialized, all members must be initialized.
1968       if (!RD->isUnion() || Inits.count(I))
1969         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1970                                            Kind))
1971           return false;
1972   }
1973   return true;
1974 }
1975 
1976 /// Check the provided statement is allowed in a constexpr function
1977 /// definition.
1978 static bool
1979 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1980                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1981                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1982                            Sema::CheckConstexprKind Kind) {
1983   // - its function-body shall be [...] a compound-statement that contains only
1984   switch (S->getStmtClass()) {
1985   case Stmt::NullStmtClass:
1986     //   - null statements,
1987     return true;
1988 
1989   case Stmt::DeclStmtClass:
1990     //   - static_assert-declarations
1991     //   - using-declarations,
1992     //   - using-directives,
1993     //   - typedef declarations and alias-declarations that do not define
1994     //     classes or enumerations,
1995     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1996       return false;
1997     return true;
1998 
1999   case Stmt::ReturnStmtClass:
2000     //   - and exactly one return statement;
2001     if (isa<CXXConstructorDecl>(Dcl)) {
2002       // C++1y allows return statements in constexpr constructors.
2003       if (!Cxx1yLoc.isValid())
2004         Cxx1yLoc = S->getBeginLoc();
2005       return true;
2006     }
2007 
2008     ReturnStmts.push_back(S->getBeginLoc());
2009     return true;
2010 
2011   case Stmt::CompoundStmtClass: {
2012     // C++1y allows compound-statements.
2013     if (!Cxx1yLoc.isValid())
2014       Cxx1yLoc = S->getBeginLoc();
2015 
2016     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2017     for (auto *BodyIt : CompStmt->body()) {
2018       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2019                                       Cxx1yLoc, Cxx2aLoc, Kind))
2020         return false;
2021     }
2022     return true;
2023   }
2024 
2025   case Stmt::AttributedStmtClass:
2026     if (!Cxx1yLoc.isValid())
2027       Cxx1yLoc = S->getBeginLoc();
2028     return true;
2029 
2030   case Stmt::IfStmtClass: {
2031     // C++1y allows if-statements.
2032     if (!Cxx1yLoc.isValid())
2033       Cxx1yLoc = S->getBeginLoc();
2034 
2035     IfStmt *If = cast<IfStmt>(S);
2036     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2037                                     Cxx1yLoc, Cxx2aLoc, Kind))
2038       return false;
2039     if (If->getElse() &&
2040         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2041                                     Cxx1yLoc, Cxx2aLoc, Kind))
2042       return false;
2043     return true;
2044   }
2045 
2046   case Stmt::WhileStmtClass:
2047   case Stmt::DoStmtClass:
2048   case Stmt::ForStmtClass:
2049   case Stmt::CXXForRangeStmtClass:
2050   case Stmt::ContinueStmtClass:
2051     // C++1y allows all of these. We don't allow them as extensions in C++11,
2052     // because they don't make sense without variable mutation.
2053     if (!SemaRef.getLangOpts().CPlusPlus14)
2054       break;
2055     if (!Cxx1yLoc.isValid())
2056       Cxx1yLoc = S->getBeginLoc();
2057     for (Stmt *SubStmt : S->children())
2058       if (SubStmt &&
2059           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2060                                       Cxx1yLoc, Cxx2aLoc, Kind))
2061         return false;
2062     return true;
2063 
2064   case Stmt::SwitchStmtClass:
2065   case Stmt::CaseStmtClass:
2066   case Stmt::DefaultStmtClass:
2067   case Stmt::BreakStmtClass:
2068     // C++1y allows switch-statements, and since they don't need variable
2069     // mutation, we can reasonably allow them in C++11 as an extension.
2070     if (!Cxx1yLoc.isValid())
2071       Cxx1yLoc = S->getBeginLoc();
2072     for (Stmt *SubStmt : S->children())
2073       if (SubStmt &&
2074           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2075                                       Cxx1yLoc, Cxx2aLoc, Kind))
2076         return false;
2077     return true;
2078 
2079   case Stmt::GCCAsmStmtClass:
2080   case Stmt::MSAsmStmtClass:
2081     // C++2a allows inline assembly statements.
2082   case Stmt::CXXTryStmtClass:
2083     if (Cxx2aLoc.isInvalid())
2084       Cxx2aLoc = S->getBeginLoc();
2085     for (Stmt *SubStmt : S->children()) {
2086       if (SubStmt &&
2087           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2088                                       Cxx1yLoc, Cxx2aLoc, Kind))
2089         return false;
2090     }
2091     return true;
2092 
2093   case Stmt::CXXCatchStmtClass:
2094     // Do not bother checking the language mode (already covered by the
2095     // try block check).
2096     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2097                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2098                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2099       return false;
2100     return true;
2101 
2102   default:
2103     if (!isa<Expr>(S))
2104       break;
2105 
2106     // C++1y allows expression-statements.
2107     if (!Cxx1yLoc.isValid())
2108       Cxx1yLoc = S->getBeginLoc();
2109     return true;
2110   }
2111 
2112   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2113     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2114         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2115   }
2116   return false;
2117 }
2118 
2119 /// Check the body for the given constexpr function declaration only contains
2120 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2121 ///
2122 /// \return true if the body is OK, false if we have found or diagnosed a
2123 /// problem.
2124 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2125                                        Stmt *Body,
2126                                        Sema::CheckConstexprKind Kind) {
2127   SmallVector<SourceLocation, 4> ReturnStmts;
2128 
2129   if (isa<CXXTryStmt>(Body)) {
2130     // C++11 [dcl.constexpr]p3:
2131     //  The definition of a constexpr function shall satisfy the following
2132     //  constraints: [...]
2133     // - its function-body shall be = delete, = default, or a
2134     //   compound-statement
2135     //
2136     // C++11 [dcl.constexpr]p4:
2137     //  In the definition of a constexpr constructor, [...]
2138     // - its function-body shall not be a function-try-block;
2139     //
2140     // This restriction is lifted in C++2a, as long as inner statements also
2141     // apply the general constexpr rules.
2142     switch (Kind) {
2143     case Sema::CheckConstexprKind::CheckValid:
2144       if (!SemaRef.getLangOpts().CPlusPlus20)
2145         return false;
2146       break;
2147 
2148     case Sema::CheckConstexprKind::Diagnose:
2149       SemaRef.Diag(Body->getBeginLoc(),
2150            !SemaRef.getLangOpts().CPlusPlus20
2151                ? diag::ext_constexpr_function_try_block_cxx20
2152                : diag::warn_cxx17_compat_constexpr_function_try_block)
2153           << isa<CXXConstructorDecl>(Dcl);
2154       break;
2155     }
2156   }
2157 
2158   // - its function-body shall be [...] a compound-statement that contains only
2159   //   [... list of cases ...]
2160   //
2161   // Note that walking the children here is enough to properly check for
2162   // CompoundStmt and CXXTryStmt body.
2163   SourceLocation Cxx1yLoc, Cxx2aLoc;
2164   for (Stmt *SubStmt : Body->children()) {
2165     if (SubStmt &&
2166         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2167                                     Cxx1yLoc, Cxx2aLoc, Kind))
2168       return false;
2169   }
2170 
2171   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2172     // If this is only valid as an extension, report that we don't satisfy the
2173     // constraints of the current language.
2174     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2175         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2176       return false;
2177   } else if (Cxx2aLoc.isValid()) {
2178     SemaRef.Diag(Cxx2aLoc,
2179          SemaRef.getLangOpts().CPlusPlus20
2180            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2181            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2182       << isa<CXXConstructorDecl>(Dcl);
2183   } else if (Cxx1yLoc.isValid()) {
2184     SemaRef.Diag(Cxx1yLoc,
2185          SemaRef.getLangOpts().CPlusPlus14
2186            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2187            : diag::ext_constexpr_body_invalid_stmt)
2188       << isa<CXXConstructorDecl>(Dcl);
2189   }
2190 
2191   if (const CXXConstructorDecl *Constructor
2192         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2193     const CXXRecordDecl *RD = Constructor->getParent();
2194     // DR1359:
2195     // - every non-variant non-static data member and base class sub-object
2196     //   shall be initialized;
2197     // DR1460:
2198     // - if the class is a union having variant members, exactly one of them
2199     //   shall be initialized;
2200     if (RD->isUnion()) {
2201       if (Constructor->getNumCtorInitializers() == 0 &&
2202           RD->hasVariantMembers()) {
2203         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2204           SemaRef.Diag(
2205               Dcl->getLocation(),
2206               SemaRef.getLangOpts().CPlusPlus20
2207                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2208                   : diag::ext_constexpr_union_ctor_no_init);
2209         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2210           return false;
2211         }
2212       }
2213     } else if (!Constructor->isDependentContext() &&
2214                !Constructor->isDelegatingConstructor()) {
2215       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2216 
2217       // Skip detailed checking if we have enough initializers, and we would
2218       // allow at most one initializer per member.
2219       bool AnyAnonStructUnionMembers = false;
2220       unsigned Fields = 0;
2221       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2222            E = RD->field_end(); I != E; ++I, ++Fields) {
2223         if (I->isAnonymousStructOrUnion()) {
2224           AnyAnonStructUnionMembers = true;
2225           break;
2226         }
2227       }
2228       // DR1460:
2229       // - if the class is a union-like class, but is not a union, for each of
2230       //   its anonymous union members having variant members, exactly one of
2231       //   them shall be initialized;
2232       if (AnyAnonStructUnionMembers ||
2233           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2234         // Check initialization of non-static data members. Base classes are
2235         // always initialized so do not need to be checked. Dependent bases
2236         // might not have initializers in the member initializer list.
2237         llvm::SmallSet<Decl*, 16> Inits;
2238         for (const auto *I: Constructor->inits()) {
2239           if (FieldDecl *FD = I->getMember())
2240             Inits.insert(FD);
2241           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2242             Inits.insert(ID->chain_begin(), ID->chain_end());
2243         }
2244 
2245         bool Diagnosed = false;
2246         for (auto *I : RD->fields())
2247           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2248                                              Kind))
2249             return false;
2250       }
2251     }
2252   } else {
2253     if (ReturnStmts.empty()) {
2254       // C++1y doesn't require constexpr functions to contain a 'return'
2255       // statement. We still do, unless the return type might be void, because
2256       // otherwise if there's no return statement, the function cannot
2257       // be used in a core constant expression.
2258       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2259                 (Dcl->getReturnType()->isVoidType() ||
2260                  Dcl->getReturnType()->isDependentType());
2261       switch (Kind) {
2262       case Sema::CheckConstexprKind::Diagnose:
2263         SemaRef.Diag(Dcl->getLocation(),
2264                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2265                         : diag::err_constexpr_body_no_return)
2266             << Dcl->isConsteval();
2267         if (!OK)
2268           return false;
2269         break;
2270 
2271       case Sema::CheckConstexprKind::CheckValid:
2272         // The formal requirements don't include this rule in C++14, even
2273         // though the "must be able to produce a constant expression" rules
2274         // still imply it in some cases.
2275         if (!SemaRef.getLangOpts().CPlusPlus14)
2276           return false;
2277         break;
2278       }
2279     } else if (ReturnStmts.size() > 1) {
2280       switch (Kind) {
2281       case Sema::CheckConstexprKind::Diagnose:
2282         SemaRef.Diag(
2283             ReturnStmts.back(),
2284             SemaRef.getLangOpts().CPlusPlus14
2285                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2286                 : diag::ext_constexpr_body_multiple_return);
2287         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2288           SemaRef.Diag(ReturnStmts[I],
2289                        diag::note_constexpr_body_previous_return);
2290         break;
2291 
2292       case Sema::CheckConstexprKind::CheckValid:
2293         if (!SemaRef.getLangOpts().CPlusPlus14)
2294           return false;
2295         break;
2296       }
2297     }
2298   }
2299 
2300   // C++11 [dcl.constexpr]p5:
2301   //   if no function argument values exist such that the function invocation
2302   //   substitution would produce a constant expression, the program is
2303   //   ill-formed; no diagnostic required.
2304   // C++11 [dcl.constexpr]p3:
2305   //   - every constructor call and implicit conversion used in initializing the
2306   //     return value shall be one of those allowed in a constant expression.
2307   // C++11 [dcl.constexpr]p4:
2308   //   - every constructor involved in initializing non-static data members and
2309   //     base class sub-objects shall be a constexpr constructor.
2310   //
2311   // Note that this rule is distinct from the "requirements for a constexpr
2312   // function", so is not checked in CheckValid mode.
2313   SmallVector<PartialDiagnosticAt, 8> Diags;
2314   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2315       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2316     SemaRef.Diag(Dcl->getLocation(),
2317                  diag::ext_constexpr_function_never_constant_expr)
2318         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2319     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2320       SemaRef.Diag(Diags[I].first, Diags[I].second);
2321     // Don't return false here: we allow this for compatibility in
2322     // system headers.
2323   }
2324 
2325   return true;
2326 }
2327 
2328 /// Get the class that is directly named by the current context. This is the
2329 /// class for which an unqualified-id in this scope could name a constructor
2330 /// or destructor.
2331 ///
2332 /// If the scope specifier denotes a class, this will be that class.
2333 /// If the scope specifier is empty, this will be the class whose
2334 /// member-specification we are currently within. Otherwise, there
2335 /// is no such class.
2336 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2337   assert(getLangOpts().CPlusPlus && "No class names in C!");
2338 
2339   if (SS && SS->isInvalid())
2340     return nullptr;
2341 
2342   if (SS && SS->isNotEmpty()) {
2343     DeclContext *DC = computeDeclContext(*SS, true);
2344     return dyn_cast_or_null<CXXRecordDecl>(DC);
2345   }
2346 
2347   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2348 }
2349 
2350 /// isCurrentClassName - Determine whether the identifier II is the
2351 /// name of the class type currently being defined. In the case of
2352 /// nested classes, this will only return true if II is the name of
2353 /// the innermost class.
2354 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2355                               const CXXScopeSpec *SS) {
2356   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2357   return CurDecl && &II == CurDecl->getIdentifier();
2358 }
2359 
2360 /// Determine whether the identifier II is a typo for the name of
2361 /// the class type currently being defined. If so, update it to the identifier
2362 /// that should have been used.
2363 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2364   assert(getLangOpts().CPlusPlus && "No class names in C!");
2365 
2366   if (!getLangOpts().SpellChecking)
2367     return false;
2368 
2369   CXXRecordDecl *CurDecl;
2370   if (SS && SS->isSet() && !SS->isInvalid()) {
2371     DeclContext *DC = computeDeclContext(*SS, true);
2372     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2373   } else
2374     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2375 
2376   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2377       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2378           < II->getLength()) {
2379     II = CurDecl->getIdentifier();
2380     return true;
2381   }
2382 
2383   return false;
2384 }
2385 
2386 /// Determine whether the given class is a base class of the given
2387 /// class, including looking at dependent bases.
2388 static bool findCircularInheritance(const CXXRecordDecl *Class,
2389                                     const CXXRecordDecl *Current) {
2390   SmallVector<const CXXRecordDecl*, 8> Queue;
2391 
2392   Class = Class->getCanonicalDecl();
2393   while (true) {
2394     for (const auto &I : Current->bases()) {
2395       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2396       if (!Base)
2397         continue;
2398 
2399       Base = Base->getDefinition();
2400       if (!Base)
2401         continue;
2402 
2403       if (Base->getCanonicalDecl() == Class)
2404         return true;
2405 
2406       Queue.push_back(Base);
2407     }
2408 
2409     if (Queue.empty())
2410       return false;
2411 
2412     Current = Queue.pop_back_val();
2413   }
2414 
2415   return false;
2416 }
2417 
2418 /// Check the validity of a C++ base class specifier.
2419 ///
2420 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2421 /// and returns NULL otherwise.
2422 CXXBaseSpecifier *
2423 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2424                          SourceRange SpecifierRange,
2425                          bool Virtual, AccessSpecifier Access,
2426                          TypeSourceInfo *TInfo,
2427                          SourceLocation EllipsisLoc) {
2428   QualType BaseType = TInfo->getType();
2429 
2430   // C++ [class.union]p1:
2431   //   A union shall not have base classes.
2432   if (Class->isUnion()) {
2433     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2434       << SpecifierRange;
2435     return nullptr;
2436   }
2437 
2438   if (EllipsisLoc.isValid() &&
2439       !TInfo->getType()->containsUnexpandedParameterPack()) {
2440     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2441       << TInfo->getTypeLoc().getSourceRange();
2442     EllipsisLoc = SourceLocation();
2443   }
2444 
2445   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2446 
2447   if (BaseType->isDependentType()) {
2448     // Make sure that we don't have circular inheritance among our dependent
2449     // bases. For non-dependent bases, the check for completeness below handles
2450     // this.
2451     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2452       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2453           ((BaseDecl = BaseDecl->getDefinition()) &&
2454            findCircularInheritance(Class, BaseDecl))) {
2455         Diag(BaseLoc, diag::err_circular_inheritance)
2456           << BaseType << Context.getTypeDeclType(Class);
2457 
2458         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2459           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2460             << BaseType;
2461 
2462         return nullptr;
2463       }
2464     }
2465 
2466     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2467                                           Class->getTagKind() == TTK_Class,
2468                                           Access, TInfo, EllipsisLoc);
2469   }
2470 
2471   // Base specifiers must be record types.
2472   if (!BaseType->isRecordType()) {
2473     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2474     return nullptr;
2475   }
2476 
2477   // C++ [class.union]p1:
2478   //   A union shall not be used as a base class.
2479   if (BaseType->isUnionType()) {
2480     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2481     return nullptr;
2482   }
2483 
2484   // For the MS ABI, propagate DLL attributes to base class templates.
2485   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2486     if (Attr *ClassAttr = getDLLAttr(Class)) {
2487       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2488               BaseType->getAsCXXRecordDecl())) {
2489         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2490                                             BaseLoc);
2491       }
2492     }
2493   }
2494 
2495   // C++ [class.derived]p2:
2496   //   The class-name in a base-specifier shall not be an incompletely
2497   //   defined class.
2498   if (RequireCompleteType(BaseLoc, BaseType,
2499                           diag::err_incomplete_base_class, SpecifierRange)) {
2500     Class->setInvalidDecl();
2501     return nullptr;
2502   }
2503 
2504   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2505   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2506   assert(BaseDecl && "Record type has no declaration");
2507   BaseDecl = BaseDecl->getDefinition();
2508   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2509   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2510   assert(CXXBaseDecl && "Base type is not a C++ type");
2511 
2512   // Microsoft docs say:
2513   // "If a base-class has a code_seg attribute, derived classes must have the
2514   // same attribute."
2515   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2516   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2517   if ((DerivedCSA || BaseCSA) &&
2518       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2519     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2520     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2521       << CXXBaseDecl;
2522     return nullptr;
2523   }
2524 
2525   // A class which contains a flexible array member is not suitable for use as a
2526   // base class:
2527   //   - If the layout determines that a base comes before another base,
2528   //     the flexible array member would index into the subsequent base.
2529   //   - If the layout determines that base comes before the derived class,
2530   //     the flexible array member would index into the derived class.
2531   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2532     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2533       << CXXBaseDecl->getDeclName();
2534     return nullptr;
2535   }
2536 
2537   // C++ [class]p3:
2538   //   If a class is marked final and it appears as a base-type-specifier in
2539   //   base-clause, the program is ill-formed.
2540   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2541     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2542       << CXXBaseDecl->getDeclName()
2543       << FA->isSpelledAsSealed();
2544     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2545         << CXXBaseDecl->getDeclName() << FA->getRange();
2546     return nullptr;
2547   }
2548 
2549   if (BaseDecl->isInvalidDecl())
2550     Class->setInvalidDecl();
2551 
2552   // Create the base specifier.
2553   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2554                                         Class->getTagKind() == TTK_Class,
2555                                         Access, TInfo, EllipsisLoc);
2556 }
2557 
2558 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2559 /// one entry in the base class list of a class specifier, for
2560 /// example:
2561 ///    class foo : public bar, virtual private baz {
2562 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2563 BaseResult
2564 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2565                          ParsedAttributes &Attributes,
2566                          bool Virtual, AccessSpecifier Access,
2567                          ParsedType basetype, SourceLocation BaseLoc,
2568                          SourceLocation EllipsisLoc) {
2569   if (!classdecl)
2570     return true;
2571 
2572   AdjustDeclIfTemplate(classdecl);
2573   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2574   if (!Class)
2575     return true;
2576 
2577   // We haven't yet attached the base specifiers.
2578   Class->setIsParsingBaseSpecifiers();
2579 
2580   // We do not support any C++11 attributes on base-specifiers yet.
2581   // Diagnose any attributes we see.
2582   for (const ParsedAttr &AL : Attributes) {
2583     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2584       continue;
2585     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2586                           ? (unsigned)diag::warn_unknown_attribute_ignored
2587                           : (unsigned)diag::err_base_specifier_attribute)
2588         << AL;
2589   }
2590 
2591   TypeSourceInfo *TInfo = nullptr;
2592   GetTypeFromParser(basetype, &TInfo);
2593 
2594   if (EllipsisLoc.isInvalid() &&
2595       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2596                                       UPPC_BaseType))
2597     return true;
2598 
2599   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2600                                                       Virtual, Access, TInfo,
2601                                                       EllipsisLoc))
2602     return BaseSpec;
2603   else
2604     Class->setInvalidDecl();
2605 
2606   return true;
2607 }
2608 
2609 /// Use small set to collect indirect bases.  As this is only used
2610 /// locally, there's no need to abstract the small size parameter.
2611 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2612 
2613 /// Recursively add the bases of Type.  Don't add Type itself.
2614 static void
2615 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2616                   const QualType &Type)
2617 {
2618   // Even though the incoming type is a base, it might not be
2619   // a class -- it could be a template parm, for instance.
2620   if (auto Rec = Type->getAs<RecordType>()) {
2621     auto Decl = Rec->getAsCXXRecordDecl();
2622 
2623     // Iterate over its bases.
2624     for (const auto &BaseSpec : Decl->bases()) {
2625       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2626         .getUnqualifiedType();
2627       if (Set.insert(Base).second)
2628         // If we've not already seen it, recurse.
2629         NoteIndirectBases(Context, Set, Base);
2630     }
2631   }
2632 }
2633 
2634 /// Performs the actual work of attaching the given base class
2635 /// specifiers to a C++ class.
2636 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2637                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2638  if (Bases.empty())
2639     return false;
2640 
2641   // Used to keep track of which base types we have already seen, so
2642   // that we can properly diagnose redundant direct base types. Note
2643   // that the key is always the unqualified canonical type of the base
2644   // class.
2645   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2646 
2647   // Used to track indirect bases so we can see if a direct base is
2648   // ambiguous.
2649   IndirectBaseSet IndirectBaseTypes;
2650 
2651   // Copy non-redundant base specifiers into permanent storage.
2652   unsigned NumGoodBases = 0;
2653   bool Invalid = false;
2654   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2655     QualType NewBaseType
2656       = Context.getCanonicalType(Bases[idx]->getType());
2657     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2658 
2659     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2660     if (KnownBase) {
2661       // C++ [class.mi]p3:
2662       //   A class shall not be specified as a direct base class of a
2663       //   derived class more than once.
2664       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2665           << KnownBase->getType() << Bases[idx]->getSourceRange();
2666 
2667       // Delete the duplicate base class specifier; we're going to
2668       // overwrite its pointer later.
2669       Context.Deallocate(Bases[idx]);
2670 
2671       Invalid = true;
2672     } else {
2673       // Okay, add this new base class.
2674       KnownBase = Bases[idx];
2675       Bases[NumGoodBases++] = Bases[idx];
2676 
2677       // Note this base's direct & indirect bases, if there could be ambiguity.
2678       if (Bases.size() > 1)
2679         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2680 
2681       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2682         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2683         if (Class->isInterface() &&
2684               (!RD->isInterfaceLike() ||
2685                KnownBase->getAccessSpecifier() != AS_public)) {
2686           // The Microsoft extension __interface does not permit bases that
2687           // are not themselves public interfaces.
2688           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2689               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2690               << RD->getSourceRange();
2691           Invalid = true;
2692         }
2693         if (RD->hasAttr<WeakAttr>())
2694           Class->addAttr(WeakAttr::CreateImplicit(Context));
2695       }
2696     }
2697   }
2698 
2699   // Attach the remaining base class specifiers to the derived class.
2700   Class->setBases(Bases.data(), NumGoodBases);
2701 
2702   // Check that the only base classes that are duplicate are virtual.
2703   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2704     // Check whether this direct base is inaccessible due to ambiguity.
2705     QualType BaseType = Bases[idx]->getType();
2706 
2707     // Skip all dependent types in templates being used as base specifiers.
2708     // Checks below assume that the base specifier is a CXXRecord.
2709     if (BaseType->isDependentType())
2710       continue;
2711 
2712     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2713       .getUnqualifiedType();
2714 
2715     if (IndirectBaseTypes.count(CanonicalBase)) {
2716       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2717                          /*DetectVirtual=*/true);
2718       bool found
2719         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2720       assert(found);
2721       (void)found;
2722 
2723       if (Paths.isAmbiguous(CanonicalBase))
2724         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2725             << BaseType << getAmbiguousPathsDisplayString(Paths)
2726             << Bases[idx]->getSourceRange();
2727       else
2728         assert(Bases[idx]->isVirtual());
2729     }
2730 
2731     // Delete the base class specifier, since its data has been copied
2732     // into the CXXRecordDecl.
2733     Context.Deallocate(Bases[idx]);
2734   }
2735 
2736   return Invalid;
2737 }
2738 
2739 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2740 /// class, after checking whether there are any duplicate base
2741 /// classes.
2742 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2743                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2744   if (!ClassDecl || Bases.empty())
2745     return;
2746 
2747   AdjustDeclIfTemplate(ClassDecl);
2748   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2749 }
2750 
2751 /// Determine whether the type \p Derived is a C++ class that is
2752 /// derived from the type \p Base.
2753 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2754   if (!getLangOpts().CPlusPlus)
2755     return false;
2756 
2757   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2758   if (!DerivedRD)
2759     return false;
2760 
2761   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2762   if (!BaseRD)
2763     return false;
2764 
2765   // If either the base or the derived type is invalid, don't try to
2766   // check whether one is derived from the other.
2767   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2768     return false;
2769 
2770   // FIXME: In a modules build, do we need the entire path to be visible for us
2771   // to be able to use the inheritance relationship?
2772   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2773     return false;
2774 
2775   return DerivedRD->isDerivedFrom(BaseRD);
2776 }
2777 
2778 /// Determine whether the type \p Derived is a C++ class that is
2779 /// derived from the type \p Base.
2780 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2781                          CXXBasePaths &Paths) {
2782   if (!getLangOpts().CPlusPlus)
2783     return false;
2784 
2785   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2786   if (!DerivedRD)
2787     return false;
2788 
2789   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2790   if (!BaseRD)
2791     return false;
2792 
2793   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2794     return false;
2795 
2796   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2797 }
2798 
2799 static void BuildBasePathArray(const CXXBasePath &Path,
2800                                CXXCastPath &BasePathArray) {
2801   // We first go backward and check if we have a virtual base.
2802   // FIXME: It would be better if CXXBasePath had the base specifier for
2803   // the nearest virtual base.
2804   unsigned Start = 0;
2805   for (unsigned I = Path.size(); I != 0; --I) {
2806     if (Path[I - 1].Base->isVirtual()) {
2807       Start = I - 1;
2808       break;
2809     }
2810   }
2811 
2812   // Now add all bases.
2813   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2814     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2815 }
2816 
2817 
2818 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2819                               CXXCastPath &BasePathArray) {
2820   assert(BasePathArray.empty() && "Base path array must be empty!");
2821   assert(Paths.isRecordingPaths() && "Must record paths!");
2822   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2823 }
2824 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2825 /// conversion (where Derived and Base are class types) is
2826 /// well-formed, meaning that the conversion is unambiguous (and
2827 /// that all of the base classes are accessible). Returns true
2828 /// and emits a diagnostic if the code is ill-formed, returns false
2829 /// otherwise. Loc is the location where this routine should point to
2830 /// if there is an error, and Range is the source range to highlight
2831 /// if there is an error.
2832 ///
2833 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2834 /// diagnostic for the respective type of error will be suppressed, but the
2835 /// check for ill-formed code will still be performed.
2836 bool
2837 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2838                                    unsigned InaccessibleBaseID,
2839                                    unsigned AmbiguousBaseConvID,
2840                                    SourceLocation Loc, SourceRange Range,
2841                                    DeclarationName Name,
2842                                    CXXCastPath *BasePath,
2843                                    bool IgnoreAccess) {
2844   // First, determine whether the path from Derived to Base is
2845   // ambiguous. This is slightly more expensive than checking whether
2846   // the Derived to Base conversion exists, because here we need to
2847   // explore multiple paths to determine if there is an ambiguity.
2848   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2849                      /*DetectVirtual=*/false);
2850   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2851   if (!DerivationOkay)
2852     return true;
2853 
2854   const CXXBasePath *Path = nullptr;
2855   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2856     Path = &Paths.front();
2857 
2858   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2859   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2860   // user to access such bases.
2861   if (!Path && getLangOpts().MSVCCompat) {
2862     for (const CXXBasePath &PossiblePath : Paths) {
2863       if (PossiblePath.size() == 1) {
2864         Path = &PossiblePath;
2865         if (AmbiguousBaseConvID)
2866           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2867               << Base << Derived << Range;
2868         break;
2869       }
2870     }
2871   }
2872 
2873   if (Path) {
2874     if (!IgnoreAccess) {
2875       // Check that the base class can be accessed.
2876       switch (
2877           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2878       case AR_inaccessible:
2879         return true;
2880       case AR_accessible:
2881       case AR_dependent:
2882       case AR_delayed:
2883         break;
2884       }
2885     }
2886 
2887     // Build a base path if necessary.
2888     if (BasePath)
2889       ::BuildBasePathArray(*Path, *BasePath);
2890     return false;
2891   }
2892 
2893   if (AmbiguousBaseConvID) {
2894     // We know that the derived-to-base conversion is ambiguous, and
2895     // we're going to produce a diagnostic. Perform the derived-to-base
2896     // search just one more time to compute all of the possible paths so
2897     // that we can print them out. This is more expensive than any of
2898     // the previous derived-to-base checks we've done, but at this point
2899     // performance isn't as much of an issue.
2900     Paths.clear();
2901     Paths.setRecordingPaths(true);
2902     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2903     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2904     (void)StillOkay;
2905 
2906     // Build up a textual representation of the ambiguous paths, e.g.,
2907     // D -> B -> A, that will be used to illustrate the ambiguous
2908     // conversions in the diagnostic. We only print one of the paths
2909     // to each base class subobject.
2910     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2911 
2912     Diag(Loc, AmbiguousBaseConvID)
2913     << Derived << Base << PathDisplayStr << Range << Name;
2914   }
2915   return true;
2916 }
2917 
2918 bool
2919 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2920                                    SourceLocation Loc, SourceRange Range,
2921                                    CXXCastPath *BasePath,
2922                                    bool IgnoreAccess) {
2923   return CheckDerivedToBaseConversion(
2924       Derived, Base, diag::err_upcast_to_inaccessible_base,
2925       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2926       BasePath, IgnoreAccess);
2927 }
2928 
2929 
2930 /// Builds a string representing ambiguous paths from a
2931 /// specific derived class to different subobjects of the same base
2932 /// class.
2933 ///
2934 /// This function builds a string that can be used in error messages
2935 /// to show the different paths that one can take through the
2936 /// inheritance hierarchy to go from the derived class to different
2937 /// subobjects of a base class. The result looks something like this:
2938 /// @code
2939 /// struct D -> struct B -> struct A
2940 /// struct D -> struct C -> struct A
2941 /// @endcode
2942 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2943   std::string PathDisplayStr;
2944   std::set<unsigned> DisplayedPaths;
2945   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2946        Path != Paths.end(); ++Path) {
2947     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2948       // We haven't displayed a path to this particular base
2949       // class subobject yet.
2950       PathDisplayStr += "\n    ";
2951       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2952       for (CXXBasePath::const_iterator Element = Path->begin();
2953            Element != Path->end(); ++Element)
2954         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2955     }
2956   }
2957 
2958   return PathDisplayStr;
2959 }
2960 
2961 //===----------------------------------------------------------------------===//
2962 // C++ class member Handling
2963 //===----------------------------------------------------------------------===//
2964 
2965 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2966 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2967                                 SourceLocation ColonLoc,
2968                                 const ParsedAttributesView &Attrs) {
2969   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2970   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2971                                                   ASLoc, ColonLoc);
2972   CurContext->addHiddenDecl(ASDecl);
2973   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2974 }
2975 
2976 /// CheckOverrideControl - Check C++11 override control semantics.
2977 void Sema::CheckOverrideControl(NamedDecl *D) {
2978   if (D->isInvalidDecl())
2979     return;
2980 
2981   // We only care about "override" and "final" declarations.
2982   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2983     return;
2984 
2985   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2986 
2987   // We can't check dependent instance methods.
2988   if (MD && MD->isInstance() &&
2989       (MD->getParent()->hasAnyDependentBases() ||
2990        MD->getType()->isDependentType()))
2991     return;
2992 
2993   if (MD && !MD->isVirtual()) {
2994     // If we have a non-virtual method, check if if hides a virtual method.
2995     // (In that case, it's most likely the method has the wrong type.)
2996     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2997     FindHiddenVirtualMethods(MD, OverloadedMethods);
2998 
2999     if (!OverloadedMethods.empty()) {
3000       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3001         Diag(OA->getLocation(),
3002              diag::override_keyword_hides_virtual_member_function)
3003           << "override" << (OverloadedMethods.size() > 1);
3004       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3005         Diag(FA->getLocation(),
3006              diag::override_keyword_hides_virtual_member_function)
3007           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3008           << (OverloadedMethods.size() > 1);
3009       }
3010       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3011       MD->setInvalidDecl();
3012       return;
3013     }
3014     // Fall through into the general case diagnostic.
3015     // FIXME: We might want to attempt typo correction here.
3016   }
3017 
3018   if (!MD || !MD->isVirtual()) {
3019     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3020       Diag(OA->getLocation(),
3021            diag::override_keyword_only_allowed_on_virtual_member_functions)
3022         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3023       D->dropAttr<OverrideAttr>();
3024     }
3025     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3026       Diag(FA->getLocation(),
3027            diag::override_keyword_only_allowed_on_virtual_member_functions)
3028         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3029         << FixItHint::CreateRemoval(FA->getLocation());
3030       D->dropAttr<FinalAttr>();
3031     }
3032     return;
3033   }
3034 
3035   // C++11 [class.virtual]p5:
3036   //   If a function is marked with the virt-specifier override and
3037   //   does not override a member function of a base class, the program is
3038   //   ill-formed.
3039   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3040   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3041     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3042       << MD->getDeclName();
3043 }
3044 
3045 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
3046   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3047     return;
3048   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3049   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3050     return;
3051 
3052   SourceLocation Loc = MD->getLocation();
3053   SourceLocation SpellingLoc = Loc;
3054   if (getSourceManager().isMacroArgExpansion(Loc))
3055     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3056   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3057   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3058       return;
3059 
3060   if (MD->size_overridden_methods() > 0) {
3061     unsigned DiagID = isa<CXXDestructorDecl>(MD)
3062                           ? diag::warn_destructor_marked_not_override_overriding
3063                           : diag::warn_function_marked_not_override_overriding;
3064     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3065     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3066     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3067   }
3068 }
3069 
3070 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3071 /// function overrides a virtual member function marked 'final', according to
3072 /// C++11 [class.virtual]p4.
3073 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3074                                                   const CXXMethodDecl *Old) {
3075   FinalAttr *FA = Old->getAttr<FinalAttr>();
3076   if (!FA)
3077     return false;
3078 
3079   Diag(New->getLocation(), diag::err_final_function_overridden)
3080     << New->getDeclName()
3081     << FA->isSpelledAsSealed();
3082   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3083   return true;
3084 }
3085 
3086 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3087   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3088   // FIXME: Destruction of ObjC lifetime types has side-effects.
3089   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3090     return !RD->isCompleteDefinition() ||
3091            !RD->hasTrivialDefaultConstructor() ||
3092            !RD->hasTrivialDestructor();
3093   return false;
3094 }
3095 
3096 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3097   ParsedAttributesView::const_iterator Itr =
3098       llvm::find_if(list, [](const ParsedAttr &AL) {
3099         return AL.isDeclspecPropertyAttribute();
3100       });
3101   if (Itr != list.end())
3102     return &*Itr;
3103   return nullptr;
3104 }
3105 
3106 // Check if there is a field shadowing.
3107 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3108                                       DeclarationName FieldName,
3109                                       const CXXRecordDecl *RD,
3110                                       bool DeclIsField) {
3111   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3112     return;
3113 
3114   // To record a shadowed field in a base
3115   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3116   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3117                            CXXBasePath &Path) {
3118     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3119     // Record an ambiguous path directly
3120     if (Bases.find(Base) != Bases.end())
3121       return true;
3122     for (const auto Field : Base->lookup(FieldName)) {
3123       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3124           Field->getAccess() != AS_private) {
3125         assert(Field->getAccess() != AS_none);
3126         assert(Bases.find(Base) == Bases.end());
3127         Bases[Base] = Field;
3128         return true;
3129       }
3130     }
3131     return false;
3132   };
3133 
3134   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3135                      /*DetectVirtual=*/true);
3136   if (!RD->lookupInBases(FieldShadowed, Paths))
3137     return;
3138 
3139   for (const auto &P : Paths) {
3140     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3141     auto It = Bases.find(Base);
3142     // Skip duplicated bases
3143     if (It == Bases.end())
3144       continue;
3145     auto BaseField = It->second;
3146     assert(BaseField->getAccess() != AS_private);
3147     if (AS_none !=
3148         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3149       Diag(Loc, diag::warn_shadow_field)
3150         << FieldName << RD << Base << DeclIsField;
3151       Diag(BaseField->getLocation(), diag::note_shadow_field);
3152       Bases.erase(It);
3153     }
3154   }
3155 }
3156 
3157 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3158 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3159 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3160 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3161 /// present (but parsing it has been deferred).
3162 NamedDecl *
3163 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3164                                MultiTemplateParamsArg TemplateParameterLists,
3165                                Expr *BW, const VirtSpecifiers &VS,
3166                                InClassInitStyle InitStyle) {
3167   const DeclSpec &DS = D.getDeclSpec();
3168   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3169   DeclarationName Name = NameInfo.getName();
3170   SourceLocation Loc = NameInfo.getLoc();
3171 
3172   // For anonymous bitfields, the location should point to the type.
3173   if (Loc.isInvalid())
3174     Loc = D.getBeginLoc();
3175 
3176   Expr *BitWidth = static_cast<Expr*>(BW);
3177 
3178   assert(isa<CXXRecordDecl>(CurContext));
3179   assert(!DS.isFriendSpecified());
3180 
3181   bool isFunc = D.isDeclarationOfFunction();
3182   const ParsedAttr *MSPropertyAttr =
3183       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3184 
3185   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3186     // The Microsoft extension __interface only permits public member functions
3187     // and prohibits constructors, destructors, operators, non-public member
3188     // functions, static methods and data members.
3189     unsigned InvalidDecl;
3190     bool ShowDeclName = true;
3191     if (!isFunc &&
3192         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3193       InvalidDecl = 0;
3194     else if (!isFunc)
3195       InvalidDecl = 1;
3196     else if (AS != AS_public)
3197       InvalidDecl = 2;
3198     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3199       InvalidDecl = 3;
3200     else switch (Name.getNameKind()) {
3201       case DeclarationName::CXXConstructorName:
3202         InvalidDecl = 4;
3203         ShowDeclName = false;
3204         break;
3205 
3206       case DeclarationName::CXXDestructorName:
3207         InvalidDecl = 5;
3208         ShowDeclName = false;
3209         break;
3210 
3211       case DeclarationName::CXXOperatorName:
3212       case DeclarationName::CXXConversionFunctionName:
3213         InvalidDecl = 6;
3214         break;
3215 
3216       default:
3217         InvalidDecl = 0;
3218         break;
3219     }
3220 
3221     if (InvalidDecl) {
3222       if (ShowDeclName)
3223         Diag(Loc, diag::err_invalid_member_in_interface)
3224           << (InvalidDecl-1) << Name;
3225       else
3226         Diag(Loc, diag::err_invalid_member_in_interface)
3227           << (InvalidDecl-1) << "";
3228       return nullptr;
3229     }
3230   }
3231 
3232   // C++ 9.2p6: A member shall not be declared to have automatic storage
3233   // duration (auto, register) or with the extern storage-class-specifier.
3234   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3235   // data members and cannot be applied to names declared const or static,
3236   // and cannot be applied to reference members.
3237   switch (DS.getStorageClassSpec()) {
3238   case DeclSpec::SCS_unspecified:
3239   case DeclSpec::SCS_typedef:
3240   case DeclSpec::SCS_static:
3241     break;
3242   case DeclSpec::SCS_mutable:
3243     if (isFunc) {
3244       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3245 
3246       // FIXME: It would be nicer if the keyword was ignored only for this
3247       // declarator. Otherwise we could get follow-up errors.
3248       D.getMutableDeclSpec().ClearStorageClassSpecs();
3249     }
3250     break;
3251   default:
3252     Diag(DS.getStorageClassSpecLoc(),
3253          diag::err_storageclass_invalid_for_member);
3254     D.getMutableDeclSpec().ClearStorageClassSpecs();
3255     break;
3256   }
3257 
3258   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3259                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3260                       !isFunc);
3261 
3262   if (DS.hasConstexprSpecifier() && isInstField) {
3263     SemaDiagnosticBuilder B =
3264         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3265     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3266     if (InitStyle == ICIS_NoInit) {
3267       B << 0 << 0;
3268       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3269         B << FixItHint::CreateRemoval(ConstexprLoc);
3270       else {
3271         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3272         D.getMutableDeclSpec().ClearConstexprSpec();
3273         const char *PrevSpec;
3274         unsigned DiagID;
3275         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3276             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3277         (void)Failed;
3278         assert(!Failed && "Making a constexpr member const shouldn't fail");
3279       }
3280     } else {
3281       B << 1;
3282       const char *PrevSpec;
3283       unsigned DiagID;
3284       if (D.getMutableDeclSpec().SetStorageClassSpec(
3285           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3286           Context.getPrintingPolicy())) {
3287         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3288                "This is the only DeclSpec that should fail to be applied");
3289         B << 1;
3290       } else {
3291         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3292         isInstField = false;
3293       }
3294     }
3295   }
3296 
3297   NamedDecl *Member;
3298   if (isInstField) {
3299     CXXScopeSpec &SS = D.getCXXScopeSpec();
3300 
3301     // Data members must have identifiers for names.
3302     if (!Name.isIdentifier()) {
3303       Diag(Loc, diag::err_bad_variable_name)
3304         << Name;
3305       return nullptr;
3306     }
3307 
3308     IdentifierInfo *II = Name.getAsIdentifierInfo();
3309 
3310     // Member field could not be with "template" keyword.
3311     // So TemplateParameterLists should be empty in this case.
3312     if (TemplateParameterLists.size()) {
3313       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3314       if (TemplateParams->size()) {
3315         // There is no such thing as a member field template.
3316         Diag(D.getIdentifierLoc(), diag::err_template_member)
3317             << II
3318             << SourceRange(TemplateParams->getTemplateLoc(),
3319                 TemplateParams->getRAngleLoc());
3320       } else {
3321         // There is an extraneous 'template<>' for this member.
3322         Diag(TemplateParams->getTemplateLoc(),
3323             diag::err_template_member_noparams)
3324             << II
3325             << SourceRange(TemplateParams->getTemplateLoc(),
3326                 TemplateParams->getRAngleLoc());
3327       }
3328       return nullptr;
3329     }
3330 
3331     if (SS.isSet() && !SS.isInvalid()) {
3332       // The user provided a superfluous scope specifier inside a class
3333       // definition:
3334       //
3335       // class X {
3336       //   int X::member;
3337       // };
3338       if (DeclContext *DC = computeDeclContext(SS, false))
3339         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3340                                      D.getName().getKind() ==
3341                                          UnqualifiedIdKind::IK_TemplateId);
3342       else
3343         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3344           << Name << SS.getRange();
3345 
3346       SS.clear();
3347     }
3348 
3349     if (MSPropertyAttr) {
3350       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3351                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3352       if (!Member)
3353         return nullptr;
3354       isInstField = false;
3355     } else {
3356       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3357                                 BitWidth, InitStyle, AS);
3358       if (!Member)
3359         return nullptr;
3360     }
3361 
3362     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3363   } else {
3364     Member = HandleDeclarator(S, D, TemplateParameterLists);
3365     if (!Member)
3366       return nullptr;
3367 
3368     // Non-instance-fields can't have a bitfield.
3369     if (BitWidth) {
3370       if (Member->isInvalidDecl()) {
3371         // don't emit another diagnostic.
3372       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3373         // C++ 9.6p3: A bit-field shall not be a static member.
3374         // "static member 'A' cannot be a bit-field"
3375         Diag(Loc, diag::err_static_not_bitfield)
3376           << Name << BitWidth->getSourceRange();
3377       } else if (isa<TypedefDecl>(Member)) {
3378         // "typedef member 'x' cannot be a bit-field"
3379         Diag(Loc, diag::err_typedef_not_bitfield)
3380           << Name << BitWidth->getSourceRange();
3381       } else {
3382         // A function typedef ("typedef int f(); f a;").
3383         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3384         Diag(Loc, diag::err_not_integral_type_bitfield)
3385           << Name << cast<ValueDecl>(Member)->getType()
3386           << BitWidth->getSourceRange();
3387       }
3388 
3389       BitWidth = nullptr;
3390       Member->setInvalidDecl();
3391     }
3392 
3393     NamedDecl *NonTemplateMember = Member;
3394     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3395       NonTemplateMember = FunTmpl->getTemplatedDecl();
3396     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3397       NonTemplateMember = VarTmpl->getTemplatedDecl();
3398 
3399     Member->setAccess(AS);
3400 
3401     // If we have declared a member function template or static data member
3402     // template, set the access of the templated declaration as well.
3403     if (NonTemplateMember != Member)
3404       NonTemplateMember->setAccess(AS);
3405 
3406     // C++ [temp.deduct.guide]p3:
3407     //   A deduction guide [...] for a member class template [shall be
3408     //   declared] with the same access [as the template].
3409     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3410       auto *TD = DG->getDeducedTemplate();
3411       // Access specifiers are only meaningful if both the template and the
3412       // deduction guide are from the same scope.
3413       if (AS != TD->getAccess() &&
3414           TD->getDeclContext()->getRedeclContext()->Equals(
3415               DG->getDeclContext()->getRedeclContext())) {
3416         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3417         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3418             << TD->getAccess();
3419         const AccessSpecDecl *LastAccessSpec = nullptr;
3420         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3421           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3422             LastAccessSpec = AccessSpec;
3423         }
3424         assert(LastAccessSpec && "differing access with no access specifier");
3425         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3426             << AS;
3427       }
3428     }
3429   }
3430 
3431   if (VS.isOverrideSpecified())
3432     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3433                                          AttributeCommonInfo::AS_Keyword));
3434   if (VS.isFinalSpecified())
3435     Member->addAttr(FinalAttr::Create(
3436         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3437         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3438 
3439   if (VS.getLastLocation().isValid()) {
3440     // Update the end location of a method that has a virt-specifiers.
3441     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3442       MD->setRangeEnd(VS.getLastLocation());
3443   }
3444 
3445   CheckOverrideControl(Member);
3446 
3447   assert((Name || isInstField) && "No identifier for non-field ?");
3448 
3449   if (isInstField) {
3450     FieldDecl *FD = cast<FieldDecl>(Member);
3451     FieldCollector->Add(FD);
3452 
3453     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3454       // Remember all explicit private FieldDecls that have a name, no side
3455       // effects and are not part of a dependent type declaration.
3456       if (!FD->isImplicit() && FD->getDeclName() &&
3457           FD->getAccess() == AS_private &&
3458           !FD->hasAttr<UnusedAttr>() &&
3459           !FD->getParent()->isDependentContext() &&
3460           !InitializationHasSideEffects(*FD))
3461         UnusedPrivateFields.insert(FD);
3462     }
3463   }
3464 
3465   return Member;
3466 }
3467 
3468 namespace {
3469   class UninitializedFieldVisitor
3470       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3471     Sema &S;
3472     // List of Decls to generate a warning on.  Also remove Decls that become
3473     // initialized.
3474     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3475     // List of base classes of the record.  Classes are removed after their
3476     // initializers.
3477     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3478     // Vector of decls to be removed from the Decl set prior to visiting the
3479     // nodes.  These Decls may have been initialized in the prior initializer.
3480     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3481     // If non-null, add a note to the warning pointing back to the constructor.
3482     const CXXConstructorDecl *Constructor;
3483     // Variables to hold state when processing an initializer list.  When
3484     // InitList is true, special case initialization of FieldDecls matching
3485     // InitListFieldDecl.
3486     bool InitList;
3487     FieldDecl *InitListFieldDecl;
3488     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3489 
3490   public:
3491     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3492     UninitializedFieldVisitor(Sema &S,
3493                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3494                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3495       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3496         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3497 
3498     // Returns true if the use of ME is not an uninitialized use.
3499     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3500                                          bool CheckReferenceOnly) {
3501       llvm::SmallVector<FieldDecl*, 4> Fields;
3502       bool ReferenceField = false;
3503       while (ME) {
3504         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3505         if (!FD)
3506           return false;
3507         Fields.push_back(FD);
3508         if (FD->getType()->isReferenceType())
3509           ReferenceField = true;
3510         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3511       }
3512 
3513       // Binding a reference to an uninitialized field is not an
3514       // uninitialized use.
3515       if (CheckReferenceOnly && !ReferenceField)
3516         return true;
3517 
3518       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3519       // Discard the first field since it is the field decl that is being
3520       // initialized.
3521       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3522         UsedFieldIndex.push_back((*I)->getFieldIndex());
3523       }
3524 
3525       for (auto UsedIter = UsedFieldIndex.begin(),
3526                 UsedEnd = UsedFieldIndex.end(),
3527                 OrigIter = InitFieldIndex.begin(),
3528                 OrigEnd = InitFieldIndex.end();
3529            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3530         if (*UsedIter < *OrigIter)
3531           return true;
3532         if (*UsedIter > *OrigIter)
3533           break;
3534       }
3535 
3536       return false;
3537     }
3538 
3539     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3540                           bool AddressOf) {
3541       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3542         return;
3543 
3544       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3545       // or union.
3546       MemberExpr *FieldME = ME;
3547 
3548       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3549 
3550       Expr *Base = ME;
3551       while (MemberExpr *SubME =
3552                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3553 
3554         if (isa<VarDecl>(SubME->getMemberDecl()))
3555           return;
3556 
3557         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3558           if (!FD->isAnonymousStructOrUnion())
3559             FieldME = SubME;
3560 
3561         if (!FieldME->getType().isPODType(S.Context))
3562           AllPODFields = false;
3563 
3564         Base = SubME->getBase();
3565       }
3566 
3567       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3568         return;
3569 
3570       if (AddressOf && AllPODFields)
3571         return;
3572 
3573       ValueDecl* FoundVD = FieldME->getMemberDecl();
3574 
3575       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3576         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3577           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3578         }
3579 
3580         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3581           QualType T = BaseCast->getType();
3582           if (T->isPointerType() &&
3583               BaseClasses.count(T->getPointeeType())) {
3584             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3585                 << T->getPointeeType() << FoundVD;
3586           }
3587         }
3588       }
3589 
3590       if (!Decls.count(FoundVD))
3591         return;
3592 
3593       const bool IsReference = FoundVD->getType()->isReferenceType();
3594 
3595       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3596         // Special checking for initializer lists.
3597         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3598           return;
3599         }
3600       } else {
3601         // Prevent double warnings on use of unbounded references.
3602         if (CheckReferenceOnly && !IsReference)
3603           return;
3604       }
3605 
3606       unsigned diag = IsReference
3607           ? diag::warn_reference_field_is_uninit
3608           : diag::warn_field_is_uninit;
3609       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3610       if (Constructor)
3611         S.Diag(Constructor->getLocation(),
3612                diag::note_uninit_in_this_constructor)
3613           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3614 
3615     }
3616 
3617     void HandleValue(Expr *E, bool AddressOf) {
3618       E = E->IgnoreParens();
3619 
3620       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3621         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3622                          AddressOf /*AddressOf*/);
3623         return;
3624       }
3625 
3626       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3627         Visit(CO->getCond());
3628         HandleValue(CO->getTrueExpr(), AddressOf);
3629         HandleValue(CO->getFalseExpr(), AddressOf);
3630         return;
3631       }
3632 
3633       if (BinaryConditionalOperator *BCO =
3634               dyn_cast<BinaryConditionalOperator>(E)) {
3635         Visit(BCO->getCond());
3636         HandleValue(BCO->getFalseExpr(), AddressOf);
3637         return;
3638       }
3639 
3640       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3641         HandleValue(OVE->getSourceExpr(), AddressOf);
3642         return;
3643       }
3644 
3645       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3646         switch (BO->getOpcode()) {
3647         default:
3648           break;
3649         case(BO_PtrMemD):
3650         case(BO_PtrMemI):
3651           HandleValue(BO->getLHS(), AddressOf);
3652           Visit(BO->getRHS());
3653           return;
3654         case(BO_Comma):
3655           Visit(BO->getLHS());
3656           HandleValue(BO->getRHS(), AddressOf);
3657           return;
3658         }
3659       }
3660 
3661       Visit(E);
3662     }
3663 
3664     void CheckInitListExpr(InitListExpr *ILE) {
3665       InitFieldIndex.push_back(0);
3666       for (auto Child : ILE->children()) {
3667         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3668           CheckInitListExpr(SubList);
3669         } else {
3670           Visit(Child);
3671         }
3672         ++InitFieldIndex.back();
3673       }
3674       InitFieldIndex.pop_back();
3675     }
3676 
3677     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3678                           FieldDecl *Field, const Type *BaseClass) {
3679       // Remove Decls that may have been initialized in the previous
3680       // initializer.
3681       for (ValueDecl* VD : DeclsToRemove)
3682         Decls.erase(VD);
3683       DeclsToRemove.clear();
3684 
3685       Constructor = FieldConstructor;
3686       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3687 
3688       if (ILE && Field) {
3689         InitList = true;
3690         InitListFieldDecl = Field;
3691         InitFieldIndex.clear();
3692         CheckInitListExpr(ILE);
3693       } else {
3694         InitList = false;
3695         Visit(E);
3696       }
3697 
3698       if (Field)
3699         Decls.erase(Field);
3700       if (BaseClass)
3701         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3702     }
3703 
3704     void VisitMemberExpr(MemberExpr *ME) {
3705       // All uses of unbounded reference fields will warn.
3706       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3707     }
3708 
3709     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3710       if (E->getCastKind() == CK_LValueToRValue) {
3711         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3712         return;
3713       }
3714 
3715       Inherited::VisitImplicitCastExpr(E);
3716     }
3717 
3718     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3719       if (E->getConstructor()->isCopyConstructor()) {
3720         Expr *ArgExpr = E->getArg(0);
3721         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3722           if (ILE->getNumInits() == 1)
3723             ArgExpr = ILE->getInit(0);
3724         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3725           if (ICE->getCastKind() == CK_NoOp)
3726             ArgExpr = ICE->getSubExpr();
3727         HandleValue(ArgExpr, false /*AddressOf*/);
3728         return;
3729       }
3730       Inherited::VisitCXXConstructExpr(E);
3731     }
3732 
3733     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3734       Expr *Callee = E->getCallee();
3735       if (isa<MemberExpr>(Callee)) {
3736         HandleValue(Callee, false /*AddressOf*/);
3737         for (auto Arg : E->arguments())
3738           Visit(Arg);
3739         return;
3740       }
3741 
3742       Inherited::VisitCXXMemberCallExpr(E);
3743     }
3744 
3745     void VisitCallExpr(CallExpr *E) {
3746       // Treat std::move as a use.
3747       if (E->isCallToStdMove()) {
3748         HandleValue(E->getArg(0), /*AddressOf=*/false);
3749         return;
3750       }
3751 
3752       Inherited::VisitCallExpr(E);
3753     }
3754 
3755     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3756       Expr *Callee = E->getCallee();
3757 
3758       if (isa<UnresolvedLookupExpr>(Callee))
3759         return Inherited::VisitCXXOperatorCallExpr(E);
3760 
3761       Visit(Callee);
3762       for (auto Arg : E->arguments())
3763         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3764     }
3765 
3766     void VisitBinaryOperator(BinaryOperator *E) {
3767       // If a field assignment is detected, remove the field from the
3768       // uninitiailized field set.
3769       if (E->getOpcode() == BO_Assign)
3770         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3771           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3772             if (!FD->getType()->isReferenceType())
3773               DeclsToRemove.push_back(FD);
3774 
3775       if (E->isCompoundAssignmentOp()) {
3776         HandleValue(E->getLHS(), false /*AddressOf*/);
3777         Visit(E->getRHS());
3778         return;
3779       }
3780 
3781       Inherited::VisitBinaryOperator(E);
3782     }
3783 
3784     void VisitUnaryOperator(UnaryOperator *E) {
3785       if (E->isIncrementDecrementOp()) {
3786         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3787         return;
3788       }
3789       if (E->getOpcode() == UO_AddrOf) {
3790         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3791           HandleValue(ME->getBase(), true /*AddressOf*/);
3792           return;
3793         }
3794       }
3795 
3796       Inherited::VisitUnaryOperator(E);
3797     }
3798   };
3799 
3800   // Diagnose value-uses of fields to initialize themselves, e.g.
3801   //   foo(foo)
3802   // where foo is not also a parameter to the constructor.
3803   // Also diagnose across field uninitialized use such as
3804   //   x(y), y(x)
3805   // TODO: implement -Wuninitialized and fold this into that framework.
3806   static void DiagnoseUninitializedFields(
3807       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3808 
3809     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3810                                            Constructor->getLocation())) {
3811       return;
3812     }
3813 
3814     if (Constructor->isInvalidDecl())
3815       return;
3816 
3817     const CXXRecordDecl *RD = Constructor->getParent();
3818 
3819     if (RD->isDependentContext())
3820       return;
3821 
3822     // Holds fields that are uninitialized.
3823     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3824 
3825     // At the beginning, all fields are uninitialized.
3826     for (auto *I : RD->decls()) {
3827       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3828         UninitializedFields.insert(FD);
3829       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3830         UninitializedFields.insert(IFD->getAnonField());
3831       }
3832     }
3833 
3834     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3835     for (auto I : RD->bases())
3836       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3837 
3838     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3839       return;
3840 
3841     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3842                                                    UninitializedFields,
3843                                                    UninitializedBaseClasses);
3844 
3845     for (const auto *FieldInit : Constructor->inits()) {
3846       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3847         break;
3848 
3849       Expr *InitExpr = FieldInit->getInit();
3850       if (!InitExpr)
3851         continue;
3852 
3853       if (CXXDefaultInitExpr *Default =
3854               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3855         InitExpr = Default->getExpr();
3856         if (!InitExpr)
3857           continue;
3858         // In class initializers will point to the constructor.
3859         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3860                                               FieldInit->getAnyMember(),
3861                                               FieldInit->getBaseClass());
3862       } else {
3863         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3864                                               FieldInit->getAnyMember(),
3865                                               FieldInit->getBaseClass());
3866       }
3867     }
3868   }
3869 } // namespace
3870 
3871 /// Enter a new C++ default initializer scope. After calling this, the
3872 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3873 /// parsing or instantiating the initializer failed.
3874 void Sema::ActOnStartCXXInClassMemberInitializer() {
3875   // Create a synthetic function scope to represent the call to the constructor
3876   // that notionally surrounds a use of this initializer.
3877   PushFunctionScope();
3878 }
3879 
3880 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3881   if (!D.isFunctionDeclarator())
3882     return;
3883   auto &FTI = D.getFunctionTypeInfo();
3884   if (!FTI.Params)
3885     return;
3886   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3887                                                           FTI.NumParams)) {
3888     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3889     if (ParamDecl->getDeclName())
3890       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3891   }
3892 }
3893 
3894 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3895   if (ConstraintExpr.isInvalid())
3896     return ExprError();
3897   return CorrectDelayedTyposInExpr(ConstraintExpr);
3898 }
3899 
3900 /// This is invoked after parsing an in-class initializer for a
3901 /// non-static C++ class member, and after instantiating an in-class initializer
3902 /// in a class template. Such actions are deferred until the class is complete.
3903 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3904                                                   SourceLocation InitLoc,
3905                                                   Expr *InitExpr) {
3906   // Pop the notional constructor scope we created earlier.
3907   PopFunctionScopeInfo(nullptr, D);
3908 
3909   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3910   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3911          "must set init style when field is created");
3912 
3913   if (!InitExpr) {
3914     D->setInvalidDecl();
3915     if (FD)
3916       FD->removeInClassInitializer();
3917     return;
3918   }
3919 
3920   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3921     FD->setInvalidDecl();
3922     FD->removeInClassInitializer();
3923     return;
3924   }
3925 
3926   ExprResult Init = InitExpr;
3927   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3928     InitializedEntity Entity =
3929         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3930     InitializationKind Kind =
3931         FD->getInClassInitStyle() == ICIS_ListInit
3932             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3933                                                    InitExpr->getBeginLoc(),
3934                                                    InitExpr->getEndLoc())
3935             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3936     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3937     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3938     if (Init.isInvalid()) {
3939       FD->setInvalidDecl();
3940       return;
3941     }
3942   }
3943 
3944   // C++11 [class.base.init]p7:
3945   //   The initialization of each base and member constitutes a
3946   //   full-expression.
3947   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3948   if (Init.isInvalid()) {
3949     FD->setInvalidDecl();
3950     return;
3951   }
3952 
3953   InitExpr = Init.get();
3954 
3955   FD->setInClassInitializer(InitExpr);
3956 }
3957 
3958 /// Find the direct and/or virtual base specifiers that
3959 /// correspond to the given base type, for use in base initialization
3960 /// within a constructor.
3961 static bool FindBaseInitializer(Sema &SemaRef,
3962                                 CXXRecordDecl *ClassDecl,
3963                                 QualType BaseType,
3964                                 const CXXBaseSpecifier *&DirectBaseSpec,
3965                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3966   // First, check for a direct base class.
3967   DirectBaseSpec = nullptr;
3968   for (const auto &Base : ClassDecl->bases()) {
3969     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3970       // We found a direct base of this type. That's what we're
3971       // initializing.
3972       DirectBaseSpec = &Base;
3973       break;
3974     }
3975   }
3976 
3977   // Check for a virtual base class.
3978   // FIXME: We might be able to short-circuit this if we know in advance that
3979   // there are no virtual bases.
3980   VirtualBaseSpec = nullptr;
3981   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3982     // We haven't found a base yet; search the class hierarchy for a
3983     // virtual base class.
3984     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3985                        /*DetectVirtual=*/false);
3986     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3987                               SemaRef.Context.getTypeDeclType(ClassDecl),
3988                               BaseType, Paths)) {
3989       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3990            Path != Paths.end(); ++Path) {
3991         if (Path->back().Base->isVirtual()) {
3992           VirtualBaseSpec = Path->back().Base;
3993           break;
3994         }
3995       }
3996     }
3997   }
3998 
3999   return DirectBaseSpec || VirtualBaseSpec;
4000 }
4001 
4002 /// Handle a C++ member initializer using braced-init-list syntax.
4003 MemInitResult
4004 Sema::ActOnMemInitializer(Decl *ConstructorD,
4005                           Scope *S,
4006                           CXXScopeSpec &SS,
4007                           IdentifierInfo *MemberOrBase,
4008                           ParsedType TemplateTypeTy,
4009                           const DeclSpec &DS,
4010                           SourceLocation IdLoc,
4011                           Expr *InitList,
4012                           SourceLocation EllipsisLoc) {
4013   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4014                              DS, IdLoc, InitList,
4015                              EllipsisLoc);
4016 }
4017 
4018 /// Handle a C++ member initializer using parentheses syntax.
4019 MemInitResult
4020 Sema::ActOnMemInitializer(Decl *ConstructorD,
4021                           Scope *S,
4022                           CXXScopeSpec &SS,
4023                           IdentifierInfo *MemberOrBase,
4024                           ParsedType TemplateTypeTy,
4025                           const DeclSpec &DS,
4026                           SourceLocation IdLoc,
4027                           SourceLocation LParenLoc,
4028                           ArrayRef<Expr *> Args,
4029                           SourceLocation RParenLoc,
4030                           SourceLocation EllipsisLoc) {
4031   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4032   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4033                              DS, IdLoc, List, EllipsisLoc);
4034 }
4035 
4036 namespace {
4037 
4038 // Callback to only accept typo corrections that can be a valid C++ member
4039 // intializer: either a non-static field member or a base class.
4040 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4041 public:
4042   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4043       : ClassDecl(ClassDecl) {}
4044 
4045   bool ValidateCandidate(const TypoCorrection &candidate) override {
4046     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4047       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4048         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4049       return isa<TypeDecl>(ND);
4050     }
4051     return false;
4052   }
4053 
4054   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4055     return std::make_unique<MemInitializerValidatorCCC>(*this);
4056   }
4057 
4058 private:
4059   CXXRecordDecl *ClassDecl;
4060 };
4061 
4062 }
4063 
4064 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4065                                              CXXScopeSpec &SS,
4066                                              ParsedType TemplateTypeTy,
4067                                              IdentifierInfo *MemberOrBase) {
4068   if (SS.getScopeRep() || TemplateTypeTy)
4069     return nullptr;
4070   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4071   if (Result.empty())
4072     return nullptr;
4073   ValueDecl *Member;
4074   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4075       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4076     return Member;
4077   return nullptr;
4078 }
4079 
4080 /// Handle a C++ member initializer.
4081 MemInitResult
4082 Sema::BuildMemInitializer(Decl *ConstructorD,
4083                           Scope *S,
4084                           CXXScopeSpec &SS,
4085                           IdentifierInfo *MemberOrBase,
4086                           ParsedType TemplateTypeTy,
4087                           const DeclSpec &DS,
4088                           SourceLocation IdLoc,
4089                           Expr *Init,
4090                           SourceLocation EllipsisLoc) {
4091   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4092   if (!Res.isUsable())
4093     return true;
4094   Init = Res.get();
4095 
4096   if (!ConstructorD)
4097     return true;
4098 
4099   AdjustDeclIfTemplate(ConstructorD);
4100 
4101   CXXConstructorDecl *Constructor
4102     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4103   if (!Constructor) {
4104     // The user wrote a constructor initializer on a function that is
4105     // not a C++ constructor. Ignore the error for now, because we may
4106     // have more member initializers coming; we'll diagnose it just
4107     // once in ActOnMemInitializers.
4108     return true;
4109   }
4110 
4111   CXXRecordDecl *ClassDecl = Constructor->getParent();
4112 
4113   // C++ [class.base.init]p2:
4114   //   Names in a mem-initializer-id are looked up in the scope of the
4115   //   constructor's class and, if not found in that scope, are looked
4116   //   up in the scope containing the constructor's definition.
4117   //   [Note: if the constructor's class contains a member with the
4118   //   same name as a direct or virtual base class of the class, a
4119   //   mem-initializer-id naming the member or base class and composed
4120   //   of a single identifier refers to the class member. A
4121   //   mem-initializer-id for the hidden base class may be specified
4122   //   using a qualified name. ]
4123 
4124   // Look for a member, first.
4125   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4126           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4127     if (EllipsisLoc.isValid())
4128       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4129           << MemberOrBase
4130           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4131 
4132     return BuildMemberInitializer(Member, Init, IdLoc);
4133   }
4134   // It didn't name a member, so see if it names a class.
4135   QualType BaseType;
4136   TypeSourceInfo *TInfo = nullptr;
4137 
4138   if (TemplateTypeTy) {
4139     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4140     if (BaseType.isNull())
4141       return true;
4142   } else if (DS.getTypeSpecType() == TST_decltype) {
4143     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4144   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4145     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4146     return true;
4147   } else {
4148     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4149     LookupParsedName(R, S, &SS);
4150 
4151     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4152     if (!TyD) {
4153       if (R.isAmbiguous()) return true;
4154 
4155       // We don't want access-control diagnostics here.
4156       R.suppressDiagnostics();
4157 
4158       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4159         bool NotUnknownSpecialization = false;
4160         DeclContext *DC = computeDeclContext(SS, false);
4161         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4162           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4163 
4164         if (!NotUnknownSpecialization) {
4165           // When the scope specifier can refer to a member of an unknown
4166           // specialization, we take it as a type name.
4167           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4168                                        SS.getWithLocInContext(Context),
4169                                        *MemberOrBase, IdLoc);
4170           if (BaseType.isNull())
4171             return true;
4172 
4173           TInfo = Context.CreateTypeSourceInfo(BaseType);
4174           DependentNameTypeLoc TL =
4175               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4176           if (!TL.isNull()) {
4177             TL.setNameLoc(IdLoc);
4178             TL.setElaboratedKeywordLoc(SourceLocation());
4179             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4180           }
4181 
4182           R.clear();
4183           R.setLookupName(MemberOrBase);
4184         }
4185       }
4186 
4187       // If no results were found, try to correct typos.
4188       TypoCorrection Corr;
4189       MemInitializerValidatorCCC CCC(ClassDecl);
4190       if (R.empty() && BaseType.isNull() &&
4191           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4192                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4193         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4194           // We have found a non-static data member with a similar
4195           // name to what was typed; complain and initialize that
4196           // member.
4197           diagnoseTypo(Corr,
4198                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4199                          << MemberOrBase << true);
4200           return BuildMemberInitializer(Member, Init, IdLoc);
4201         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4202           const CXXBaseSpecifier *DirectBaseSpec;
4203           const CXXBaseSpecifier *VirtualBaseSpec;
4204           if (FindBaseInitializer(*this, ClassDecl,
4205                                   Context.getTypeDeclType(Type),
4206                                   DirectBaseSpec, VirtualBaseSpec)) {
4207             // We have found a direct or virtual base class with a
4208             // similar name to what was typed; complain and initialize
4209             // that base class.
4210             diagnoseTypo(Corr,
4211                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4212                            << MemberOrBase << false,
4213                          PDiag() /*Suppress note, we provide our own.*/);
4214 
4215             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4216                                                               : VirtualBaseSpec;
4217             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4218                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4219 
4220             TyD = Type;
4221           }
4222         }
4223       }
4224 
4225       if (!TyD && BaseType.isNull()) {
4226         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4227           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4228         return true;
4229       }
4230     }
4231 
4232     if (BaseType.isNull()) {
4233       BaseType = Context.getTypeDeclType(TyD);
4234       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4235       if (SS.isSet()) {
4236         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4237                                              BaseType);
4238         TInfo = Context.CreateTypeSourceInfo(BaseType);
4239         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4240         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4241         TL.setElaboratedKeywordLoc(SourceLocation());
4242         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4243       }
4244     }
4245   }
4246 
4247   if (!TInfo)
4248     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4249 
4250   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4251 }
4252 
4253 MemInitResult
4254 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4255                              SourceLocation IdLoc) {
4256   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4257   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4258   assert((DirectMember || IndirectMember) &&
4259          "Member must be a FieldDecl or IndirectFieldDecl");
4260 
4261   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4262     return true;
4263 
4264   if (Member->isInvalidDecl())
4265     return true;
4266 
4267   MultiExprArg Args;
4268   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4269     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4270   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4271     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4272   } else {
4273     // Template instantiation doesn't reconstruct ParenListExprs for us.
4274     Args = Init;
4275   }
4276 
4277   SourceRange InitRange = Init->getSourceRange();
4278 
4279   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4280     // Can't check initialization for a member of dependent type or when
4281     // any of the arguments are type-dependent expressions.
4282     DiscardCleanupsInEvaluationContext();
4283   } else {
4284     bool InitList = false;
4285     if (isa<InitListExpr>(Init)) {
4286       InitList = true;
4287       Args = Init;
4288     }
4289 
4290     // Initialize the member.
4291     InitializedEntity MemberEntity =
4292       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4293                    : InitializedEntity::InitializeMember(IndirectMember,
4294                                                          nullptr);
4295     InitializationKind Kind =
4296         InitList ? InitializationKind::CreateDirectList(
4297                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4298                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4299                                                     InitRange.getEnd());
4300 
4301     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4302     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4303                                             nullptr);
4304     if (MemberInit.isInvalid())
4305       return true;
4306 
4307     // C++11 [class.base.init]p7:
4308     //   The initialization of each base and member constitutes a
4309     //   full-expression.
4310     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4311                                      /*DiscardedValue*/ false);
4312     if (MemberInit.isInvalid())
4313       return true;
4314 
4315     Init = MemberInit.get();
4316   }
4317 
4318   if (DirectMember) {
4319     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4320                                             InitRange.getBegin(), Init,
4321                                             InitRange.getEnd());
4322   } else {
4323     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4324                                             InitRange.getBegin(), Init,
4325                                             InitRange.getEnd());
4326   }
4327 }
4328 
4329 MemInitResult
4330 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4331                                  CXXRecordDecl *ClassDecl) {
4332   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4333   if (!LangOpts.CPlusPlus11)
4334     return Diag(NameLoc, diag::err_delegating_ctor)
4335       << TInfo->getTypeLoc().getLocalSourceRange();
4336   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4337 
4338   bool InitList = true;
4339   MultiExprArg Args = Init;
4340   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4341     InitList = false;
4342     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4343   }
4344 
4345   SourceRange InitRange = Init->getSourceRange();
4346   // Initialize the object.
4347   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4348                                      QualType(ClassDecl->getTypeForDecl(), 0));
4349   InitializationKind Kind =
4350       InitList ? InitializationKind::CreateDirectList(
4351                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4352                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4353                                                   InitRange.getEnd());
4354   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4355   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4356                                               Args, nullptr);
4357   if (DelegationInit.isInvalid())
4358     return true;
4359 
4360   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4361          "Delegating constructor with no target?");
4362 
4363   // C++11 [class.base.init]p7:
4364   //   The initialization of each base and member constitutes a
4365   //   full-expression.
4366   DelegationInit = ActOnFinishFullExpr(
4367       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4368   if (DelegationInit.isInvalid())
4369     return true;
4370 
4371   // If we are in a dependent context, template instantiation will
4372   // perform this type-checking again. Just save the arguments that we
4373   // received in a ParenListExpr.
4374   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4375   // of the information that we have about the base
4376   // initializer. However, deconstructing the ASTs is a dicey process,
4377   // and this approach is far more likely to get the corner cases right.
4378   if (CurContext->isDependentContext())
4379     DelegationInit = Init;
4380 
4381   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4382                                           DelegationInit.getAs<Expr>(),
4383                                           InitRange.getEnd());
4384 }
4385 
4386 MemInitResult
4387 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4388                            Expr *Init, CXXRecordDecl *ClassDecl,
4389                            SourceLocation EllipsisLoc) {
4390   SourceLocation BaseLoc
4391     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4392 
4393   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4394     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4395              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4396 
4397   // C++ [class.base.init]p2:
4398   //   [...] Unless the mem-initializer-id names a nonstatic data
4399   //   member of the constructor's class or a direct or virtual base
4400   //   of that class, the mem-initializer is ill-formed. A
4401   //   mem-initializer-list can initialize a base class using any
4402   //   name that denotes that base class type.
4403   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4404 
4405   SourceRange InitRange = Init->getSourceRange();
4406   if (EllipsisLoc.isValid()) {
4407     // This is a pack expansion.
4408     if (!BaseType->containsUnexpandedParameterPack())  {
4409       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4410         << SourceRange(BaseLoc, InitRange.getEnd());
4411 
4412       EllipsisLoc = SourceLocation();
4413     }
4414   } else {
4415     // Check for any unexpanded parameter packs.
4416     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4417       return true;
4418 
4419     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4420       return true;
4421   }
4422 
4423   // Check for direct and virtual base classes.
4424   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4425   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4426   if (!Dependent) {
4427     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4428                                        BaseType))
4429       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4430 
4431     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4432                         VirtualBaseSpec);
4433 
4434     // C++ [base.class.init]p2:
4435     // Unless the mem-initializer-id names a nonstatic data member of the
4436     // constructor's class or a direct or virtual base of that class, the
4437     // mem-initializer is ill-formed.
4438     if (!DirectBaseSpec && !VirtualBaseSpec) {
4439       // If the class has any dependent bases, then it's possible that
4440       // one of those types will resolve to the same type as
4441       // BaseType. Therefore, just treat this as a dependent base
4442       // class initialization.  FIXME: Should we try to check the
4443       // initialization anyway? It seems odd.
4444       if (ClassDecl->hasAnyDependentBases())
4445         Dependent = true;
4446       else
4447         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4448           << BaseType << Context.getTypeDeclType(ClassDecl)
4449           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4450     }
4451   }
4452 
4453   if (Dependent) {
4454     DiscardCleanupsInEvaluationContext();
4455 
4456     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4457                                             /*IsVirtual=*/false,
4458                                             InitRange.getBegin(), Init,
4459                                             InitRange.getEnd(), EllipsisLoc);
4460   }
4461 
4462   // C++ [base.class.init]p2:
4463   //   If a mem-initializer-id is ambiguous because it designates both
4464   //   a direct non-virtual base class and an inherited virtual base
4465   //   class, the mem-initializer is ill-formed.
4466   if (DirectBaseSpec && VirtualBaseSpec)
4467     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4468       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4469 
4470   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4471   if (!BaseSpec)
4472     BaseSpec = VirtualBaseSpec;
4473 
4474   // Initialize the base.
4475   bool InitList = true;
4476   MultiExprArg Args = Init;
4477   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4478     InitList = false;
4479     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4480   }
4481 
4482   InitializedEntity BaseEntity =
4483     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4484   InitializationKind Kind =
4485       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4486                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4487                                                   InitRange.getEnd());
4488   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4489   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4490   if (BaseInit.isInvalid())
4491     return true;
4492 
4493   // C++11 [class.base.init]p7:
4494   //   The initialization of each base and member constitutes a
4495   //   full-expression.
4496   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4497                                  /*DiscardedValue*/ false);
4498   if (BaseInit.isInvalid())
4499     return true;
4500 
4501   // If we are in a dependent context, template instantiation will
4502   // perform this type-checking again. Just save the arguments that we
4503   // received in a ParenListExpr.
4504   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4505   // of the information that we have about the base
4506   // initializer. However, deconstructing the ASTs is a dicey process,
4507   // and this approach is far more likely to get the corner cases right.
4508   if (CurContext->isDependentContext())
4509     BaseInit = Init;
4510 
4511   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4512                                           BaseSpec->isVirtual(),
4513                                           InitRange.getBegin(),
4514                                           BaseInit.getAs<Expr>(),
4515                                           InitRange.getEnd(), EllipsisLoc);
4516 }
4517 
4518 // Create a static_cast\<T&&>(expr).
4519 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4520   if (T.isNull()) T = E->getType();
4521   QualType TargetType = SemaRef.BuildReferenceType(
4522       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4523   SourceLocation ExprLoc = E->getBeginLoc();
4524   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4525       TargetType, ExprLoc);
4526 
4527   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4528                                    SourceRange(ExprLoc, ExprLoc),
4529                                    E->getSourceRange()).get();
4530 }
4531 
4532 /// ImplicitInitializerKind - How an implicit base or member initializer should
4533 /// initialize its base or member.
4534 enum ImplicitInitializerKind {
4535   IIK_Default,
4536   IIK_Copy,
4537   IIK_Move,
4538   IIK_Inherit
4539 };
4540 
4541 static bool
4542 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4543                              ImplicitInitializerKind ImplicitInitKind,
4544                              CXXBaseSpecifier *BaseSpec,
4545                              bool IsInheritedVirtualBase,
4546                              CXXCtorInitializer *&CXXBaseInit) {
4547   InitializedEntity InitEntity
4548     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4549                                         IsInheritedVirtualBase);
4550 
4551   ExprResult BaseInit;
4552 
4553   switch (ImplicitInitKind) {
4554   case IIK_Inherit:
4555   case IIK_Default: {
4556     InitializationKind InitKind
4557       = InitializationKind::CreateDefault(Constructor->getLocation());
4558     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4559     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4560     break;
4561   }
4562 
4563   case IIK_Move:
4564   case IIK_Copy: {
4565     bool Moving = ImplicitInitKind == IIK_Move;
4566     ParmVarDecl *Param = Constructor->getParamDecl(0);
4567     QualType ParamType = Param->getType().getNonReferenceType();
4568 
4569     Expr *CopyCtorArg =
4570       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4571                           SourceLocation(), Param, false,
4572                           Constructor->getLocation(), ParamType,
4573                           VK_LValue, nullptr);
4574 
4575     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4576 
4577     // Cast to the base class to avoid ambiguities.
4578     QualType ArgTy =
4579       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4580                                        ParamType.getQualifiers());
4581 
4582     if (Moving) {
4583       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4584     }
4585 
4586     CXXCastPath BasePath;
4587     BasePath.push_back(BaseSpec);
4588     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4589                                             CK_UncheckedDerivedToBase,
4590                                             Moving ? VK_XValue : VK_LValue,
4591                                             &BasePath).get();
4592 
4593     InitializationKind InitKind
4594       = InitializationKind::CreateDirect(Constructor->getLocation(),
4595                                          SourceLocation(), SourceLocation());
4596     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4597     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4598     break;
4599   }
4600   }
4601 
4602   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4603   if (BaseInit.isInvalid())
4604     return true;
4605 
4606   CXXBaseInit =
4607     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4608                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4609                                                         SourceLocation()),
4610                                              BaseSpec->isVirtual(),
4611                                              SourceLocation(),
4612                                              BaseInit.getAs<Expr>(),
4613                                              SourceLocation(),
4614                                              SourceLocation());
4615 
4616   return false;
4617 }
4618 
4619 static bool RefersToRValueRef(Expr *MemRef) {
4620   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4621   return Referenced->getType()->isRValueReferenceType();
4622 }
4623 
4624 static bool
4625 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4626                                ImplicitInitializerKind ImplicitInitKind,
4627                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4628                                CXXCtorInitializer *&CXXMemberInit) {
4629   if (Field->isInvalidDecl())
4630     return true;
4631 
4632   SourceLocation Loc = Constructor->getLocation();
4633 
4634   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4635     bool Moving = ImplicitInitKind == IIK_Move;
4636     ParmVarDecl *Param = Constructor->getParamDecl(0);
4637     QualType ParamType = Param->getType().getNonReferenceType();
4638 
4639     // Suppress copying zero-width bitfields.
4640     if (Field->isZeroLengthBitField(SemaRef.Context))
4641       return false;
4642 
4643     Expr *MemberExprBase =
4644       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4645                           SourceLocation(), Param, false,
4646                           Loc, ParamType, VK_LValue, nullptr);
4647 
4648     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4649 
4650     if (Moving) {
4651       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4652     }
4653 
4654     // Build a reference to this field within the parameter.
4655     CXXScopeSpec SS;
4656     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4657                               Sema::LookupMemberName);
4658     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4659                                   : cast<ValueDecl>(Field), AS_public);
4660     MemberLookup.resolveKind();
4661     ExprResult CtorArg
4662       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4663                                          ParamType, Loc,
4664                                          /*IsArrow=*/false,
4665                                          SS,
4666                                          /*TemplateKWLoc=*/SourceLocation(),
4667                                          /*FirstQualifierInScope=*/nullptr,
4668                                          MemberLookup,
4669                                          /*TemplateArgs=*/nullptr,
4670                                          /*S*/nullptr);
4671     if (CtorArg.isInvalid())
4672       return true;
4673 
4674     // C++11 [class.copy]p15:
4675     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4676     //     with static_cast<T&&>(x.m);
4677     if (RefersToRValueRef(CtorArg.get())) {
4678       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4679     }
4680 
4681     InitializedEntity Entity =
4682         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4683                                                        /*Implicit*/ true)
4684                  : InitializedEntity::InitializeMember(Field, nullptr,
4685                                                        /*Implicit*/ true);
4686 
4687     // Direct-initialize to use the copy constructor.
4688     InitializationKind InitKind =
4689       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4690 
4691     Expr *CtorArgE = CtorArg.getAs<Expr>();
4692     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4693     ExprResult MemberInit =
4694         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4695     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4696     if (MemberInit.isInvalid())
4697       return true;
4698 
4699     if (Indirect)
4700       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4701           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4702     else
4703       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4704           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4705     return false;
4706   }
4707 
4708   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4709          "Unhandled implicit init kind!");
4710 
4711   QualType FieldBaseElementType =
4712     SemaRef.Context.getBaseElementType(Field->getType());
4713 
4714   if (FieldBaseElementType->isRecordType()) {
4715     InitializedEntity InitEntity =
4716         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4717                                                        /*Implicit*/ true)
4718                  : InitializedEntity::InitializeMember(Field, nullptr,
4719                                                        /*Implicit*/ true);
4720     InitializationKind InitKind =
4721       InitializationKind::CreateDefault(Loc);
4722 
4723     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4724     ExprResult MemberInit =
4725       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4726 
4727     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4728     if (MemberInit.isInvalid())
4729       return true;
4730 
4731     if (Indirect)
4732       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4733                                                                Indirect, Loc,
4734                                                                Loc,
4735                                                                MemberInit.get(),
4736                                                                Loc);
4737     else
4738       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4739                                                                Field, Loc, Loc,
4740                                                                MemberInit.get(),
4741                                                                Loc);
4742     return false;
4743   }
4744 
4745   if (!Field->getParent()->isUnion()) {
4746     if (FieldBaseElementType->isReferenceType()) {
4747       SemaRef.Diag(Constructor->getLocation(),
4748                    diag::err_uninitialized_member_in_ctor)
4749       << (int)Constructor->isImplicit()
4750       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4751       << 0 << Field->getDeclName();
4752       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4753       return true;
4754     }
4755 
4756     if (FieldBaseElementType.isConstQualified()) {
4757       SemaRef.Diag(Constructor->getLocation(),
4758                    diag::err_uninitialized_member_in_ctor)
4759       << (int)Constructor->isImplicit()
4760       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4761       << 1 << Field->getDeclName();
4762       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4763       return true;
4764     }
4765   }
4766 
4767   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4768     // ARC and Weak:
4769     //   Default-initialize Objective-C pointers to NULL.
4770     CXXMemberInit
4771       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4772                                                  Loc, Loc,
4773                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4774                                                  Loc);
4775     return false;
4776   }
4777 
4778   // Nothing to initialize.
4779   CXXMemberInit = nullptr;
4780   return false;
4781 }
4782 
4783 namespace {
4784 struct BaseAndFieldInfo {
4785   Sema &S;
4786   CXXConstructorDecl *Ctor;
4787   bool AnyErrorsInInits;
4788   ImplicitInitializerKind IIK;
4789   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4790   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4791   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4792 
4793   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4794     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4795     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4796     if (Ctor->getInheritedConstructor())
4797       IIK = IIK_Inherit;
4798     else if (Generated && Ctor->isCopyConstructor())
4799       IIK = IIK_Copy;
4800     else if (Generated && Ctor->isMoveConstructor())
4801       IIK = IIK_Move;
4802     else
4803       IIK = IIK_Default;
4804   }
4805 
4806   bool isImplicitCopyOrMove() const {
4807     switch (IIK) {
4808     case IIK_Copy:
4809     case IIK_Move:
4810       return true;
4811 
4812     case IIK_Default:
4813     case IIK_Inherit:
4814       return false;
4815     }
4816 
4817     llvm_unreachable("Invalid ImplicitInitializerKind!");
4818   }
4819 
4820   bool addFieldInitializer(CXXCtorInitializer *Init) {
4821     AllToInit.push_back(Init);
4822 
4823     // Check whether this initializer makes the field "used".
4824     if (Init->getInit()->HasSideEffects(S.Context))
4825       S.UnusedPrivateFields.remove(Init->getAnyMember());
4826 
4827     return false;
4828   }
4829 
4830   bool isInactiveUnionMember(FieldDecl *Field) {
4831     RecordDecl *Record = Field->getParent();
4832     if (!Record->isUnion())
4833       return false;
4834 
4835     if (FieldDecl *Active =
4836             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4837       return Active != Field->getCanonicalDecl();
4838 
4839     // In an implicit copy or move constructor, ignore any in-class initializer.
4840     if (isImplicitCopyOrMove())
4841       return true;
4842 
4843     // If there's no explicit initialization, the field is active only if it
4844     // has an in-class initializer...
4845     if (Field->hasInClassInitializer())
4846       return false;
4847     // ... or it's an anonymous struct or union whose class has an in-class
4848     // initializer.
4849     if (!Field->isAnonymousStructOrUnion())
4850       return true;
4851     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4852     return !FieldRD->hasInClassInitializer();
4853   }
4854 
4855   /// Determine whether the given field is, or is within, a union member
4856   /// that is inactive (because there was an initializer given for a different
4857   /// member of the union, or because the union was not initialized at all).
4858   bool isWithinInactiveUnionMember(FieldDecl *Field,
4859                                    IndirectFieldDecl *Indirect) {
4860     if (!Indirect)
4861       return isInactiveUnionMember(Field);
4862 
4863     for (auto *C : Indirect->chain()) {
4864       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4865       if (Field && isInactiveUnionMember(Field))
4866         return true;
4867     }
4868     return false;
4869   }
4870 };
4871 }
4872 
4873 /// Determine whether the given type is an incomplete or zero-lenfgth
4874 /// array type.
4875 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4876   if (T->isIncompleteArrayType())
4877     return true;
4878 
4879   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4880     if (!ArrayT->getSize())
4881       return true;
4882 
4883     T = ArrayT->getElementType();
4884   }
4885 
4886   return false;
4887 }
4888 
4889 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4890                                     FieldDecl *Field,
4891                                     IndirectFieldDecl *Indirect = nullptr) {
4892   if (Field->isInvalidDecl())
4893     return false;
4894 
4895   // Overwhelmingly common case: we have a direct initializer for this field.
4896   if (CXXCtorInitializer *Init =
4897           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4898     return Info.addFieldInitializer(Init);
4899 
4900   // C++11 [class.base.init]p8:
4901   //   if the entity is a non-static data member that has a
4902   //   brace-or-equal-initializer and either
4903   //   -- the constructor's class is a union and no other variant member of that
4904   //      union is designated by a mem-initializer-id or
4905   //   -- the constructor's class is not a union, and, if the entity is a member
4906   //      of an anonymous union, no other member of that union is designated by
4907   //      a mem-initializer-id,
4908   //   the entity is initialized as specified in [dcl.init].
4909   //
4910   // We also apply the same rules to handle anonymous structs within anonymous
4911   // unions.
4912   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4913     return false;
4914 
4915   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4916     ExprResult DIE =
4917         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4918     if (DIE.isInvalid())
4919       return true;
4920 
4921     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4922     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4923 
4924     CXXCtorInitializer *Init;
4925     if (Indirect)
4926       Init = new (SemaRef.Context)
4927           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4928                              SourceLocation(), DIE.get(), SourceLocation());
4929     else
4930       Init = new (SemaRef.Context)
4931           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4932                              SourceLocation(), DIE.get(), SourceLocation());
4933     return Info.addFieldInitializer(Init);
4934   }
4935 
4936   // Don't initialize incomplete or zero-length arrays.
4937   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4938     return false;
4939 
4940   // Don't try to build an implicit initializer if there were semantic
4941   // errors in any of the initializers (and therefore we might be
4942   // missing some that the user actually wrote).
4943   if (Info.AnyErrorsInInits)
4944     return false;
4945 
4946   CXXCtorInitializer *Init = nullptr;
4947   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4948                                      Indirect, Init))
4949     return true;
4950 
4951   if (!Init)
4952     return false;
4953 
4954   return Info.addFieldInitializer(Init);
4955 }
4956 
4957 bool
4958 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4959                                CXXCtorInitializer *Initializer) {
4960   assert(Initializer->isDelegatingInitializer());
4961   Constructor->setNumCtorInitializers(1);
4962   CXXCtorInitializer **initializer =
4963     new (Context) CXXCtorInitializer*[1];
4964   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4965   Constructor->setCtorInitializers(initializer);
4966 
4967   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4968     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4969     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4970   }
4971 
4972   DelegatingCtorDecls.push_back(Constructor);
4973 
4974   DiagnoseUninitializedFields(*this, Constructor);
4975 
4976   return false;
4977 }
4978 
4979 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4980                                ArrayRef<CXXCtorInitializer *> Initializers) {
4981   if (Constructor->isDependentContext()) {
4982     // Just store the initializers as written, they will be checked during
4983     // instantiation.
4984     if (!Initializers.empty()) {
4985       Constructor->setNumCtorInitializers(Initializers.size());
4986       CXXCtorInitializer **baseOrMemberInitializers =
4987         new (Context) CXXCtorInitializer*[Initializers.size()];
4988       memcpy(baseOrMemberInitializers, Initializers.data(),
4989              Initializers.size() * sizeof(CXXCtorInitializer*));
4990       Constructor->setCtorInitializers(baseOrMemberInitializers);
4991     }
4992 
4993     // Let template instantiation know whether we had errors.
4994     if (AnyErrors)
4995       Constructor->setInvalidDecl();
4996 
4997     return false;
4998   }
4999 
5000   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5001 
5002   // We need to build the initializer AST according to order of construction
5003   // and not what user specified in the Initializers list.
5004   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5005   if (!ClassDecl)
5006     return true;
5007 
5008   bool HadError = false;
5009 
5010   for (unsigned i = 0; i < Initializers.size(); i++) {
5011     CXXCtorInitializer *Member = Initializers[i];
5012 
5013     if (Member->isBaseInitializer())
5014       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5015     else {
5016       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5017 
5018       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5019         for (auto *C : F->chain()) {
5020           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5021           if (FD && FD->getParent()->isUnion())
5022             Info.ActiveUnionMember.insert(std::make_pair(
5023                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5024         }
5025       } else if (FieldDecl *FD = Member->getMember()) {
5026         if (FD->getParent()->isUnion())
5027           Info.ActiveUnionMember.insert(std::make_pair(
5028               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5029       }
5030     }
5031   }
5032 
5033   // Keep track of the direct virtual bases.
5034   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5035   for (auto &I : ClassDecl->bases()) {
5036     if (I.isVirtual())
5037       DirectVBases.insert(&I);
5038   }
5039 
5040   // Push virtual bases before others.
5041   for (auto &VBase : ClassDecl->vbases()) {
5042     if (CXXCtorInitializer *Value
5043         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5044       // [class.base.init]p7, per DR257:
5045       //   A mem-initializer where the mem-initializer-id names a virtual base
5046       //   class is ignored during execution of a constructor of any class that
5047       //   is not the most derived class.
5048       if (ClassDecl->isAbstract()) {
5049         // FIXME: Provide a fixit to remove the base specifier. This requires
5050         // tracking the location of the associated comma for a base specifier.
5051         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5052           << VBase.getType() << ClassDecl;
5053         DiagnoseAbstractType(ClassDecl);
5054       }
5055 
5056       Info.AllToInit.push_back(Value);
5057     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5058       // [class.base.init]p8, per DR257:
5059       //   If a given [...] base class is not named by a mem-initializer-id
5060       //   [...] and the entity is not a virtual base class of an abstract
5061       //   class, then [...] the entity is default-initialized.
5062       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5063       CXXCtorInitializer *CXXBaseInit;
5064       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5065                                        &VBase, IsInheritedVirtualBase,
5066                                        CXXBaseInit)) {
5067         HadError = true;
5068         continue;
5069       }
5070 
5071       Info.AllToInit.push_back(CXXBaseInit);
5072     }
5073   }
5074 
5075   // Non-virtual bases.
5076   for (auto &Base : ClassDecl->bases()) {
5077     // Virtuals are in the virtual base list and already constructed.
5078     if (Base.isVirtual())
5079       continue;
5080 
5081     if (CXXCtorInitializer *Value
5082           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5083       Info.AllToInit.push_back(Value);
5084     } else if (!AnyErrors) {
5085       CXXCtorInitializer *CXXBaseInit;
5086       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5087                                        &Base, /*IsInheritedVirtualBase=*/false,
5088                                        CXXBaseInit)) {
5089         HadError = true;
5090         continue;
5091       }
5092 
5093       Info.AllToInit.push_back(CXXBaseInit);
5094     }
5095   }
5096 
5097   // Fields.
5098   for (auto *Mem : ClassDecl->decls()) {
5099     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5100       // C++ [class.bit]p2:
5101       //   A declaration for a bit-field that omits the identifier declares an
5102       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5103       //   initialized.
5104       if (F->isUnnamedBitfield())
5105         continue;
5106 
5107       // If we're not generating the implicit copy/move constructor, then we'll
5108       // handle anonymous struct/union fields based on their individual
5109       // indirect fields.
5110       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5111         continue;
5112 
5113       if (CollectFieldInitializer(*this, Info, F))
5114         HadError = true;
5115       continue;
5116     }
5117 
5118     // Beyond this point, we only consider default initialization.
5119     if (Info.isImplicitCopyOrMove())
5120       continue;
5121 
5122     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5123       if (F->getType()->isIncompleteArrayType()) {
5124         assert(ClassDecl->hasFlexibleArrayMember() &&
5125                "Incomplete array type is not valid");
5126         continue;
5127       }
5128 
5129       // Initialize each field of an anonymous struct individually.
5130       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5131         HadError = true;
5132 
5133       continue;
5134     }
5135   }
5136 
5137   unsigned NumInitializers = Info.AllToInit.size();
5138   if (NumInitializers > 0) {
5139     Constructor->setNumCtorInitializers(NumInitializers);
5140     CXXCtorInitializer **baseOrMemberInitializers =
5141       new (Context) CXXCtorInitializer*[NumInitializers];
5142     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5143            NumInitializers * sizeof(CXXCtorInitializer*));
5144     Constructor->setCtorInitializers(baseOrMemberInitializers);
5145 
5146     // Constructors implicitly reference the base and member
5147     // destructors.
5148     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5149                                            Constructor->getParent());
5150   }
5151 
5152   return HadError;
5153 }
5154 
5155 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5156   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5157     const RecordDecl *RD = RT->getDecl();
5158     if (RD->isAnonymousStructOrUnion()) {
5159       for (auto *Field : RD->fields())
5160         PopulateKeysForFields(Field, IdealInits);
5161       return;
5162     }
5163   }
5164   IdealInits.push_back(Field->getCanonicalDecl());
5165 }
5166 
5167 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5168   return Context.getCanonicalType(BaseType).getTypePtr();
5169 }
5170 
5171 static const void *GetKeyForMember(ASTContext &Context,
5172                                    CXXCtorInitializer *Member) {
5173   if (!Member->isAnyMemberInitializer())
5174     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5175 
5176   return Member->getAnyMember()->getCanonicalDecl();
5177 }
5178 
5179 static void DiagnoseBaseOrMemInitializerOrder(
5180     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5181     ArrayRef<CXXCtorInitializer *> Inits) {
5182   if (Constructor->getDeclContext()->isDependentContext())
5183     return;
5184 
5185   // Don't check initializers order unless the warning is enabled at the
5186   // location of at least one initializer.
5187   bool ShouldCheckOrder = false;
5188   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5189     CXXCtorInitializer *Init = Inits[InitIndex];
5190     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5191                                  Init->getSourceLocation())) {
5192       ShouldCheckOrder = true;
5193       break;
5194     }
5195   }
5196   if (!ShouldCheckOrder)
5197     return;
5198 
5199   // Build the list of bases and members in the order that they'll
5200   // actually be initialized.  The explicit initializers should be in
5201   // this same order but may be missing things.
5202   SmallVector<const void*, 32> IdealInitKeys;
5203 
5204   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5205 
5206   // 1. Virtual bases.
5207   for (const auto &VBase : ClassDecl->vbases())
5208     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5209 
5210   // 2. Non-virtual bases.
5211   for (const auto &Base : ClassDecl->bases()) {
5212     if (Base.isVirtual())
5213       continue;
5214     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5215   }
5216 
5217   // 3. Direct fields.
5218   for (auto *Field : ClassDecl->fields()) {
5219     if (Field->isUnnamedBitfield())
5220       continue;
5221 
5222     PopulateKeysForFields(Field, IdealInitKeys);
5223   }
5224 
5225   unsigned NumIdealInits = IdealInitKeys.size();
5226   unsigned IdealIndex = 0;
5227 
5228   CXXCtorInitializer *PrevInit = nullptr;
5229   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5230     CXXCtorInitializer *Init = Inits[InitIndex];
5231     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5232 
5233     // Scan forward to try to find this initializer in the idealized
5234     // initializers list.
5235     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5236       if (InitKey == IdealInitKeys[IdealIndex])
5237         break;
5238 
5239     // If we didn't find this initializer, it must be because we
5240     // scanned past it on a previous iteration.  That can only
5241     // happen if we're out of order;  emit a warning.
5242     if (IdealIndex == NumIdealInits && PrevInit) {
5243       Sema::SemaDiagnosticBuilder D =
5244         SemaRef.Diag(PrevInit->getSourceLocation(),
5245                      diag::warn_initializer_out_of_order);
5246 
5247       if (PrevInit->isAnyMemberInitializer())
5248         D << 0 << PrevInit->getAnyMember()->getDeclName();
5249       else
5250         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5251 
5252       if (Init->isAnyMemberInitializer())
5253         D << 0 << Init->getAnyMember()->getDeclName();
5254       else
5255         D << 1 << Init->getTypeSourceInfo()->getType();
5256 
5257       // Move back to the initializer's location in the ideal list.
5258       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5259         if (InitKey == IdealInitKeys[IdealIndex])
5260           break;
5261 
5262       assert(IdealIndex < NumIdealInits &&
5263              "initializer not found in initializer list");
5264     }
5265 
5266     PrevInit = Init;
5267   }
5268 }
5269 
5270 namespace {
5271 bool CheckRedundantInit(Sema &S,
5272                         CXXCtorInitializer *Init,
5273                         CXXCtorInitializer *&PrevInit) {
5274   if (!PrevInit) {
5275     PrevInit = Init;
5276     return false;
5277   }
5278 
5279   if (FieldDecl *Field = Init->getAnyMember())
5280     S.Diag(Init->getSourceLocation(),
5281            diag::err_multiple_mem_initialization)
5282       << Field->getDeclName()
5283       << Init->getSourceRange();
5284   else {
5285     const Type *BaseClass = Init->getBaseClass();
5286     assert(BaseClass && "neither field nor base");
5287     S.Diag(Init->getSourceLocation(),
5288            diag::err_multiple_base_initialization)
5289       << QualType(BaseClass, 0)
5290       << Init->getSourceRange();
5291   }
5292   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5293     << 0 << PrevInit->getSourceRange();
5294 
5295   return true;
5296 }
5297 
5298 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5299 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5300 
5301 bool CheckRedundantUnionInit(Sema &S,
5302                              CXXCtorInitializer *Init,
5303                              RedundantUnionMap &Unions) {
5304   FieldDecl *Field = Init->getAnyMember();
5305   RecordDecl *Parent = Field->getParent();
5306   NamedDecl *Child = Field;
5307 
5308   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5309     if (Parent->isUnion()) {
5310       UnionEntry &En = Unions[Parent];
5311       if (En.first && En.first != Child) {
5312         S.Diag(Init->getSourceLocation(),
5313                diag::err_multiple_mem_union_initialization)
5314           << Field->getDeclName()
5315           << Init->getSourceRange();
5316         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5317           << 0 << En.second->getSourceRange();
5318         return true;
5319       }
5320       if (!En.first) {
5321         En.first = Child;
5322         En.second = Init;
5323       }
5324       if (!Parent->isAnonymousStructOrUnion())
5325         return false;
5326     }
5327 
5328     Child = Parent;
5329     Parent = cast<RecordDecl>(Parent->getDeclContext());
5330   }
5331 
5332   return false;
5333 }
5334 }
5335 
5336 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5337 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5338                                 SourceLocation ColonLoc,
5339                                 ArrayRef<CXXCtorInitializer*> MemInits,
5340                                 bool AnyErrors) {
5341   if (!ConstructorDecl)
5342     return;
5343 
5344   AdjustDeclIfTemplate(ConstructorDecl);
5345 
5346   CXXConstructorDecl *Constructor
5347     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5348 
5349   if (!Constructor) {
5350     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5351     return;
5352   }
5353 
5354   // Mapping for the duplicate initializers check.
5355   // For member initializers, this is keyed with a FieldDecl*.
5356   // For base initializers, this is keyed with a Type*.
5357   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5358 
5359   // Mapping for the inconsistent anonymous-union initializers check.
5360   RedundantUnionMap MemberUnions;
5361 
5362   bool HadError = false;
5363   for (unsigned i = 0; i < MemInits.size(); i++) {
5364     CXXCtorInitializer *Init = MemInits[i];
5365 
5366     // Set the source order index.
5367     Init->setSourceOrder(i);
5368 
5369     if (Init->isAnyMemberInitializer()) {
5370       const void *Key = GetKeyForMember(Context, Init);
5371       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5372           CheckRedundantUnionInit(*this, Init, MemberUnions))
5373         HadError = true;
5374     } else if (Init->isBaseInitializer()) {
5375       const void *Key = GetKeyForMember(Context, Init);
5376       if (CheckRedundantInit(*this, Init, Members[Key]))
5377         HadError = true;
5378     } else {
5379       assert(Init->isDelegatingInitializer());
5380       // This must be the only initializer
5381       if (MemInits.size() != 1) {
5382         Diag(Init->getSourceLocation(),
5383              diag::err_delegating_initializer_alone)
5384           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5385         // We will treat this as being the only initializer.
5386       }
5387       SetDelegatingInitializer(Constructor, MemInits[i]);
5388       // Return immediately as the initializer is set.
5389       return;
5390     }
5391   }
5392 
5393   if (HadError)
5394     return;
5395 
5396   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5397 
5398   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5399 
5400   DiagnoseUninitializedFields(*this, Constructor);
5401 }
5402 
5403 void
5404 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5405                                              CXXRecordDecl *ClassDecl) {
5406   // Ignore dependent contexts. Also ignore unions, since their members never
5407   // have destructors implicitly called.
5408   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5409     return;
5410 
5411   // FIXME: all the access-control diagnostics are positioned on the
5412   // field/base declaration.  That's probably good; that said, the
5413   // user might reasonably want to know why the destructor is being
5414   // emitted, and we currently don't say.
5415 
5416   // Non-static data members.
5417   for (auto *Field : ClassDecl->fields()) {
5418     if (Field->isInvalidDecl())
5419       continue;
5420 
5421     // Don't destroy incomplete or zero-length arrays.
5422     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5423       continue;
5424 
5425     QualType FieldType = Context.getBaseElementType(Field->getType());
5426 
5427     const RecordType* RT = FieldType->getAs<RecordType>();
5428     if (!RT)
5429       continue;
5430 
5431     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5432     if (FieldClassDecl->isInvalidDecl())
5433       continue;
5434     if (FieldClassDecl->hasIrrelevantDestructor())
5435       continue;
5436     // The destructor for an implicit anonymous union member is never invoked.
5437     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5438       continue;
5439 
5440     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5441     assert(Dtor && "No dtor found for FieldClassDecl!");
5442     CheckDestructorAccess(Field->getLocation(), Dtor,
5443                           PDiag(diag::err_access_dtor_field)
5444                             << Field->getDeclName()
5445                             << FieldType);
5446 
5447     MarkFunctionReferenced(Location, Dtor);
5448     DiagnoseUseOfDecl(Dtor, Location);
5449   }
5450 
5451   // We only potentially invoke the destructors of potentially constructed
5452   // subobjects.
5453   bool VisitVirtualBases = !ClassDecl->isAbstract();
5454 
5455   // If the destructor exists and has already been marked used in the MS ABI,
5456   // then virtual base destructors have already been checked and marked used.
5457   // Skip checking them again to avoid duplicate diagnostics.
5458   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5459     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5460     if (Dtor && Dtor->isUsed())
5461       VisitVirtualBases = false;
5462   }
5463 
5464   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5465 
5466   // Bases.
5467   for (const auto &Base : ClassDecl->bases()) {
5468     // Bases are always records in a well-formed non-dependent class.
5469     const RecordType *RT = Base.getType()->getAs<RecordType>();
5470 
5471     // Remember direct virtual bases.
5472     if (Base.isVirtual()) {
5473       if (!VisitVirtualBases)
5474         continue;
5475       DirectVirtualBases.insert(RT);
5476     }
5477 
5478     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5479     // If our base class is invalid, we probably can't get its dtor anyway.
5480     if (BaseClassDecl->isInvalidDecl())
5481       continue;
5482     if (BaseClassDecl->hasIrrelevantDestructor())
5483       continue;
5484 
5485     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5486     assert(Dtor && "No dtor found for BaseClassDecl!");
5487 
5488     // FIXME: caret should be on the start of the class name
5489     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5490                           PDiag(diag::err_access_dtor_base)
5491                               << Base.getType() << Base.getSourceRange(),
5492                           Context.getTypeDeclType(ClassDecl));
5493 
5494     MarkFunctionReferenced(Location, Dtor);
5495     DiagnoseUseOfDecl(Dtor, Location);
5496   }
5497 
5498   if (VisitVirtualBases)
5499     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5500                                          &DirectVirtualBases);
5501 }
5502 
5503 void Sema::MarkVirtualBaseDestructorsReferenced(
5504     SourceLocation Location, CXXRecordDecl *ClassDecl,
5505     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5506   // Virtual bases.
5507   for (const auto &VBase : ClassDecl->vbases()) {
5508     // Bases are always records in a well-formed non-dependent class.
5509     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5510 
5511     // Ignore already visited direct virtual bases.
5512     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5513       continue;
5514 
5515     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5516     // If our base class is invalid, we probably can't get its dtor anyway.
5517     if (BaseClassDecl->isInvalidDecl())
5518       continue;
5519     if (BaseClassDecl->hasIrrelevantDestructor())
5520       continue;
5521 
5522     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5523     assert(Dtor && "No dtor found for BaseClassDecl!");
5524     if (CheckDestructorAccess(
5525             ClassDecl->getLocation(), Dtor,
5526             PDiag(diag::err_access_dtor_vbase)
5527                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5528             Context.getTypeDeclType(ClassDecl)) ==
5529         AR_accessible) {
5530       CheckDerivedToBaseConversion(
5531           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5532           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5533           SourceRange(), DeclarationName(), nullptr);
5534     }
5535 
5536     MarkFunctionReferenced(Location, Dtor);
5537     DiagnoseUseOfDecl(Dtor, Location);
5538   }
5539 }
5540 
5541 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5542   if (!CDtorDecl)
5543     return;
5544 
5545   if (CXXConstructorDecl *Constructor
5546       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5547     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5548     DiagnoseUninitializedFields(*this, Constructor);
5549   }
5550 }
5551 
5552 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5553   if (!getLangOpts().CPlusPlus)
5554     return false;
5555 
5556   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5557   if (!RD)
5558     return false;
5559 
5560   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5561   // class template specialization here, but doing so breaks a lot of code.
5562 
5563   // We can't answer whether something is abstract until it has a
5564   // definition. If it's currently being defined, we'll walk back
5565   // over all the declarations when we have a full definition.
5566   const CXXRecordDecl *Def = RD->getDefinition();
5567   if (!Def || Def->isBeingDefined())
5568     return false;
5569 
5570   return RD->isAbstract();
5571 }
5572 
5573 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5574                                   TypeDiagnoser &Diagnoser) {
5575   if (!isAbstractType(Loc, T))
5576     return false;
5577 
5578   T = Context.getBaseElementType(T);
5579   Diagnoser.diagnose(*this, Loc, T);
5580   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5581   return true;
5582 }
5583 
5584 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5585   // Check if we've already emitted the list of pure virtual functions
5586   // for this class.
5587   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5588     return;
5589 
5590   // If the diagnostic is suppressed, don't emit the notes. We're only
5591   // going to emit them once, so try to attach them to a diagnostic we're
5592   // actually going to show.
5593   if (Diags.isLastDiagnosticIgnored())
5594     return;
5595 
5596   CXXFinalOverriderMap FinalOverriders;
5597   RD->getFinalOverriders(FinalOverriders);
5598 
5599   // Keep a set of seen pure methods so we won't diagnose the same method
5600   // more than once.
5601   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5602 
5603   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5604                                    MEnd = FinalOverriders.end();
5605        M != MEnd;
5606        ++M) {
5607     for (OverridingMethods::iterator SO = M->second.begin(),
5608                                   SOEnd = M->second.end();
5609          SO != SOEnd; ++SO) {
5610       // C++ [class.abstract]p4:
5611       //   A class is abstract if it contains or inherits at least one
5612       //   pure virtual function for which the final overrider is pure
5613       //   virtual.
5614 
5615       //
5616       if (SO->second.size() != 1)
5617         continue;
5618 
5619       if (!SO->second.front().Method->isPure())
5620         continue;
5621 
5622       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5623         continue;
5624 
5625       Diag(SO->second.front().Method->getLocation(),
5626            diag::note_pure_virtual_function)
5627         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5628     }
5629   }
5630 
5631   if (!PureVirtualClassDiagSet)
5632     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5633   PureVirtualClassDiagSet->insert(RD);
5634 }
5635 
5636 namespace {
5637 struct AbstractUsageInfo {
5638   Sema &S;
5639   CXXRecordDecl *Record;
5640   CanQualType AbstractType;
5641   bool Invalid;
5642 
5643   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5644     : S(S), Record(Record),
5645       AbstractType(S.Context.getCanonicalType(
5646                    S.Context.getTypeDeclType(Record))),
5647       Invalid(false) {}
5648 
5649   void DiagnoseAbstractType() {
5650     if (Invalid) return;
5651     S.DiagnoseAbstractType(Record);
5652     Invalid = true;
5653   }
5654 
5655   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5656 };
5657 
5658 struct CheckAbstractUsage {
5659   AbstractUsageInfo &Info;
5660   const NamedDecl *Ctx;
5661 
5662   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5663     : Info(Info), Ctx(Ctx) {}
5664 
5665   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5666     switch (TL.getTypeLocClass()) {
5667 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5668 #define TYPELOC(CLASS, PARENT) \
5669     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5670 #include "clang/AST/TypeLocNodes.def"
5671     }
5672   }
5673 
5674   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5675     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5676     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5677       if (!TL.getParam(I))
5678         continue;
5679 
5680       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5681       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5682     }
5683   }
5684 
5685   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5686     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5687   }
5688 
5689   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5690     // Visit the type parameters from a permissive context.
5691     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5692       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5693       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5694         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5695           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5696       // TODO: other template argument types?
5697     }
5698   }
5699 
5700   // Visit pointee types from a permissive context.
5701 #define CheckPolymorphic(Type) \
5702   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5703     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5704   }
5705   CheckPolymorphic(PointerTypeLoc)
5706   CheckPolymorphic(ReferenceTypeLoc)
5707   CheckPolymorphic(MemberPointerTypeLoc)
5708   CheckPolymorphic(BlockPointerTypeLoc)
5709   CheckPolymorphic(AtomicTypeLoc)
5710 
5711   /// Handle all the types we haven't given a more specific
5712   /// implementation for above.
5713   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5714     // Every other kind of type that we haven't called out already
5715     // that has an inner type is either (1) sugar or (2) contains that
5716     // inner type in some way as a subobject.
5717     if (TypeLoc Next = TL.getNextTypeLoc())
5718       return Visit(Next, Sel);
5719 
5720     // If there's no inner type and we're in a permissive context,
5721     // don't diagnose.
5722     if (Sel == Sema::AbstractNone) return;
5723 
5724     // Check whether the type matches the abstract type.
5725     QualType T = TL.getType();
5726     if (T->isArrayType()) {
5727       Sel = Sema::AbstractArrayType;
5728       T = Info.S.Context.getBaseElementType(T);
5729     }
5730     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5731     if (CT != Info.AbstractType) return;
5732 
5733     // It matched; do some magic.
5734     if (Sel == Sema::AbstractArrayType) {
5735       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5736         << T << TL.getSourceRange();
5737     } else {
5738       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5739         << Sel << T << TL.getSourceRange();
5740     }
5741     Info.DiagnoseAbstractType();
5742   }
5743 };
5744 
5745 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5746                                   Sema::AbstractDiagSelID Sel) {
5747   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5748 }
5749 
5750 }
5751 
5752 /// Check for invalid uses of an abstract type in a method declaration.
5753 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5754                                     CXXMethodDecl *MD) {
5755   // No need to do the check on definitions, which require that
5756   // the return/param types be complete.
5757   if (MD->doesThisDeclarationHaveABody())
5758     return;
5759 
5760   // For safety's sake, just ignore it if we don't have type source
5761   // information.  This should never happen for non-implicit methods,
5762   // but...
5763   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5764     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5765 }
5766 
5767 /// Check for invalid uses of an abstract type within a class definition.
5768 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5769                                     CXXRecordDecl *RD) {
5770   for (auto *D : RD->decls()) {
5771     if (D->isImplicit()) continue;
5772 
5773     // Methods and method templates.
5774     if (isa<CXXMethodDecl>(D)) {
5775       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5776     } else if (isa<FunctionTemplateDecl>(D)) {
5777       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5778       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5779 
5780     // Fields and static variables.
5781     } else if (isa<FieldDecl>(D)) {
5782       FieldDecl *FD = cast<FieldDecl>(D);
5783       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5784         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5785     } else if (isa<VarDecl>(D)) {
5786       VarDecl *VD = cast<VarDecl>(D);
5787       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5788         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5789 
5790     // Nested classes and class templates.
5791     } else if (isa<CXXRecordDecl>(D)) {
5792       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5793     } else if (isa<ClassTemplateDecl>(D)) {
5794       CheckAbstractClassUsage(Info,
5795                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5796     }
5797   }
5798 }
5799 
5800 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5801   Attr *ClassAttr = getDLLAttr(Class);
5802   if (!ClassAttr)
5803     return;
5804 
5805   assert(ClassAttr->getKind() == attr::DLLExport);
5806 
5807   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5808 
5809   if (TSK == TSK_ExplicitInstantiationDeclaration)
5810     // Don't go any further if this is just an explicit instantiation
5811     // declaration.
5812     return;
5813 
5814   // Add a context note to explain how we got to any diagnostics produced below.
5815   struct MarkingClassDllexported {
5816     Sema &S;
5817     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5818                             SourceLocation AttrLoc)
5819         : S(S) {
5820       Sema::CodeSynthesisContext Ctx;
5821       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5822       Ctx.PointOfInstantiation = AttrLoc;
5823       Ctx.Entity = Class;
5824       S.pushCodeSynthesisContext(Ctx);
5825     }
5826     ~MarkingClassDllexported() {
5827       S.popCodeSynthesisContext();
5828     }
5829   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5830 
5831   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5832     S.MarkVTableUsed(Class->getLocation(), Class, true);
5833 
5834   for (Decl *Member : Class->decls()) {
5835     // Defined static variables that are members of an exported base
5836     // class must be marked export too.
5837     auto *VD = dyn_cast<VarDecl>(Member);
5838     if (VD && Member->getAttr<DLLExportAttr>() &&
5839         VD->getStorageClass() == SC_Static &&
5840         TSK == TSK_ImplicitInstantiation)
5841       S.MarkVariableReferenced(VD->getLocation(), VD);
5842 
5843     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5844     if (!MD)
5845       continue;
5846 
5847     if (Member->getAttr<DLLExportAttr>()) {
5848       if (MD->isUserProvided()) {
5849         // Instantiate non-default class member functions ...
5850 
5851         // .. except for certain kinds of template specializations.
5852         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5853           continue;
5854 
5855         S.MarkFunctionReferenced(Class->getLocation(), MD);
5856 
5857         // The function will be passed to the consumer when its definition is
5858         // encountered.
5859       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5860                  MD->isCopyAssignmentOperator() ||
5861                  MD->isMoveAssignmentOperator()) {
5862         // Synthesize and instantiate non-trivial implicit methods, explicitly
5863         // defaulted methods, and the copy and move assignment operators. The
5864         // latter are exported even if they are trivial, because the address of
5865         // an operator can be taken and should compare equal across libraries.
5866         S.MarkFunctionReferenced(Class->getLocation(), MD);
5867 
5868         // There is no later point when we will see the definition of this
5869         // function, so pass it to the consumer now.
5870         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5871       }
5872     }
5873   }
5874 }
5875 
5876 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5877                                                         CXXRecordDecl *Class) {
5878   // Only the MS ABI has default constructor closures, so we don't need to do
5879   // this semantic checking anywhere else.
5880   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5881     return;
5882 
5883   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5884   for (Decl *Member : Class->decls()) {
5885     // Look for exported default constructors.
5886     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5887     if (!CD || !CD->isDefaultConstructor())
5888       continue;
5889     auto *Attr = CD->getAttr<DLLExportAttr>();
5890     if (!Attr)
5891       continue;
5892 
5893     // If the class is non-dependent, mark the default arguments as ODR-used so
5894     // that we can properly codegen the constructor closure.
5895     if (!Class->isDependentContext()) {
5896       for (ParmVarDecl *PD : CD->parameters()) {
5897         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5898         S.DiscardCleanupsInEvaluationContext();
5899       }
5900     }
5901 
5902     if (LastExportedDefaultCtor) {
5903       S.Diag(LastExportedDefaultCtor->getLocation(),
5904              diag::err_attribute_dll_ambiguous_default_ctor)
5905           << Class;
5906       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5907           << CD->getDeclName();
5908       return;
5909     }
5910     LastExportedDefaultCtor = CD;
5911   }
5912 }
5913 
5914 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5915                                                        CXXRecordDecl *Class) {
5916   bool ErrorReported = false;
5917   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5918                                                      ClassTemplateDecl *TD) {
5919     if (ErrorReported)
5920       return;
5921     S.Diag(TD->getLocation(),
5922            diag::err_cuda_device_builtin_surftex_cls_template)
5923         << /*surface*/ 0 << TD;
5924     ErrorReported = true;
5925   };
5926 
5927   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5928   if (!TD) {
5929     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5930     if (!SD) {
5931       S.Diag(Class->getLocation(),
5932              diag::err_cuda_device_builtin_surftex_ref_decl)
5933           << /*surface*/ 0 << Class;
5934       S.Diag(Class->getLocation(),
5935              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5936           << Class;
5937       return;
5938     }
5939     TD = SD->getSpecializedTemplate();
5940   }
5941 
5942   TemplateParameterList *Params = TD->getTemplateParameters();
5943   unsigned N = Params->size();
5944 
5945   if (N != 2) {
5946     reportIllegalClassTemplate(S, TD);
5947     S.Diag(TD->getLocation(),
5948            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5949         << TD << 2;
5950   }
5951   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5952     reportIllegalClassTemplate(S, TD);
5953     S.Diag(TD->getLocation(),
5954            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5955         << TD << /*1st*/ 0 << /*type*/ 0;
5956   }
5957   if (N > 1) {
5958     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5959     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5960       reportIllegalClassTemplate(S, TD);
5961       S.Diag(TD->getLocation(),
5962              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5963           << TD << /*2nd*/ 1 << /*integer*/ 1;
5964     }
5965   }
5966 }
5967 
5968 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5969                                                        CXXRecordDecl *Class) {
5970   bool ErrorReported = false;
5971   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5972                                                      ClassTemplateDecl *TD) {
5973     if (ErrorReported)
5974       return;
5975     S.Diag(TD->getLocation(),
5976            diag::err_cuda_device_builtin_surftex_cls_template)
5977         << /*texture*/ 1 << TD;
5978     ErrorReported = true;
5979   };
5980 
5981   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5982   if (!TD) {
5983     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5984     if (!SD) {
5985       S.Diag(Class->getLocation(),
5986              diag::err_cuda_device_builtin_surftex_ref_decl)
5987           << /*texture*/ 1 << Class;
5988       S.Diag(Class->getLocation(),
5989              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5990           << Class;
5991       return;
5992     }
5993     TD = SD->getSpecializedTemplate();
5994   }
5995 
5996   TemplateParameterList *Params = TD->getTemplateParameters();
5997   unsigned N = Params->size();
5998 
5999   if (N != 3) {
6000     reportIllegalClassTemplate(S, TD);
6001     S.Diag(TD->getLocation(),
6002            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6003         << TD << 3;
6004   }
6005   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6006     reportIllegalClassTemplate(S, TD);
6007     S.Diag(TD->getLocation(),
6008            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6009         << TD << /*1st*/ 0 << /*type*/ 0;
6010   }
6011   if (N > 1) {
6012     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6013     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6014       reportIllegalClassTemplate(S, TD);
6015       S.Diag(TD->getLocation(),
6016              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6017           << TD << /*2nd*/ 1 << /*integer*/ 1;
6018     }
6019   }
6020   if (N > 2) {
6021     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6022     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6023       reportIllegalClassTemplate(S, TD);
6024       S.Diag(TD->getLocation(),
6025              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6026           << TD << /*3rd*/ 2 << /*integer*/ 1;
6027     }
6028   }
6029 }
6030 
6031 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6032   // Mark any compiler-generated routines with the implicit code_seg attribute.
6033   for (auto *Method : Class->methods()) {
6034     if (Method->isUserProvided())
6035       continue;
6036     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6037       Method->addAttr(A);
6038   }
6039 }
6040 
6041 /// Check class-level dllimport/dllexport attribute.
6042 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6043   Attr *ClassAttr = getDLLAttr(Class);
6044 
6045   // MSVC inherits DLL attributes to partial class template specializations.
6046   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
6047     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6048       if (Attr *TemplateAttr =
6049               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6050         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6051         A->setInherited(true);
6052         ClassAttr = A;
6053       }
6054     }
6055   }
6056 
6057   if (!ClassAttr)
6058     return;
6059 
6060   if (!Class->isExternallyVisible()) {
6061     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6062         << Class << ClassAttr;
6063     return;
6064   }
6065 
6066   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6067       !ClassAttr->isInherited()) {
6068     // Diagnose dll attributes on members of class with dll attribute.
6069     for (Decl *Member : Class->decls()) {
6070       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6071         continue;
6072       InheritableAttr *MemberAttr = getDLLAttr(Member);
6073       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6074         continue;
6075 
6076       Diag(MemberAttr->getLocation(),
6077              diag::err_attribute_dll_member_of_dll_class)
6078           << MemberAttr << ClassAttr;
6079       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6080       Member->setInvalidDecl();
6081     }
6082   }
6083 
6084   if (Class->getDescribedClassTemplate())
6085     // Don't inherit dll attribute until the template is instantiated.
6086     return;
6087 
6088   // The class is either imported or exported.
6089   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6090 
6091   // Check if this was a dllimport attribute propagated from a derived class to
6092   // a base class template specialization. We don't apply these attributes to
6093   // static data members.
6094   const bool PropagatedImport =
6095       !ClassExported &&
6096       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6097 
6098   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6099 
6100   // Ignore explicit dllexport on explicit class template instantiation
6101   // declarations, except in MinGW mode.
6102   if (ClassExported && !ClassAttr->isInherited() &&
6103       TSK == TSK_ExplicitInstantiationDeclaration &&
6104       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6105     Class->dropAttr<DLLExportAttr>();
6106     return;
6107   }
6108 
6109   // Force declaration of implicit members so they can inherit the attribute.
6110   ForceDeclarationOfImplicitMembers(Class);
6111 
6112   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6113   // seem to be true in practice?
6114 
6115   for (Decl *Member : Class->decls()) {
6116     VarDecl *VD = dyn_cast<VarDecl>(Member);
6117     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6118 
6119     // Only methods and static fields inherit the attributes.
6120     if (!VD && !MD)
6121       continue;
6122 
6123     if (MD) {
6124       // Don't process deleted methods.
6125       if (MD->isDeleted())
6126         continue;
6127 
6128       if (MD->isInlined()) {
6129         // MinGW does not import or export inline methods. But do it for
6130         // template instantiations.
6131         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6132             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6133             TSK != TSK_ExplicitInstantiationDeclaration &&
6134             TSK != TSK_ExplicitInstantiationDefinition)
6135           continue;
6136 
6137         // MSVC versions before 2015 don't export the move assignment operators
6138         // and move constructor, so don't attempt to import/export them if
6139         // we have a definition.
6140         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6141         if ((MD->isMoveAssignmentOperator() ||
6142              (Ctor && Ctor->isMoveConstructor())) &&
6143             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6144           continue;
6145 
6146         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6147         // operator is exported anyway.
6148         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6149             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6150           continue;
6151       }
6152     }
6153 
6154     // Don't apply dllimport attributes to static data members of class template
6155     // instantiations when the attribute is propagated from a derived class.
6156     if (VD && PropagatedImport)
6157       continue;
6158 
6159     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6160       continue;
6161 
6162     if (!getDLLAttr(Member)) {
6163       InheritableAttr *NewAttr = nullptr;
6164 
6165       // Do not export/import inline function when -fno-dllexport-inlines is
6166       // passed. But add attribute for later local static var check.
6167       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6168           TSK != TSK_ExplicitInstantiationDeclaration &&
6169           TSK != TSK_ExplicitInstantiationDefinition) {
6170         if (ClassExported) {
6171           NewAttr = ::new (getASTContext())
6172               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6173         } else {
6174           NewAttr = ::new (getASTContext())
6175               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6176         }
6177       } else {
6178         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6179       }
6180 
6181       NewAttr->setInherited(true);
6182       Member->addAttr(NewAttr);
6183 
6184       if (MD) {
6185         // Propagate DLLAttr to friend re-declarations of MD that have already
6186         // been constructed.
6187         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6188              FD = FD->getPreviousDecl()) {
6189           if (FD->getFriendObjectKind() == Decl::FOK_None)
6190             continue;
6191           assert(!getDLLAttr(FD) &&
6192                  "friend re-decl should not already have a DLLAttr");
6193           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6194           NewAttr->setInherited(true);
6195           FD->addAttr(NewAttr);
6196         }
6197       }
6198     }
6199   }
6200 
6201   if (ClassExported)
6202     DelayedDllExportClasses.push_back(Class);
6203 }
6204 
6205 /// Perform propagation of DLL attributes from a derived class to a
6206 /// templated base class for MS compatibility.
6207 void Sema::propagateDLLAttrToBaseClassTemplate(
6208     CXXRecordDecl *Class, Attr *ClassAttr,
6209     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6210   if (getDLLAttr(
6211           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6212     // If the base class template has a DLL attribute, don't try to change it.
6213     return;
6214   }
6215 
6216   auto TSK = BaseTemplateSpec->getSpecializationKind();
6217   if (!getDLLAttr(BaseTemplateSpec) &&
6218       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6219        TSK == TSK_ImplicitInstantiation)) {
6220     // The template hasn't been instantiated yet (or it has, but only as an
6221     // explicit instantiation declaration or implicit instantiation, which means
6222     // we haven't codegenned any members yet), so propagate the attribute.
6223     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6224     NewAttr->setInherited(true);
6225     BaseTemplateSpec->addAttr(NewAttr);
6226 
6227     // If this was an import, mark that we propagated it from a derived class to
6228     // a base class template specialization.
6229     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6230       ImportAttr->setPropagatedToBaseTemplate();
6231 
6232     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6233     // needs to be run again to work see the new attribute. Otherwise this will
6234     // get run whenever the template is instantiated.
6235     if (TSK != TSK_Undeclared)
6236       checkClassLevelDLLAttribute(BaseTemplateSpec);
6237 
6238     return;
6239   }
6240 
6241   if (getDLLAttr(BaseTemplateSpec)) {
6242     // The template has already been specialized or instantiated with an
6243     // attribute, explicitly or through propagation. We should not try to change
6244     // it.
6245     return;
6246   }
6247 
6248   // The template was previously instantiated or explicitly specialized without
6249   // a dll attribute, It's too late for us to add an attribute, so warn that
6250   // this is unsupported.
6251   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6252       << BaseTemplateSpec->isExplicitSpecialization();
6253   Diag(ClassAttr->getLocation(), diag::note_attribute);
6254   if (BaseTemplateSpec->isExplicitSpecialization()) {
6255     Diag(BaseTemplateSpec->getLocation(),
6256            diag::note_template_class_explicit_specialization_was_here)
6257         << BaseTemplateSpec;
6258   } else {
6259     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6260            diag::note_template_class_instantiation_was_here)
6261         << BaseTemplateSpec;
6262   }
6263 }
6264 
6265 /// Determine the kind of defaulting that would be done for a given function.
6266 ///
6267 /// If the function is both a default constructor and a copy / move constructor
6268 /// (due to having a default argument for the first parameter), this picks
6269 /// CXXDefaultConstructor.
6270 ///
6271 /// FIXME: Check that case is properly handled by all callers.
6272 Sema::DefaultedFunctionKind
6273 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6274   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6275     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6276       if (Ctor->isDefaultConstructor())
6277         return Sema::CXXDefaultConstructor;
6278 
6279       if (Ctor->isCopyConstructor())
6280         return Sema::CXXCopyConstructor;
6281 
6282       if (Ctor->isMoveConstructor())
6283         return Sema::CXXMoveConstructor;
6284     }
6285 
6286     if (MD->isCopyAssignmentOperator())
6287       return Sema::CXXCopyAssignment;
6288 
6289     if (MD->isMoveAssignmentOperator())
6290       return Sema::CXXMoveAssignment;
6291 
6292     if (isa<CXXDestructorDecl>(FD))
6293       return Sema::CXXDestructor;
6294   }
6295 
6296   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6297   case OO_EqualEqual:
6298     return DefaultedComparisonKind::Equal;
6299 
6300   case OO_ExclaimEqual:
6301     return DefaultedComparisonKind::NotEqual;
6302 
6303   case OO_Spaceship:
6304     // No point allowing this if <=> doesn't exist in the current language mode.
6305     if (!getLangOpts().CPlusPlus20)
6306       break;
6307     return DefaultedComparisonKind::ThreeWay;
6308 
6309   case OO_Less:
6310   case OO_LessEqual:
6311   case OO_Greater:
6312   case OO_GreaterEqual:
6313     // No point allowing this if <=> doesn't exist in the current language mode.
6314     if (!getLangOpts().CPlusPlus20)
6315       break;
6316     return DefaultedComparisonKind::Relational;
6317 
6318   default:
6319     break;
6320   }
6321 
6322   // Not defaultable.
6323   return DefaultedFunctionKind();
6324 }
6325 
6326 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6327                                     SourceLocation DefaultLoc) {
6328   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6329   if (DFK.isComparison())
6330     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6331 
6332   switch (DFK.asSpecialMember()) {
6333   case Sema::CXXDefaultConstructor:
6334     S.DefineImplicitDefaultConstructor(DefaultLoc,
6335                                        cast<CXXConstructorDecl>(FD));
6336     break;
6337   case Sema::CXXCopyConstructor:
6338     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6339     break;
6340   case Sema::CXXCopyAssignment:
6341     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6342     break;
6343   case Sema::CXXDestructor:
6344     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6345     break;
6346   case Sema::CXXMoveConstructor:
6347     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6348     break;
6349   case Sema::CXXMoveAssignment:
6350     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6351     break;
6352   case Sema::CXXInvalid:
6353     llvm_unreachable("Invalid special member.");
6354   }
6355 }
6356 
6357 /// Determine whether a type is permitted to be passed or returned in
6358 /// registers, per C++ [class.temporary]p3.
6359 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6360                                TargetInfo::CallingConvKind CCK) {
6361   if (D->isDependentType() || D->isInvalidDecl())
6362     return false;
6363 
6364   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6365   // The PS4 platform ABI follows the behavior of Clang 3.2.
6366   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6367     return !D->hasNonTrivialDestructorForCall() &&
6368            !D->hasNonTrivialCopyConstructorForCall();
6369 
6370   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6371     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6372     bool DtorIsTrivialForCall = false;
6373 
6374     // If a class has at least one non-deleted, trivial copy constructor, it
6375     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6376     //
6377     // Note: This permits classes with non-trivial copy or move ctors to be
6378     // passed in registers, so long as they *also* have a trivial copy ctor,
6379     // which is non-conforming.
6380     if (D->needsImplicitCopyConstructor()) {
6381       if (!D->defaultedCopyConstructorIsDeleted()) {
6382         if (D->hasTrivialCopyConstructor())
6383           CopyCtorIsTrivial = true;
6384         if (D->hasTrivialCopyConstructorForCall())
6385           CopyCtorIsTrivialForCall = true;
6386       }
6387     } else {
6388       for (const CXXConstructorDecl *CD : D->ctors()) {
6389         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6390           if (CD->isTrivial())
6391             CopyCtorIsTrivial = true;
6392           if (CD->isTrivialForCall())
6393             CopyCtorIsTrivialForCall = true;
6394         }
6395       }
6396     }
6397 
6398     if (D->needsImplicitDestructor()) {
6399       if (!D->defaultedDestructorIsDeleted() &&
6400           D->hasTrivialDestructorForCall())
6401         DtorIsTrivialForCall = true;
6402     } else if (const auto *DD = D->getDestructor()) {
6403       if (!DD->isDeleted() && DD->isTrivialForCall())
6404         DtorIsTrivialForCall = true;
6405     }
6406 
6407     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6408     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6409       return true;
6410 
6411     // If a class has a destructor, we'd really like to pass it indirectly
6412     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6413     // impossible for small types, which it will pass in a single register or
6414     // stack slot. Most objects with dtors are large-ish, so handle that early.
6415     // We can't call out all large objects as being indirect because there are
6416     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6417     // how we pass large POD types.
6418 
6419     // Note: This permits small classes with nontrivial destructors to be
6420     // passed in registers, which is non-conforming.
6421     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6422     uint64_t TypeSize = isAArch64 ? 128 : 64;
6423 
6424     if (CopyCtorIsTrivial &&
6425         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6426       return true;
6427     return false;
6428   }
6429 
6430   // Per C++ [class.temporary]p3, the relevant condition is:
6431   //   each copy constructor, move constructor, and destructor of X is
6432   //   either trivial or deleted, and X has at least one non-deleted copy
6433   //   or move constructor
6434   bool HasNonDeletedCopyOrMove = false;
6435 
6436   if (D->needsImplicitCopyConstructor() &&
6437       !D->defaultedCopyConstructorIsDeleted()) {
6438     if (!D->hasTrivialCopyConstructorForCall())
6439       return false;
6440     HasNonDeletedCopyOrMove = true;
6441   }
6442 
6443   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6444       !D->defaultedMoveConstructorIsDeleted()) {
6445     if (!D->hasTrivialMoveConstructorForCall())
6446       return false;
6447     HasNonDeletedCopyOrMove = true;
6448   }
6449 
6450   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6451       !D->hasTrivialDestructorForCall())
6452     return false;
6453 
6454   for (const CXXMethodDecl *MD : D->methods()) {
6455     if (MD->isDeleted())
6456       continue;
6457 
6458     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6459     if (CD && CD->isCopyOrMoveConstructor())
6460       HasNonDeletedCopyOrMove = true;
6461     else if (!isa<CXXDestructorDecl>(MD))
6462       continue;
6463 
6464     if (!MD->isTrivialForCall())
6465       return false;
6466   }
6467 
6468   return HasNonDeletedCopyOrMove;
6469 }
6470 
6471 /// Report an error regarding overriding, along with any relevant
6472 /// overridden methods.
6473 ///
6474 /// \param DiagID the primary error to report.
6475 /// \param MD the overriding method.
6476 static bool
6477 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6478                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6479   bool IssuedDiagnostic = false;
6480   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6481     if (Report(O)) {
6482       if (!IssuedDiagnostic) {
6483         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6484         IssuedDiagnostic = true;
6485       }
6486       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6487     }
6488   }
6489   return IssuedDiagnostic;
6490 }
6491 
6492 /// Perform semantic checks on a class definition that has been
6493 /// completing, introducing implicitly-declared members, checking for
6494 /// abstract types, etc.
6495 ///
6496 /// \param S The scope in which the class was parsed. Null if we didn't just
6497 ///        parse a class definition.
6498 /// \param Record The completed class.
6499 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6500   if (!Record)
6501     return;
6502 
6503   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6504     AbstractUsageInfo Info(*this, Record);
6505     CheckAbstractClassUsage(Info, Record);
6506   }
6507 
6508   // If this is not an aggregate type and has no user-declared constructor,
6509   // complain about any non-static data members of reference or const scalar
6510   // type, since they will never get initializers.
6511   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6512       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6513       !Record->isLambda()) {
6514     bool Complained = false;
6515     for (const auto *F : Record->fields()) {
6516       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6517         continue;
6518 
6519       if (F->getType()->isReferenceType() ||
6520           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6521         if (!Complained) {
6522           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6523             << Record->getTagKind() << Record;
6524           Complained = true;
6525         }
6526 
6527         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6528           << F->getType()->isReferenceType()
6529           << F->getDeclName();
6530       }
6531     }
6532   }
6533 
6534   if (Record->getIdentifier()) {
6535     // C++ [class.mem]p13:
6536     //   If T is the name of a class, then each of the following shall have a
6537     //   name different from T:
6538     //     - every member of every anonymous union that is a member of class T.
6539     //
6540     // C++ [class.mem]p14:
6541     //   In addition, if class T has a user-declared constructor (12.1), every
6542     //   non-static data member of class T shall have a name different from T.
6543     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6544     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6545          ++I) {
6546       NamedDecl *D = (*I)->getUnderlyingDecl();
6547       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6548            Record->hasUserDeclaredConstructor()) ||
6549           isa<IndirectFieldDecl>(D)) {
6550         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6551           << D->getDeclName();
6552         break;
6553       }
6554     }
6555   }
6556 
6557   // Warn if the class has virtual methods but non-virtual public destructor.
6558   if (Record->isPolymorphic() && !Record->isDependentType()) {
6559     CXXDestructorDecl *dtor = Record->getDestructor();
6560     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6561         !Record->hasAttr<FinalAttr>())
6562       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6563            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6564   }
6565 
6566   if (Record->isAbstract()) {
6567     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6568       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6569         << FA->isSpelledAsSealed();
6570       DiagnoseAbstractType(Record);
6571     }
6572   }
6573 
6574   // Warn if the class has a final destructor but is not itself marked final.
6575   if (!Record->hasAttr<FinalAttr>()) {
6576     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6577       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6578         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6579             << FA->isSpelledAsSealed()
6580             << FixItHint::CreateInsertion(
6581                    getLocForEndOfToken(Record->getLocation()),
6582                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6583         Diag(Record->getLocation(),
6584              diag::note_final_dtor_non_final_class_silence)
6585             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6586       }
6587     }
6588   }
6589 
6590   // See if trivial_abi has to be dropped.
6591   if (Record->hasAttr<TrivialABIAttr>())
6592     checkIllFormedTrivialABIStruct(*Record);
6593 
6594   // Set HasTrivialSpecialMemberForCall if the record has attribute
6595   // "trivial_abi".
6596   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6597 
6598   if (HasTrivialABI)
6599     Record->setHasTrivialSpecialMemberForCall();
6600 
6601   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6602   // We check these last because they can depend on the properties of the
6603   // primary comparison functions (==, <=>).
6604   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6605 
6606   // Perform checks that can't be done until we know all the properties of a
6607   // member function (whether it's defaulted, deleted, virtual, overriding,
6608   // ...).
6609   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6610     // A static function cannot override anything.
6611     if (MD->getStorageClass() == SC_Static) {
6612       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6613                           [](const CXXMethodDecl *) { return true; }))
6614         return;
6615     }
6616 
6617     // A deleted function cannot override a non-deleted function and vice
6618     // versa.
6619     if (ReportOverrides(*this,
6620                         MD->isDeleted() ? diag::err_deleted_override
6621                                         : diag::err_non_deleted_override,
6622                         MD, [&](const CXXMethodDecl *V) {
6623                           return MD->isDeleted() != V->isDeleted();
6624                         })) {
6625       if (MD->isDefaulted() && MD->isDeleted())
6626         // Explain why this defaulted function was deleted.
6627         DiagnoseDeletedDefaultedFunction(MD);
6628       return;
6629     }
6630 
6631     // A consteval function cannot override a non-consteval function and vice
6632     // versa.
6633     if (ReportOverrides(*this,
6634                         MD->isConsteval() ? diag::err_consteval_override
6635                                           : diag::err_non_consteval_override,
6636                         MD, [&](const CXXMethodDecl *V) {
6637                           return MD->isConsteval() != V->isConsteval();
6638                         })) {
6639       if (MD->isDefaulted() && MD->isDeleted())
6640         // Explain why this defaulted function was deleted.
6641         DiagnoseDeletedDefaultedFunction(MD);
6642       return;
6643     }
6644   };
6645 
6646   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6647     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6648       return false;
6649 
6650     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6651     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6652         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6653       DefaultedSecondaryComparisons.push_back(FD);
6654       return true;
6655     }
6656 
6657     CheckExplicitlyDefaultedFunction(S, FD);
6658     return false;
6659   };
6660 
6661   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6662     // Check whether the explicitly-defaulted members are valid.
6663     bool Incomplete = CheckForDefaultedFunction(M);
6664 
6665     // Skip the rest of the checks for a member of a dependent class.
6666     if (Record->isDependentType())
6667       return;
6668 
6669     // For an explicitly defaulted or deleted special member, we defer
6670     // determining triviality until the class is complete. That time is now!
6671     CXXSpecialMember CSM = getSpecialMember(M);
6672     if (!M->isImplicit() && !M->isUserProvided()) {
6673       if (CSM != CXXInvalid) {
6674         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6675         // Inform the class that we've finished declaring this member.
6676         Record->finishedDefaultedOrDeletedMember(M);
6677         M->setTrivialForCall(
6678             HasTrivialABI ||
6679             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6680         Record->setTrivialForCallFlags(M);
6681       }
6682     }
6683 
6684     // Set triviality for the purpose of calls if this is a user-provided
6685     // copy/move constructor or destructor.
6686     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6687          CSM == CXXDestructor) && M->isUserProvided()) {
6688       M->setTrivialForCall(HasTrivialABI);
6689       Record->setTrivialForCallFlags(M);
6690     }
6691 
6692     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6693         M->hasAttr<DLLExportAttr>()) {
6694       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6695           M->isTrivial() &&
6696           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6697            CSM == CXXDestructor))
6698         M->dropAttr<DLLExportAttr>();
6699 
6700       if (M->hasAttr<DLLExportAttr>()) {
6701         // Define after any fields with in-class initializers have been parsed.
6702         DelayedDllExportMemberFunctions.push_back(M);
6703       }
6704     }
6705 
6706     // Define defaulted constexpr virtual functions that override a base class
6707     // function right away.
6708     // FIXME: We can defer doing this until the vtable is marked as used.
6709     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6710       DefineDefaultedFunction(*this, M, M->getLocation());
6711 
6712     if (!Incomplete)
6713       CheckCompletedMemberFunction(M);
6714   };
6715 
6716   // Check the destructor before any other member function. We need to
6717   // determine whether it's trivial in order to determine whether the claas
6718   // type is a literal type, which is a prerequisite for determining whether
6719   // other special member functions are valid and whether they're implicitly
6720   // 'constexpr'.
6721   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6722     CompleteMemberFunction(Dtor);
6723 
6724   bool HasMethodWithOverrideControl = false,
6725        HasOverridingMethodWithoutOverrideControl = false;
6726   for (auto *D : Record->decls()) {
6727     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6728       // FIXME: We could do this check for dependent types with non-dependent
6729       // bases.
6730       if (!Record->isDependentType()) {
6731         // See if a method overloads virtual methods in a base
6732         // class without overriding any.
6733         if (!M->isStatic())
6734           DiagnoseHiddenVirtualMethods(M);
6735         if (M->hasAttr<OverrideAttr>())
6736           HasMethodWithOverrideControl = true;
6737         else if (M->size_overridden_methods() > 0)
6738           HasOverridingMethodWithoutOverrideControl = true;
6739       }
6740 
6741       if (!isa<CXXDestructorDecl>(M))
6742         CompleteMemberFunction(M);
6743     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6744       CheckForDefaultedFunction(
6745           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6746     }
6747   }
6748 
6749   if (HasMethodWithOverrideControl &&
6750       HasOverridingMethodWithoutOverrideControl) {
6751     // At least one method has the 'override' control declared.
6752     // Diagnose all other overridden methods which do not have 'override'
6753     // specified on them.
6754     for (auto *M : Record->methods())
6755       DiagnoseAbsenceOfOverrideControl(M);
6756   }
6757 
6758   // Check the defaulted secondary comparisons after any other member functions.
6759   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6760     CheckExplicitlyDefaultedFunction(S, FD);
6761 
6762     // If this is a member function, we deferred checking it until now.
6763     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6764       CheckCompletedMemberFunction(MD);
6765   }
6766 
6767   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6768   // whether this class uses any C++ features that are implemented
6769   // completely differently in MSVC, and if so, emit a diagnostic.
6770   // That diagnostic defaults to an error, but we allow projects to
6771   // map it down to a warning (or ignore it).  It's a fairly common
6772   // practice among users of the ms_struct pragma to mass-annotate
6773   // headers, sweeping up a bunch of types that the project doesn't
6774   // really rely on MSVC-compatible layout for.  We must therefore
6775   // support "ms_struct except for C++ stuff" as a secondary ABI.
6776   // Don't emit this diagnostic if the feature was enabled as a
6777   // language option (as opposed to via a pragma or attribute), as
6778   // the option -mms-bitfields otherwise essentially makes it impossible
6779   // to build C++ code, unless this diagnostic is turned off.
6780   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6781       (Record->isPolymorphic() || Record->getNumBases())) {
6782     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6783   }
6784 
6785   checkClassLevelDLLAttribute(Record);
6786   checkClassLevelCodeSegAttribute(Record);
6787 
6788   bool ClangABICompat4 =
6789       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6790   TargetInfo::CallingConvKind CCK =
6791       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6792   bool CanPass = canPassInRegisters(*this, Record, CCK);
6793 
6794   // Do not change ArgPassingRestrictions if it has already been set to
6795   // APK_CanNeverPassInRegs.
6796   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6797     Record->setArgPassingRestrictions(CanPass
6798                                           ? RecordDecl::APK_CanPassInRegs
6799                                           : RecordDecl::APK_CannotPassInRegs);
6800 
6801   // If canPassInRegisters returns true despite the record having a non-trivial
6802   // destructor, the record is destructed in the callee. This happens only when
6803   // the record or one of its subobjects has a field annotated with trivial_abi
6804   // or a field qualified with ObjC __strong/__weak.
6805   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6806     Record->setParamDestroyedInCallee(true);
6807   else if (Record->hasNonTrivialDestructor())
6808     Record->setParamDestroyedInCallee(CanPass);
6809 
6810   if (getLangOpts().ForceEmitVTables) {
6811     // If we want to emit all the vtables, we need to mark it as used.  This
6812     // is especially required for cases like vtable assumption loads.
6813     MarkVTableUsed(Record->getInnerLocStart(), Record);
6814   }
6815 
6816   if (getLangOpts().CUDA) {
6817     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6818       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6819     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6820       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6821   }
6822 }
6823 
6824 /// Look up the special member function that would be called by a special
6825 /// member function for a subobject of class type.
6826 ///
6827 /// \param Class The class type of the subobject.
6828 /// \param CSM The kind of special member function.
6829 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6830 /// \param ConstRHS True if this is a copy operation with a const object
6831 ///        on its RHS, that is, if the argument to the outer special member
6832 ///        function is 'const' and this is not a field marked 'mutable'.
6833 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6834     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6835     unsigned FieldQuals, bool ConstRHS) {
6836   unsigned LHSQuals = 0;
6837   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6838     LHSQuals = FieldQuals;
6839 
6840   unsigned RHSQuals = FieldQuals;
6841   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6842     RHSQuals = 0;
6843   else if (ConstRHS)
6844     RHSQuals |= Qualifiers::Const;
6845 
6846   return S.LookupSpecialMember(Class, CSM,
6847                                RHSQuals & Qualifiers::Const,
6848                                RHSQuals & Qualifiers::Volatile,
6849                                false,
6850                                LHSQuals & Qualifiers::Const,
6851                                LHSQuals & Qualifiers::Volatile);
6852 }
6853 
6854 class Sema::InheritedConstructorInfo {
6855   Sema &S;
6856   SourceLocation UseLoc;
6857 
6858   /// A mapping from the base classes through which the constructor was
6859   /// inherited to the using shadow declaration in that base class (or a null
6860   /// pointer if the constructor was declared in that base class).
6861   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6862       InheritedFromBases;
6863 
6864 public:
6865   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6866                            ConstructorUsingShadowDecl *Shadow)
6867       : S(S), UseLoc(UseLoc) {
6868     bool DiagnosedMultipleConstructedBases = false;
6869     CXXRecordDecl *ConstructedBase = nullptr;
6870     UsingDecl *ConstructedBaseUsing = nullptr;
6871 
6872     // Find the set of such base class subobjects and check that there's a
6873     // unique constructed subobject.
6874     for (auto *D : Shadow->redecls()) {
6875       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6876       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6877       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6878 
6879       InheritedFromBases.insert(
6880           std::make_pair(DNominatedBase->getCanonicalDecl(),
6881                          DShadow->getNominatedBaseClassShadowDecl()));
6882       if (DShadow->constructsVirtualBase())
6883         InheritedFromBases.insert(
6884             std::make_pair(DConstructedBase->getCanonicalDecl(),
6885                            DShadow->getConstructedBaseClassShadowDecl()));
6886       else
6887         assert(DNominatedBase == DConstructedBase);
6888 
6889       // [class.inhctor.init]p2:
6890       //   If the constructor was inherited from multiple base class subobjects
6891       //   of type B, the program is ill-formed.
6892       if (!ConstructedBase) {
6893         ConstructedBase = DConstructedBase;
6894         ConstructedBaseUsing = D->getUsingDecl();
6895       } else if (ConstructedBase != DConstructedBase &&
6896                  !Shadow->isInvalidDecl()) {
6897         if (!DiagnosedMultipleConstructedBases) {
6898           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6899               << Shadow->getTargetDecl();
6900           S.Diag(ConstructedBaseUsing->getLocation(),
6901                diag::note_ambiguous_inherited_constructor_using)
6902               << ConstructedBase;
6903           DiagnosedMultipleConstructedBases = true;
6904         }
6905         S.Diag(D->getUsingDecl()->getLocation(),
6906                diag::note_ambiguous_inherited_constructor_using)
6907             << DConstructedBase;
6908       }
6909     }
6910 
6911     if (DiagnosedMultipleConstructedBases)
6912       Shadow->setInvalidDecl();
6913   }
6914 
6915   /// Find the constructor to use for inherited construction of a base class,
6916   /// and whether that base class constructor inherits the constructor from a
6917   /// virtual base class (in which case it won't actually invoke it).
6918   std::pair<CXXConstructorDecl *, bool>
6919   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6920     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6921     if (It == InheritedFromBases.end())
6922       return std::make_pair(nullptr, false);
6923 
6924     // This is an intermediary class.
6925     if (It->second)
6926       return std::make_pair(
6927           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6928           It->second->constructsVirtualBase());
6929 
6930     // This is the base class from which the constructor was inherited.
6931     return std::make_pair(Ctor, false);
6932   }
6933 };
6934 
6935 /// Is the special member function which would be selected to perform the
6936 /// specified operation on the specified class type a constexpr constructor?
6937 static bool
6938 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6939                          Sema::CXXSpecialMember CSM, unsigned Quals,
6940                          bool ConstRHS,
6941                          CXXConstructorDecl *InheritedCtor = nullptr,
6942                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6943   // If we're inheriting a constructor, see if we need to call it for this base
6944   // class.
6945   if (InheritedCtor) {
6946     assert(CSM == Sema::CXXDefaultConstructor);
6947     auto BaseCtor =
6948         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6949     if (BaseCtor)
6950       return BaseCtor->isConstexpr();
6951   }
6952 
6953   if (CSM == Sema::CXXDefaultConstructor)
6954     return ClassDecl->hasConstexprDefaultConstructor();
6955   if (CSM == Sema::CXXDestructor)
6956     return ClassDecl->hasConstexprDestructor();
6957 
6958   Sema::SpecialMemberOverloadResult SMOR =
6959       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6960   if (!SMOR.getMethod())
6961     // A constructor we wouldn't select can't be "involved in initializing"
6962     // anything.
6963     return true;
6964   return SMOR.getMethod()->isConstexpr();
6965 }
6966 
6967 /// Determine whether the specified special member function would be constexpr
6968 /// if it were implicitly defined.
6969 static bool defaultedSpecialMemberIsConstexpr(
6970     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6971     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6972     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6973   if (!S.getLangOpts().CPlusPlus11)
6974     return false;
6975 
6976   // C++11 [dcl.constexpr]p4:
6977   // In the definition of a constexpr constructor [...]
6978   bool Ctor = true;
6979   switch (CSM) {
6980   case Sema::CXXDefaultConstructor:
6981     if (Inherited)
6982       break;
6983     // Since default constructor lookup is essentially trivial (and cannot
6984     // involve, for instance, template instantiation), we compute whether a
6985     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6986     //
6987     // This is important for performance; we need to know whether the default
6988     // constructor is constexpr to determine whether the type is a literal type.
6989     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6990 
6991   case Sema::CXXCopyConstructor:
6992   case Sema::CXXMoveConstructor:
6993     // For copy or move constructors, we need to perform overload resolution.
6994     break;
6995 
6996   case Sema::CXXCopyAssignment:
6997   case Sema::CXXMoveAssignment:
6998     if (!S.getLangOpts().CPlusPlus14)
6999       return false;
7000     // In C++1y, we need to perform overload resolution.
7001     Ctor = false;
7002     break;
7003 
7004   case Sema::CXXDestructor:
7005     return ClassDecl->defaultedDestructorIsConstexpr();
7006 
7007   case Sema::CXXInvalid:
7008     return false;
7009   }
7010 
7011   //   -- if the class is a non-empty union, or for each non-empty anonymous
7012   //      union member of a non-union class, exactly one non-static data member
7013   //      shall be initialized; [DR1359]
7014   //
7015   // If we squint, this is guaranteed, since exactly one non-static data member
7016   // will be initialized (if the constructor isn't deleted), we just don't know
7017   // which one.
7018   if (Ctor && ClassDecl->isUnion())
7019     return CSM == Sema::CXXDefaultConstructor
7020                ? ClassDecl->hasInClassInitializer() ||
7021                      !ClassDecl->hasVariantMembers()
7022                : true;
7023 
7024   //   -- the class shall not have any virtual base classes;
7025   if (Ctor && ClassDecl->getNumVBases())
7026     return false;
7027 
7028   // C++1y [class.copy]p26:
7029   //   -- [the class] is a literal type, and
7030   if (!Ctor && !ClassDecl->isLiteral())
7031     return false;
7032 
7033   //   -- every constructor involved in initializing [...] base class
7034   //      sub-objects shall be a constexpr constructor;
7035   //   -- the assignment operator selected to copy/move each direct base
7036   //      class is a constexpr function, and
7037   for (const auto &B : ClassDecl->bases()) {
7038     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7039     if (!BaseType) continue;
7040 
7041     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7042     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7043                                   InheritedCtor, Inherited))
7044       return false;
7045   }
7046 
7047   //   -- every constructor involved in initializing non-static data members
7048   //      [...] shall be a constexpr constructor;
7049   //   -- every non-static data member and base class sub-object shall be
7050   //      initialized
7051   //   -- for each non-static data member of X that is of class type (or array
7052   //      thereof), the assignment operator selected to copy/move that member is
7053   //      a constexpr function
7054   for (const auto *F : ClassDecl->fields()) {
7055     if (F->isInvalidDecl())
7056       continue;
7057     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7058       continue;
7059     QualType BaseType = S.Context.getBaseElementType(F->getType());
7060     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7061       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7062       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7063                                     BaseType.getCVRQualifiers(),
7064                                     ConstArg && !F->isMutable()))
7065         return false;
7066     } else if (CSM == Sema::CXXDefaultConstructor) {
7067       return false;
7068     }
7069   }
7070 
7071   // All OK, it's constexpr!
7072   return true;
7073 }
7074 
7075 namespace {
7076 /// RAII object to register a defaulted function as having its exception
7077 /// specification computed.
7078 struct ComputingExceptionSpec {
7079   Sema &S;
7080 
7081   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7082       : S(S) {
7083     Sema::CodeSynthesisContext Ctx;
7084     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7085     Ctx.PointOfInstantiation = Loc;
7086     Ctx.Entity = FD;
7087     S.pushCodeSynthesisContext(Ctx);
7088   }
7089   ~ComputingExceptionSpec() {
7090     S.popCodeSynthesisContext();
7091   }
7092 };
7093 }
7094 
7095 static Sema::ImplicitExceptionSpecification
7096 ComputeDefaultedSpecialMemberExceptionSpec(
7097     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7098     Sema::InheritedConstructorInfo *ICI);
7099 
7100 static Sema::ImplicitExceptionSpecification
7101 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7102                                         FunctionDecl *FD,
7103                                         Sema::DefaultedComparisonKind DCK);
7104 
7105 static Sema::ImplicitExceptionSpecification
7106 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7107   auto DFK = S.getDefaultedFunctionKind(FD);
7108   if (DFK.isSpecialMember())
7109     return ComputeDefaultedSpecialMemberExceptionSpec(
7110         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7111   if (DFK.isComparison())
7112     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7113                                                    DFK.asComparison());
7114 
7115   auto *CD = cast<CXXConstructorDecl>(FD);
7116   assert(CD->getInheritedConstructor() &&
7117          "only defaulted functions and inherited constructors have implicit "
7118          "exception specs");
7119   Sema::InheritedConstructorInfo ICI(
7120       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7121   return ComputeDefaultedSpecialMemberExceptionSpec(
7122       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7123 }
7124 
7125 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7126                                                             CXXMethodDecl *MD) {
7127   FunctionProtoType::ExtProtoInfo EPI;
7128 
7129   // Build an exception specification pointing back at this member.
7130   EPI.ExceptionSpec.Type = EST_Unevaluated;
7131   EPI.ExceptionSpec.SourceDecl = MD;
7132 
7133   // Set the calling convention to the default for C++ instance methods.
7134   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7135       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7136                                             /*IsCXXMethod=*/true));
7137   return EPI;
7138 }
7139 
7140 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7141   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7142   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7143     return;
7144 
7145   // Evaluate the exception specification.
7146   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7147   auto ESI = IES.getExceptionSpec();
7148 
7149   // Update the type of the special member to use it.
7150   UpdateExceptionSpec(FD, ESI);
7151 }
7152 
7153 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7154   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7155 
7156   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7157   if (!DefKind) {
7158     assert(FD->getDeclContext()->isDependentContext());
7159     return;
7160   }
7161 
7162   if (DefKind.isSpecialMember()
7163           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7164                                                   DefKind.asSpecialMember())
7165           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7166     FD->setInvalidDecl();
7167 }
7168 
7169 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7170                                                  CXXSpecialMember CSM) {
7171   CXXRecordDecl *RD = MD->getParent();
7172 
7173   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7174          "not an explicitly-defaulted special member");
7175 
7176   // Defer all checking for special members of a dependent type.
7177   if (RD->isDependentType())
7178     return false;
7179 
7180   // Whether this was the first-declared instance of the constructor.
7181   // This affects whether we implicitly add an exception spec and constexpr.
7182   bool First = MD == MD->getCanonicalDecl();
7183 
7184   bool HadError = false;
7185 
7186   // C++11 [dcl.fct.def.default]p1:
7187   //   A function that is explicitly defaulted shall
7188   //     -- be a special member function [...] (checked elsewhere),
7189   //     -- have the same type (except for ref-qualifiers, and except that a
7190   //        copy operation can take a non-const reference) as an implicit
7191   //        declaration, and
7192   //     -- not have default arguments.
7193   // C++2a changes the second bullet to instead delete the function if it's
7194   // defaulted on its first declaration, unless it's "an assignment operator,
7195   // and its return type differs or its parameter type is not a reference".
7196   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7197   bool ShouldDeleteForTypeMismatch = false;
7198   unsigned ExpectedParams = 1;
7199   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7200     ExpectedParams = 0;
7201   if (MD->getNumParams() != ExpectedParams) {
7202     // This checks for default arguments: a copy or move constructor with a
7203     // default argument is classified as a default constructor, and assignment
7204     // operations and destructors can't have default arguments.
7205     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7206       << CSM << MD->getSourceRange();
7207     HadError = true;
7208   } else if (MD->isVariadic()) {
7209     if (DeleteOnTypeMismatch)
7210       ShouldDeleteForTypeMismatch = true;
7211     else {
7212       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7213         << CSM << MD->getSourceRange();
7214       HadError = true;
7215     }
7216   }
7217 
7218   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7219 
7220   bool CanHaveConstParam = false;
7221   if (CSM == CXXCopyConstructor)
7222     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7223   else if (CSM == CXXCopyAssignment)
7224     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7225 
7226   QualType ReturnType = Context.VoidTy;
7227   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7228     // Check for return type matching.
7229     ReturnType = Type->getReturnType();
7230 
7231     QualType DeclType = Context.getTypeDeclType(RD);
7232     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7233     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7234 
7235     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7236       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7237         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7238       HadError = true;
7239     }
7240 
7241     // A defaulted special member cannot have cv-qualifiers.
7242     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7243       if (DeleteOnTypeMismatch)
7244         ShouldDeleteForTypeMismatch = true;
7245       else {
7246         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7247           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7248         HadError = true;
7249       }
7250     }
7251   }
7252 
7253   // Check for parameter type matching.
7254   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7255   bool HasConstParam = false;
7256   if (ExpectedParams && ArgType->isReferenceType()) {
7257     // Argument must be reference to possibly-const T.
7258     QualType ReferentType = ArgType->getPointeeType();
7259     HasConstParam = ReferentType.isConstQualified();
7260 
7261     if (ReferentType.isVolatileQualified()) {
7262       if (DeleteOnTypeMismatch)
7263         ShouldDeleteForTypeMismatch = true;
7264       else {
7265         Diag(MD->getLocation(),
7266              diag::err_defaulted_special_member_volatile_param) << CSM;
7267         HadError = true;
7268       }
7269     }
7270 
7271     if (HasConstParam && !CanHaveConstParam) {
7272       if (DeleteOnTypeMismatch)
7273         ShouldDeleteForTypeMismatch = true;
7274       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7275         Diag(MD->getLocation(),
7276              diag::err_defaulted_special_member_copy_const_param)
7277           << (CSM == CXXCopyAssignment);
7278         // FIXME: Explain why this special member can't be const.
7279         HadError = true;
7280       } else {
7281         Diag(MD->getLocation(),
7282              diag::err_defaulted_special_member_move_const_param)
7283           << (CSM == CXXMoveAssignment);
7284         HadError = true;
7285       }
7286     }
7287   } else if (ExpectedParams) {
7288     // A copy assignment operator can take its argument by value, but a
7289     // defaulted one cannot.
7290     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7291     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7292     HadError = true;
7293   }
7294 
7295   // C++11 [dcl.fct.def.default]p2:
7296   //   An explicitly-defaulted function may be declared constexpr only if it
7297   //   would have been implicitly declared as constexpr,
7298   // Do not apply this rule to members of class templates, since core issue 1358
7299   // makes such functions always instantiate to constexpr functions. For
7300   // functions which cannot be constexpr (for non-constructors in C++11 and for
7301   // destructors in C++14 and C++17), this is checked elsewhere.
7302   //
7303   // FIXME: This should not apply if the member is deleted.
7304   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7305                                                      HasConstParam);
7306   if ((getLangOpts().CPlusPlus20 ||
7307        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7308                                   : isa<CXXConstructorDecl>(MD))) &&
7309       MD->isConstexpr() && !Constexpr &&
7310       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7311     Diag(MD->getBeginLoc(), MD->isConsteval()
7312                                 ? diag::err_incorrect_defaulted_consteval
7313                                 : diag::err_incorrect_defaulted_constexpr)
7314         << CSM;
7315     // FIXME: Explain why the special member can't be constexpr.
7316     HadError = true;
7317   }
7318 
7319   if (First) {
7320     // C++2a [dcl.fct.def.default]p3:
7321     //   If a function is explicitly defaulted on its first declaration, it is
7322     //   implicitly considered to be constexpr if the implicit declaration
7323     //   would be.
7324     MD->setConstexprKind(
7325         Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7326                   : CSK_unspecified);
7327 
7328     if (!Type->hasExceptionSpec()) {
7329       // C++2a [except.spec]p3:
7330       //   If a declaration of a function does not have a noexcept-specifier
7331       //   [and] is defaulted on its first declaration, [...] the exception
7332       //   specification is as specified below
7333       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7334       EPI.ExceptionSpec.Type = EST_Unevaluated;
7335       EPI.ExceptionSpec.SourceDecl = MD;
7336       MD->setType(Context.getFunctionType(ReturnType,
7337                                           llvm::makeArrayRef(&ArgType,
7338                                                              ExpectedParams),
7339                                           EPI));
7340     }
7341   }
7342 
7343   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7344     if (First) {
7345       SetDeclDeleted(MD, MD->getLocation());
7346       if (!inTemplateInstantiation() && !HadError) {
7347         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7348         if (ShouldDeleteForTypeMismatch) {
7349           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7350         } else {
7351           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7352         }
7353       }
7354       if (ShouldDeleteForTypeMismatch && !HadError) {
7355         Diag(MD->getLocation(),
7356              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7357       }
7358     } else {
7359       // C++11 [dcl.fct.def.default]p4:
7360       //   [For a] user-provided explicitly-defaulted function [...] if such a
7361       //   function is implicitly defined as deleted, the program is ill-formed.
7362       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7363       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7364       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7365       HadError = true;
7366     }
7367   }
7368 
7369   return HadError;
7370 }
7371 
7372 namespace {
7373 /// Helper class for building and checking a defaulted comparison.
7374 ///
7375 /// Defaulted functions are built in two phases:
7376 ///
7377 ///  * First, the set of operations that the function will perform are
7378 ///    identified, and some of them are checked. If any of the checked
7379 ///    operations is invalid in certain ways, the comparison function is
7380 ///    defined as deleted and no body is built.
7381 ///  * Then, if the function is not defined as deleted, the body is built.
7382 ///
7383 /// This is accomplished by performing two visitation steps over the eventual
7384 /// body of the function.
7385 template<typename Derived, typename ResultList, typename Result,
7386          typename Subobject>
7387 class DefaultedComparisonVisitor {
7388 public:
7389   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7390 
7391   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7392                              DefaultedComparisonKind DCK)
7393       : S(S), RD(RD), FD(FD), DCK(DCK) {
7394     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7395       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7396       // UnresolvedSet to avoid this copy.
7397       Fns.assign(Info->getUnqualifiedLookups().begin(),
7398                  Info->getUnqualifiedLookups().end());
7399     }
7400   }
7401 
7402   ResultList visit() {
7403     // The type of an lvalue naming a parameter of this function.
7404     QualType ParamLvalType =
7405         FD->getParamDecl(0)->getType().getNonReferenceType();
7406 
7407     ResultList Results;
7408 
7409     switch (DCK) {
7410     case DefaultedComparisonKind::None:
7411       llvm_unreachable("not a defaulted comparison");
7412 
7413     case DefaultedComparisonKind::Equal:
7414     case DefaultedComparisonKind::ThreeWay:
7415       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7416       return Results;
7417 
7418     case DefaultedComparisonKind::NotEqual:
7419     case DefaultedComparisonKind::Relational:
7420       Results.add(getDerived().visitExpandedSubobject(
7421           ParamLvalType, getDerived().getCompleteObject()));
7422       return Results;
7423     }
7424     llvm_unreachable("");
7425   }
7426 
7427 protected:
7428   Derived &getDerived() { return static_cast<Derived&>(*this); }
7429 
7430   /// Visit the expanded list of subobjects of the given type, as specified in
7431   /// C++2a [class.compare.default].
7432   ///
7433   /// \return \c true if the ResultList object said we're done, \c false if not.
7434   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7435                        Qualifiers Quals) {
7436     // C++2a [class.compare.default]p4:
7437     //   The direct base class subobjects of C
7438     for (CXXBaseSpecifier &Base : Record->bases())
7439       if (Results.add(getDerived().visitSubobject(
7440               S.Context.getQualifiedType(Base.getType(), Quals),
7441               getDerived().getBase(&Base))))
7442         return true;
7443 
7444     //   followed by the non-static data members of C
7445     for (FieldDecl *Field : Record->fields()) {
7446       // Recursively expand anonymous structs.
7447       if (Field->isAnonymousStructOrUnion()) {
7448         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7449                             Quals))
7450           return true;
7451         continue;
7452       }
7453 
7454       // Figure out the type of an lvalue denoting this field.
7455       Qualifiers FieldQuals = Quals;
7456       if (Field->isMutable())
7457         FieldQuals.removeConst();
7458       QualType FieldType =
7459           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7460 
7461       if (Results.add(getDerived().visitSubobject(
7462               FieldType, getDerived().getField(Field))))
7463         return true;
7464     }
7465 
7466     //   form a list of subobjects.
7467     return false;
7468   }
7469 
7470   Result visitSubobject(QualType Type, Subobject Subobj) {
7471     //   In that list, any subobject of array type is recursively expanded
7472     const ArrayType *AT = S.Context.getAsArrayType(Type);
7473     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7474       return getDerived().visitSubobjectArray(CAT->getElementType(),
7475                                               CAT->getSize(), Subobj);
7476     return getDerived().visitExpandedSubobject(Type, Subobj);
7477   }
7478 
7479   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7480                              Subobject Subobj) {
7481     return getDerived().visitSubobject(Type, Subobj);
7482   }
7483 
7484 protected:
7485   Sema &S;
7486   CXXRecordDecl *RD;
7487   FunctionDecl *FD;
7488   DefaultedComparisonKind DCK;
7489   UnresolvedSet<16> Fns;
7490 };
7491 
7492 /// Information about a defaulted comparison, as determined by
7493 /// DefaultedComparisonAnalyzer.
7494 struct DefaultedComparisonInfo {
7495   bool Deleted = false;
7496   bool Constexpr = true;
7497   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7498 
7499   static DefaultedComparisonInfo deleted() {
7500     DefaultedComparisonInfo Deleted;
7501     Deleted.Deleted = true;
7502     return Deleted;
7503   }
7504 
7505   bool add(const DefaultedComparisonInfo &R) {
7506     Deleted |= R.Deleted;
7507     Constexpr &= R.Constexpr;
7508     Category = commonComparisonType(Category, R.Category);
7509     return Deleted;
7510   }
7511 };
7512 
7513 /// An element in the expanded list of subobjects of a defaulted comparison, as
7514 /// specified in C++2a [class.compare.default]p4.
7515 struct DefaultedComparisonSubobject {
7516   enum { CompleteObject, Member, Base } Kind;
7517   NamedDecl *Decl;
7518   SourceLocation Loc;
7519 };
7520 
7521 /// A visitor over the notional body of a defaulted comparison that determines
7522 /// whether that body would be deleted or constexpr.
7523 class DefaultedComparisonAnalyzer
7524     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7525                                         DefaultedComparisonInfo,
7526                                         DefaultedComparisonInfo,
7527                                         DefaultedComparisonSubobject> {
7528 public:
7529   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7530 
7531 private:
7532   DiagnosticKind Diagnose;
7533 
7534 public:
7535   using Base = DefaultedComparisonVisitor;
7536   using Result = DefaultedComparisonInfo;
7537   using Subobject = DefaultedComparisonSubobject;
7538 
7539   friend Base;
7540 
7541   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7542                               DefaultedComparisonKind DCK,
7543                               DiagnosticKind Diagnose = NoDiagnostics)
7544       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7545 
7546   Result visit() {
7547     if ((DCK == DefaultedComparisonKind::Equal ||
7548          DCK == DefaultedComparisonKind::ThreeWay) &&
7549         RD->hasVariantMembers()) {
7550       // C++2a [class.compare.default]p2 [P2002R0]:
7551       //   A defaulted comparison operator function for class C is defined as
7552       //   deleted if [...] C has variant members.
7553       if (Diagnose == ExplainDeleted) {
7554         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7555           << FD << RD->isUnion() << RD;
7556       }
7557       return Result::deleted();
7558     }
7559 
7560     return Base::visit();
7561   }
7562 
7563 private:
7564   Subobject getCompleteObject() {
7565     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7566   }
7567 
7568   Subobject getBase(CXXBaseSpecifier *Base) {
7569     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7570                      Base->getBaseTypeLoc()};
7571   }
7572 
7573   Subobject getField(FieldDecl *Field) {
7574     return Subobject{Subobject::Member, Field, Field->getLocation()};
7575   }
7576 
7577   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7578     // C++2a [class.compare.default]p2 [P2002R0]:
7579     //   A defaulted <=> or == operator function for class C is defined as
7580     //   deleted if any non-static data member of C is of reference type
7581     if (Type->isReferenceType()) {
7582       if (Diagnose == ExplainDeleted) {
7583         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7584             << FD << RD;
7585       }
7586       return Result::deleted();
7587     }
7588 
7589     // [...] Let xi be an lvalue denoting the ith element [...]
7590     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7591     Expr *Args[] = {&Xi, &Xi};
7592 
7593     // All operators start by trying to apply that same operator recursively.
7594     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7595     assert(OO != OO_None && "not an overloaded operator!");
7596     return visitBinaryOperator(OO, Args, Subobj);
7597   }
7598 
7599   Result
7600   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7601                       Subobject Subobj,
7602                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7603     // Note that there is no need to consider rewritten candidates here if
7604     // we've already found there is no viable 'operator<=>' candidate (and are
7605     // considering synthesizing a '<=>' from '==' and '<').
7606     OverloadCandidateSet CandidateSet(
7607         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7608         OverloadCandidateSet::OperatorRewriteInfo(
7609             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7610 
7611     /// C++2a [class.compare.default]p1 [P2002R0]:
7612     ///   [...] the defaulted function itself is never a candidate for overload
7613     ///   resolution [...]
7614     CandidateSet.exclude(FD);
7615 
7616     if (Args[0]->getType()->isOverloadableType())
7617       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7618     else {
7619       // FIXME: We determine whether this is a valid expression by checking to
7620       // see if there's a viable builtin operator candidate for it. That isn't
7621       // really what the rules ask us to do, but should give the right results.
7622       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7623     }
7624 
7625     Result R;
7626 
7627     OverloadCandidateSet::iterator Best;
7628     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7629     case OR_Success: {
7630       // C++2a [class.compare.secondary]p2 [P2002R0]:
7631       //   The operator function [...] is defined as deleted if [...] the
7632       //   candidate selected by overload resolution is not a rewritten
7633       //   candidate.
7634       if ((DCK == DefaultedComparisonKind::NotEqual ||
7635            DCK == DefaultedComparisonKind::Relational) &&
7636           !Best->RewriteKind) {
7637         if (Diagnose == ExplainDeleted) {
7638           S.Diag(Best->Function->getLocation(),
7639                  diag::note_defaulted_comparison_not_rewritten_callee)
7640               << FD;
7641         }
7642         return Result::deleted();
7643       }
7644 
7645       // Throughout C++2a [class.compare]: if overload resolution does not
7646       // result in a usable function, the candidate function is defined as
7647       // deleted. This requires that we selected an accessible function.
7648       //
7649       // Note that this only considers the access of the function when named
7650       // within the type of the subobject, and not the access path for any
7651       // derived-to-base conversion.
7652       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7653       if (ArgClass && Best->FoundDecl.getDecl() &&
7654           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7655         QualType ObjectType = Subobj.Kind == Subobject::Member
7656                                   ? Args[0]->getType()
7657                                   : S.Context.getRecordType(RD);
7658         if (!S.isMemberAccessibleForDeletion(
7659                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7660                 Diagnose == ExplainDeleted
7661                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7662                           << FD << Subobj.Kind << Subobj.Decl
7663                     : S.PDiag()))
7664           return Result::deleted();
7665       }
7666 
7667       // C++2a [class.compare.default]p3 [P2002R0]:
7668       //   A defaulted comparison function is constexpr-compatible if [...]
7669       //   no overlod resolution performed [...] results in a non-constexpr
7670       //   function.
7671       if (FunctionDecl *BestFD = Best->Function) {
7672         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7673         // If it's not constexpr, explain why not.
7674         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7675           if (Subobj.Kind != Subobject::CompleteObject)
7676             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7677               << Subobj.Kind << Subobj.Decl;
7678           S.Diag(BestFD->getLocation(),
7679                  diag::note_defaulted_comparison_not_constexpr_here);
7680           // Bail out after explaining; we don't want any more notes.
7681           return Result::deleted();
7682         }
7683         R.Constexpr &= BestFD->isConstexpr();
7684       }
7685 
7686       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7687         if (auto *BestFD = Best->Function) {
7688           // If any callee has an undeduced return type, deduce it now.
7689           // FIXME: It's not clear how a failure here should be handled. For
7690           // now, we produce an eager diagnostic, because that is forward
7691           // compatible with most (all?) other reasonable options.
7692           if (BestFD->getReturnType()->isUndeducedType() &&
7693               S.DeduceReturnType(BestFD, FD->getLocation(),
7694                                  /*Diagnose=*/false)) {
7695             // Don't produce a duplicate error when asked to explain why the
7696             // comparison is deleted: we diagnosed that when initially checking
7697             // the defaulted operator.
7698             if (Diagnose == NoDiagnostics) {
7699               S.Diag(
7700                   FD->getLocation(),
7701                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7702                   << Subobj.Kind << Subobj.Decl;
7703               S.Diag(
7704                   Subobj.Loc,
7705                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7706                   << Subobj.Kind << Subobj.Decl;
7707               S.Diag(BestFD->getLocation(),
7708                      diag::note_defaulted_comparison_cannot_deduce_callee)
7709                   << Subobj.Kind << Subobj.Decl;
7710             }
7711             return Result::deleted();
7712           }
7713           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7714               BestFD->getCallResultType())) {
7715             R.Category = Info->Kind;
7716           } else {
7717             if (Diagnose == ExplainDeleted) {
7718               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7719                   << Subobj.Kind << Subobj.Decl
7720                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7721               S.Diag(BestFD->getLocation(),
7722                      diag::note_defaulted_comparison_cannot_deduce_callee)
7723                   << Subobj.Kind << Subobj.Decl;
7724             }
7725             return Result::deleted();
7726           }
7727         } else {
7728           Optional<ComparisonCategoryType> Cat =
7729               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7730           assert(Cat && "no category for builtin comparison?");
7731           R.Category = *Cat;
7732         }
7733       }
7734 
7735       // Note that we might be rewriting to a different operator. That call is
7736       // not considered until we come to actually build the comparison function.
7737       break;
7738     }
7739 
7740     case OR_Ambiguous:
7741       if (Diagnose == ExplainDeleted) {
7742         unsigned Kind = 0;
7743         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7744           Kind = OO == OO_EqualEqual ? 1 : 2;
7745         CandidateSet.NoteCandidates(
7746             PartialDiagnosticAt(
7747                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7748                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7749             S, OCD_AmbiguousCandidates, Args);
7750       }
7751       R = Result::deleted();
7752       break;
7753 
7754     case OR_Deleted:
7755       if (Diagnose == ExplainDeleted) {
7756         if ((DCK == DefaultedComparisonKind::NotEqual ||
7757              DCK == DefaultedComparisonKind::Relational) &&
7758             !Best->RewriteKind) {
7759           S.Diag(Best->Function->getLocation(),
7760                  diag::note_defaulted_comparison_not_rewritten_callee)
7761               << FD;
7762         } else {
7763           S.Diag(Subobj.Loc,
7764                  diag::note_defaulted_comparison_calls_deleted)
7765               << FD << Subobj.Kind << Subobj.Decl;
7766           S.NoteDeletedFunction(Best->Function);
7767         }
7768       }
7769       R = Result::deleted();
7770       break;
7771 
7772     case OR_No_Viable_Function:
7773       // If there's no usable candidate, we're done unless we can rewrite a
7774       // '<=>' in terms of '==' and '<'.
7775       if (OO == OO_Spaceship &&
7776           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7777         // For any kind of comparison category return type, we need a usable
7778         // '==' and a usable '<'.
7779         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7780                                        &CandidateSet)))
7781           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7782         break;
7783       }
7784 
7785       if (Diagnose == ExplainDeleted) {
7786         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7787             << FD << Subobj.Kind << Subobj.Decl;
7788 
7789         // For a three-way comparison, list both the candidates for the
7790         // original operator and the candidates for the synthesized operator.
7791         if (SpaceshipCandidates) {
7792           SpaceshipCandidates->NoteCandidates(
7793               S, Args,
7794               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7795                                                       Args, FD->getLocation()));
7796           S.Diag(Subobj.Loc,
7797                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7798               << (OO == OO_EqualEqual ? 0 : 1);
7799         }
7800 
7801         CandidateSet.NoteCandidates(
7802             S, Args,
7803             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7804                                             FD->getLocation()));
7805       }
7806       R = Result::deleted();
7807       break;
7808     }
7809 
7810     return R;
7811   }
7812 };
7813 
7814 /// A list of statements.
7815 struct StmtListResult {
7816   bool IsInvalid = false;
7817   llvm::SmallVector<Stmt*, 16> Stmts;
7818 
7819   bool add(const StmtResult &S) {
7820     IsInvalid |= S.isInvalid();
7821     if (IsInvalid)
7822       return true;
7823     Stmts.push_back(S.get());
7824     return false;
7825   }
7826 };
7827 
7828 /// A visitor over the notional body of a defaulted comparison that synthesizes
7829 /// the actual body.
7830 class DefaultedComparisonSynthesizer
7831     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7832                                         StmtListResult, StmtResult,
7833                                         std::pair<ExprResult, ExprResult>> {
7834   SourceLocation Loc;
7835   unsigned ArrayDepth = 0;
7836 
7837 public:
7838   using Base = DefaultedComparisonVisitor;
7839   using ExprPair = std::pair<ExprResult, ExprResult>;
7840 
7841   friend Base;
7842 
7843   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7844                                  DefaultedComparisonKind DCK,
7845                                  SourceLocation BodyLoc)
7846       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7847 
7848   /// Build a suitable function body for this defaulted comparison operator.
7849   StmtResult build() {
7850     Sema::CompoundScopeRAII CompoundScope(S);
7851 
7852     StmtListResult Stmts = visit();
7853     if (Stmts.IsInvalid)
7854       return StmtError();
7855 
7856     ExprResult RetVal;
7857     switch (DCK) {
7858     case DefaultedComparisonKind::None:
7859       llvm_unreachable("not a defaulted comparison");
7860 
7861     case DefaultedComparisonKind::Equal: {
7862       // C++2a [class.eq]p3:
7863       //   [...] compar[e] the corresponding elements [...] until the first
7864       //   index i where xi == yi yields [...] false. If no such index exists,
7865       //   V is true. Otherwise, V is false.
7866       //
7867       // Join the comparisons with '&&'s and return the result. Use a right
7868       // fold (traversing the conditions right-to-left), because that
7869       // short-circuits more naturally.
7870       auto OldStmts = std::move(Stmts.Stmts);
7871       Stmts.Stmts.clear();
7872       ExprResult CmpSoFar;
7873       // Finish a particular comparison chain.
7874       auto FinishCmp = [&] {
7875         if (Expr *Prior = CmpSoFar.get()) {
7876           // Convert the last expression to 'return ...;'
7877           if (RetVal.isUnset() && Stmts.Stmts.empty())
7878             RetVal = CmpSoFar;
7879           // Convert any prior comparison to 'if (!(...)) return false;'
7880           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7881             return true;
7882           CmpSoFar = ExprResult();
7883         }
7884         return false;
7885       };
7886       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7887         Expr *E = dyn_cast<Expr>(EAsStmt);
7888         if (!E) {
7889           // Found an array comparison.
7890           if (FinishCmp() || Stmts.add(EAsStmt))
7891             return StmtError();
7892           continue;
7893         }
7894 
7895         if (CmpSoFar.isUnset()) {
7896           CmpSoFar = E;
7897           continue;
7898         }
7899         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7900         if (CmpSoFar.isInvalid())
7901           return StmtError();
7902       }
7903       if (FinishCmp())
7904         return StmtError();
7905       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7906       //   If no such index exists, V is true.
7907       if (RetVal.isUnset())
7908         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7909       break;
7910     }
7911 
7912     case DefaultedComparisonKind::ThreeWay: {
7913       // Per C++2a [class.spaceship]p3, as a fallback add:
7914       // return static_cast<R>(std::strong_ordering::equal);
7915       QualType StrongOrdering = S.CheckComparisonCategoryType(
7916           ComparisonCategoryType::StrongOrdering, Loc,
7917           Sema::ComparisonCategoryUsage::DefaultedOperator);
7918       if (StrongOrdering.isNull())
7919         return StmtError();
7920       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7921                              .getValueInfo(ComparisonCategoryResult::Equal)
7922                              ->VD;
7923       RetVal = getDecl(EqualVD);
7924       if (RetVal.isInvalid())
7925         return StmtError();
7926       RetVal = buildStaticCastToR(RetVal.get());
7927       break;
7928     }
7929 
7930     case DefaultedComparisonKind::NotEqual:
7931     case DefaultedComparisonKind::Relational:
7932       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7933       break;
7934     }
7935 
7936     // Build the final return statement.
7937     if (RetVal.isInvalid())
7938       return StmtError();
7939     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7940     if (ReturnStmt.isInvalid())
7941       return StmtError();
7942     Stmts.Stmts.push_back(ReturnStmt.get());
7943 
7944     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7945   }
7946 
7947 private:
7948   ExprResult getDecl(ValueDecl *VD) {
7949     return S.BuildDeclarationNameExpr(
7950         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7951   }
7952 
7953   ExprResult getParam(unsigned I) {
7954     ParmVarDecl *PD = FD->getParamDecl(I);
7955     return getDecl(PD);
7956   }
7957 
7958   ExprPair getCompleteObject() {
7959     unsigned Param = 0;
7960     ExprResult LHS;
7961     if (isa<CXXMethodDecl>(FD)) {
7962       // LHS is '*this'.
7963       LHS = S.ActOnCXXThis(Loc);
7964       if (!LHS.isInvalid())
7965         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7966     } else {
7967       LHS = getParam(Param++);
7968     }
7969     ExprResult RHS = getParam(Param++);
7970     assert(Param == FD->getNumParams());
7971     return {LHS, RHS};
7972   }
7973 
7974   ExprPair getBase(CXXBaseSpecifier *Base) {
7975     ExprPair Obj = getCompleteObject();
7976     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7977       return {ExprError(), ExprError()};
7978     CXXCastPath Path = {Base};
7979     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7980                                 CK_DerivedToBase, VK_LValue, &Path),
7981             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7982                                 CK_DerivedToBase, VK_LValue, &Path)};
7983   }
7984 
7985   ExprPair getField(FieldDecl *Field) {
7986     ExprPair Obj = getCompleteObject();
7987     if (Obj.first.isInvalid() || Obj.second.isInvalid())
7988       return {ExprError(), ExprError()};
7989 
7990     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
7991     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
7992     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
7993                                       CXXScopeSpec(), Field, Found, NameInfo),
7994             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
7995                                       CXXScopeSpec(), Field, Found, NameInfo)};
7996   }
7997 
7998   // FIXME: When expanding a subobject, register a note in the code synthesis
7999   // stack to say which subobject we're comparing.
8000 
8001   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8002     if (Cond.isInvalid())
8003       return StmtError();
8004 
8005     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8006     if (NotCond.isInvalid())
8007       return StmtError();
8008 
8009     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8010     assert(!False.isInvalid() && "should never fail");
8011     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8012     if (ReturnFalse.isInvalid())
8013       return StmtError();
8014 
8015     return S.ActOnIfStmt(Loc, false, nullptr,
8016                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8017                                           Sema::ConditionKind::Boolean),
8018                          ReturnFalse.get(), SourceLocation(), nullptr);
8019   }
8020 
8021   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8022                                  ExprPair Subobj) {
8023     QualType SizeType = S.Context.getSizeType();
8024     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8025 
8026     // Build 'size_t i$n = 0'.
8027     IdentifierInfo *IterationVarName = nullptr;
8028     {
8029       SmallString<8> Str;
8030       llvm::raw_svector_ostream OS(Str);
8031       OS << "i" << ArrayDepth;
8032       IterationVarName = &S.Context.Idents.get(OS.str());
8033     }
8034     VarDecl *IterationVar = VarDecl::Create(
8035         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8036         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8037     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8038     IterationVar->setInit(
8039         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8040     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8041 
8042     auto IterRef = [&] {
8043       ExprResult Ref = S.BuildDeclarationNameExpr(
8044           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8045           IterationVar);
8046       assert(!Ref.isInvalid() && "can't reference our own variable?");
8047       return Ref.get();
8048     };
8049 
8050     // Build 'i$n != Size'.
8051     ExprResult Cond = S.CreateBuiltinBinOp(
8052         Loc, BO_NE, IterRef(),
8053         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8054     assert(!Cond.isInvalid() && "should never fail");
8055 
8056     // Build '++i$n'.
8057     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8058     assert(!Inc.isInvalid() && "should never fail");
8059 
8060     // Build 'a[i$n]' and 'b[i$n]'.
8061     auto Index = [&](ExprResult E) {
8062       if (E.isInvalid())
8063         return ExprError();
8064       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8065     };
8066     Subobj.first = Index(Subobj.first);
8067     Subobj.second = Index(Subobj.second);
8068 
8069     // Compare the array elements.
8070     ++ArrayDepth;
8071     StmtResult Substmt = visitSubobject(Type, Subobj);
8072     --ArrayDepth;
8073 
8074     if (Substmt.isInvalid())
8075       return StmtError();
8076 
8077     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8078     // For outer levels or for an 'operator<=>' we already have a suitable
8079     // statement that returns as necessary.
8080     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8081       assert(DCK == DefaultedComparisonKind::Equal &&
8082              "should have non-expression statement");
8083       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8084       if (Substmt.isInvalid())
8085         return StmtError();
8086     }
8087 
8088     // Build 'for (...) ...'
8089     return S.ActOnForStmt(Loc, Loc, Init,
8090                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8091                                            Sema::ConditionKind::Boolean),
8092                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8093                           Substmt.get());
8094   }
8095 
8096   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8097     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8098       return StmtError();
8099 
8100     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8101     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8102     ExprResult Op;
8103     if (Type->isOverloadableType())
8104       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8105                                    Obj.second.get(), /*PerformADL=*/true,
8106                                    /*AllowRewrittenCandidates=*/true, FD);
8107     else
8108       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8109     if (Op.isInvalid())
8110       return StmtError();
8111 
8112     switch (DCK) {
8113     case DefaultedComparisonKind::None:
8114       llvm_unreachable("not a defaulted comparison");
8115 
8116     case DefaultedComparisonKind::Equal:
8117       // Per C++2a [class.eq]p2, each comparison is individually contextually
8118       // converted to bool.
8119       Op = S.PerformContextuallyConvertToBool(Op.get());
8120       if (Op.isInvalid())
8121         return StmtError();
8122       return Op.get();
8123 
8124     case DefaultedComparisonKind::ThreeWay: {
8125       // Per C++2a [class.spaceship]p3, form:
8126       //   if (R cmp = static_cast<R>(op); cmp != 0)
8127       //     return cmp;
8128       QualType R = FD->getReturnType();
8129       Op = buildStaticCastToR(Op.get());
8130       if (Op.isInvalid())
8131         return StmtError();
8132 
8133       // R cmp = ...;
8134       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8135       VarDecl *VD =
8136           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8137                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8138       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8139       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8140 
8141       // cmp != 0
8142       ExprResult VDRef = getDecl(VD);
8143       if (VDRef.isInvalid())
8144         return StmtError();
8145       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8146       Expr *Zero =
8147           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8148       ExprResult Comp;
8149       if (VDRef.get()->getType()->isOverloadableType())
8150         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8151                                        true, FD);
8152       else
8153         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8154       if (Comp.isInvalid())
8155         return StmtError();
8156       Sema::ConditionResult Cond = S.ActOnCondition(
8157           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8158       if (Cond.isInvalid())
8159         return StmtError();
8160 
8161       // return cmp;
8162       VDRef = getDecl(VD);
8163       if (VDRef.isInvalid())
8164         return StmtError();
8165       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8166       if (ReturnStmt.isInvalid())
8167         return StmtError();
8168 
8169       // if (...)
8170       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond,
8171                            ReturnStmt.get(), /*ElseLoc=*/SourceLocation(),
8172                            /*Else=*/nullptr);
8173     }
8174 
8175     case DefaultedComparisonKind::NotEqual:
8176     case DefaultedComparisonKind::Relational:
8177       // C++2a [class.compare.secondary]p2:
8178       //   Otherwise, the operator function yields x @ y.
8179       return Op.get();
8180     }
8181     llvm_unreachable("");
8182   }
8183 
8184   /// Build "static_cast<R>(E)".
8185   ExprResult buildStaticCastToR(Expr *E) {
8186     QualType R = FD->getReturnType();
8187     assert(!R->isUndeducedType() && "type should have been deduced already");
8188 
8189     // Don't bother forming a no-op cast in the common case.
8190     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8191       return E;
8192     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8193                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8194                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8195   }
8196 };
8197 }
8198 
8199 /// Perform the unqualified lookups that might be needed to form a defaulted
8200 /// comparison function for the given operator.
8201 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8202                                                   UnresolvedSetImpl &Operators,
8203                                                   OverloadedOperatorKind Op) {
8204   auto Lookup = [&](OverloadedOperatorKind OO) {
8205     Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators);
8206   };
8207 
8208   // Every defaulted operator looks up itself.
8209   Lookup(Op);
8210   // ... and the rewritten form of itself, if any.
8211   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8212     Lookup(ExtraOp);
8213 
8214   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8215   // synthesize a three-way comparison from '<' and '=='. In a dependent
8216   // context, we also need to look up '==' in case we implicitly declare a
8217   // defaulted 'operator=='.
8218   if (Op == OO_Spaceship) {
8219     Lookup(OO_ExclaimEqual);
8220     Lookup(OO_Less);
8221     Lookup(OO_EqualEqual);
8222   }
8223 }
8224 
8225 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8226                                               DefaultedComparisonKind DCK) {
8227   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8228 
8229   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8230   assert(RD && "defaulted comparison is not defaulted in a class");
8231 
8232   // Perform any unqualified lookups we're going to need to default this
8233   // function.
8234   if (S) {
8235     UnresolvedSet<32> Operators;
8236     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8237                                           FD->getOverloadedOperator());
8238     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8239         Context, Operators.pairs()));
8240   }
8241 
8242   // C++2a [class.compare.default]p1:
8243   //   A defaulted comparison operator function for some class C shall be a
8244   //   non-template function declared in the member-specification of C that is
8245   //    -- a non-static const member of C having one parameter of type
8246   //       const C&, or
8247   //    -- a friend of C having two parameters of type const C& or two
8248   //       parameters of type C.
8249   QualType ExpectedParmType1 = Context.getRecordType(RD);
8250   QualType ExpectedParmType2 =
8251       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8252   if (isa<CXXMethodDecl>(FD))
8253     ExpectedParmType1 = ExpectedParmType2;
8254   for (const ParmVarDecl *Param : FD->parameters()) {
8255     if (!Param->getType()->isDependentType() &&
8256         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8257         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8258       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8259       // corresponding defaulted 'operator<=>' already.
8260       if (!FD->isImplicit()) {
8261         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8262             << (int)DCK << Param->getType() << ExpectedParmType1
8263             << !isa<CXXMethodDecl>(FD)
8264             << ExpectedParmType2 << Param->getSourceRange();
8265       }
8266       return true;
8267     }
8268   }
8269   if (FD->getNumParams() == 2 &&
8270       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8271                            FD->getParamDecl(1)->getType())) {
8272     if (!FD->isImplicit()) {
8273       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8274           << (int)DCK
8275           << FD->getParamDecl(0)->getType()
8276           << FD->getParamDecl(0)->getSourceRange()
8277           << FD->getParamDecl(1)->getType()
8278           << FD->getParamDecl(1)->getSourceRange();
8279     }
8280     return true;
8281   }
8282 
8283   // ... non-static const member ...
8284   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8285     assert(!MD->isStatic() && "comparison function cannot be a static member");
8286     if (!MD->isConst()) {
8287       SourceLocation InsertLoc;
8288       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8289         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8290       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8291       // corresponding defaulted 'operator<=>' already.
8292       if (!MD->isImplicit()) {
8293         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8294           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8295       }
8296 
8297       // Add the 'const' to the type to recover.
8298       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8299       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8300       EPI.TypeQuals.addConst();
8301       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8302                                           FPT->getParamTypes(), EPI));
8303     }
8304   } else {
8305     // A non-member function declared in a class must be a friend.
8306     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8307   }
8308 
8309   // C++2a [class.eq]p1, [class.rel]p1:
8310   //   A [defaulted comparison other than <=>] shall have a declared return
8311   //   type bool.
8312   if (DCK != DefaultedComparisonKind::ThreeWay &&
8313       !FD->getDeclaredReturnType()->isDependentType() &&
8314       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8315     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8316         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8317         << FD->getReturnTypeSourceRange();
8318     return true;
8319   }
8320   // C++2a [class.spaceship]p2 [P2002R0]:
8321   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8322   //   R shall not contain a placeholder type.
8323   if (DCK == DefaultedComparisonKind::ThreeWay &&
8324       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8325       !Context.hasSameType(FD->getDeclaredReturnType(),
8326                            Context.getAutoDeductType())) {
8327     Diag(FD->getLocation(),
8328          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8329         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8330         << FD->getReturnTypeSourceRange();
8331     return true;
8332   }
8333 
8334   // For a defaulted function in a dependent class, defer all remaining checks
8335   // until instantiation.
8336   if (RD->isDependentType())
8337     return false;
8338 
8339   // Determine whether the function should be defined as deleted.
8340   DefaultedComparisonInfo Info =
8341       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8342 
8343   bool First = FD == FD->getCanonicalDecl();
8344 
8345   // If we want to delete the function, then do so; there's nothing else to
8346   // check in that case.
8347   if (Info.Deleted) {
8348     if (!First) {
8349       // C++11 [dcl.fct.def.default]p4:
8350       //   [For a] user-provided explicitly-defaulted function [...] if such a
8351       //   function is implicitly defined as deleted, the program is ill-formed.
8352       //
8353       // This is really just a consequence of the general rule that you can
8354       // only delete a function on its first declaration.
8355       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8356           << FD->isImplicit() << (int)DCK;
8357       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8358                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8359           .visit();
8360       return true;
8361     }
8362 
8363     SetDeclDeleted(FD, FD->getLocation());
8364     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8365       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8366           << (int)DCK;
8367       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8368                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8369           .visit();
8370     }
8371     return false;
8372   }
8373 
8374   // C++2a [class.spaceship]p2:
8375   //   The return type is deduced as the common comparison type of R0, R1, ...
8376   if (DCK == DefaultedComparisonKind::ThreeWay &&
8377       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8378     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8379     if (RetLoc.isInvalid())
8380       RetLoc = FD->getBeginLoc();
8381     // FIXME: Should we really care whether we have the complete type and the
8382     // 'enumerator' constants here? A forward declaration seems sufficient.
8383     QualType Cat = CheckComparisonCategoryType(
8384         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8385     if (Cat.isNull())
8386       return true;
8387     Context.adjustDeducedFunctionResultType(
8388         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8389   }
8390 
8391   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8392   //   An explicitly-defaulted function that is not defined as deleted may be
8393   //   declared constexpr or consteval only if it is constexpr-compatible.
8394   // C++2a [class.compare.default]p3 [P2002R0]:
8395   //   A defaulted comparison function is constexpr-compatible if it satisfies
8396   //   the requirements for a constexpr function [...]
8397   // The only relevant requirements are that the parameter and return types are
8398   // literal types. The remaining conditions are checked by the analyzer.
8399   if (FD->isConstexpr()) {
8400     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8401         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8402         !Info.Constexpr) {
8403       Diag(FD->getBeginLoc(),
8404            diag::err_incorrect_defaulted_comparison_constexpr)
8405           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8406       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8407                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8408           .visit();
8409     }
8410   }
8411 
8412   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8413   //   If a constexpr-compatible function is explicitly defaulted on its first
8414   //   declaration, it is implicitly considered to be constexpr.
8415   // FIXME: Only applying this to the first declaration seems problematic, as
8416   // simple reorderings can affect the meaning of the program.
8417   if (First && !FD->isConstexpr() && Info.Constexpr)
8418     FD->setConstexprKind(CSK_constexpr);
8419 
8420   // C++2a [except.spec]p3:
8421   //   If a declaration of a function does not have a noexcept-specifier
8422   //   [and] is defaulted on its first declaration, [...] the exception
8423   //   specification is as specified below
8424   if (FD->getExceptionSpecType() == EST_None) {
8425     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8426     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8427     EPI.ExceptionSpec.Type = EST_Unevaluated;
8428     EPI.ExceptionSpec.SourceDecl = FD;
8429     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8430                                         FPT->getParamTypes(), EPI));
8431   }
8432 
8433   return false;
8434 }
8435 
8436 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8437                                              FunctionDecl *Spaceship) {
8438   Sema::CodeSynthesisContext Ctx;
8439   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8440   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8441   Ctx.Entity = Spaceship;
8442   pushCodeSynthesisContext(Ctx);
8443 
8444   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8445     EqualEqual->setImplicit();
8446 
8447   popCodeSynthesisContext();
8448 }
8449 
8450 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8451                                      DefaultedComparisonKind DCK) {
8452   assert(FD->isDefaulted() && !FD->isDeleted() &&
8453          !FD->doesThisDeclarationHaveABody());
8454   if (FD->willHaveBody() || FD->isInvalidDecl())
8455     return;
8456 
8457   SynthesizedFunctionScope Scope(*this, FD);
8458 
8459   // Add a context note for diagnostics produced after this point.
8460   Scope.addContextNote(UseLoc);
8461 
8462   {
8463     // Build and set up the function body.
8464     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8465     SourceLocation BodyLoc =
8466         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8467     StmtResult Body =
8468         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8469     if (Body.isInvalid()) {
8470       FD->setInvalidDecl();
8471       return;
8472     }
8473     FD->setBody(Body.get());
8474     FD->markUsed(Context);
8475   }
8476 
8477   // The exception specification is needed because we are defining the
8478   // function. Note that this will reuse the body we just built.
8479   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8480 
8481   if (ASTMutationListener *L = getASTMutationListener())
8482     L->CompletedImplicitDefinition(FD);
8483 }
8484 
8485 static Sema::ImplicitExceptionSpecification
8486 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8487                                         FunctionDecl *FD,
8488                                         Sema::DefaultedComparisonKind DCK) {
8489   ComputingExceptionSpec CES(S, FD, Loc);
8490   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8491 
8492   if (FD->isInvalidDecl())
8493     return ExceptSpec;
8494 
8495   // The common case is that we just defined the comparison function. In that
8496   // case, just look at whether the body can throw.
8497   if (FD->hasBody()) {
8498     ExceptSpec.CalledStmt(FD->getBody());
8499   } else {
8500     // Otherwise, build a body so we can check it. This should ideally only
8501     // happen when we're not actually marking the function referenced. (This is
8502     // only really important for efficiency: we don't want to build and throw
8503     // away bodies for comparison functions more than we strictly need to.)
8504 
8505     // Pretend to synthesize the function body in an unevaluated context.
8506     // Note that we can't actually just go ahead and define the function here:
8507     // we are not permitted to mark its callees as referenced.
8508     Sema::SynthesizedFunctionScope Scope(S, FD);
8509     EnterExpressionEvaluationContext Context(
8510         S, Sema::ExpressionEvaluationContext::Unevaluated);
8511 
8512     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8513     SourceLocation BodyLoc =
8514         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8515     StmtResult Body =
8516         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8517     if (!Body.isInvalid())
8518       ExceptSpec.CalledStmt(Body.get());
8519 
8520     // FIXME: Can we hold onto this body and just transform it to potentially
8521     // evaluated when we're asked to define the function rather than rebuilding
8522     // it? Either that, or we should only build the bits of the body that we
8523     // need (the expressions, not the statements).
8524   }
8525 
8526   return ExceptSpec;
8527 }
8528 
8529 void Sema::CheckDelayedMemberExceptionSpecs() {
8530   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8531   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8532 
8533   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8534   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8535 
8536   // Perform any deferred checking of exception specifications for virtual
8537   // destructors.
8538   for (auto &Check : Overriding)
8539     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8540 
8541   // Perform any deferred checking of exception specifications for befriended
8542   // special members.
8543   for (auto &Check : Equivalent)
8544     CheckEquivalentExceptionSpec(Check.second, Check.first);
8545 }
8546 
8547 namespace {
8548 /// CRTP base class for visiting operations performed by a special member
8549 /// function (or inherited constructor).
8550 template<typename Derived>
8551 struct SpecialMemberVisitor {
8552   Sema &S;
8553   CXXMethodDecl *MD;
8554   Sema::CXXSpecialMember CSM;
8555   Sema::InheritedConstructorInfo *ICI;
8556 
8557   // Properties of the special member, computed for convenience.
8558   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8559 
8560   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8561                        Sema::InheritedConstructorInfo *ICI)
8562       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8563     switch (CSM) {
8564     case Sema::CXXDefaultConstructor:
8565     case Sema::CXXCopyConstructor:
8566     case Sema::CXXMoveConstructor:
8567       IsConstructor = true;
8568       break;
8569     case Sema::CXXCopyAssignment:
8570     case Sema::CXXMoveAssignment:
8571       IsAssignment = true;
8572       break;
8573     case Sema::CXXDestructor:
8574       break;
8575     case Sema::CXXInvalid:
8576       llvm_unreachable("invalid special member kind");
8577     }
8578 
8579     if (MD->getNumParams()) {
8580       if (const ReferenceType *RT =
8581               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8582         ConstArg = RT->getPointeeType().isConstQualified();
8583     }
8584   }
8585 
8586   Derived &getDerived() { return static_cast<Derived&>(*this); }
8587 
8588   /// Is this a "move" special member?
8589   bool isMove() const {
8590     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8591   }
8592 
8593   /// Look up the corresponding special member in the given class.
8594   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8595                                              unsigned Quals, bool IsMutable) {
8596     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8597                                        ConstArg && !IsMutable);
8598   }
8599 
8600   /// Look up the constructor for the specified base class to see if it's
8601   /// overridden due to this being an inherited constructor.
8602   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8603     if (!ICI)
8604       return {};
8605     assert(CSM == Sema::CXXDefaultConstructor);
8606     auto *BaseCtor =
8607       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8608     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8609       return MD;
8610     return {};
8611   }
8612 
8613   /// A base or member subobject.
8614   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8615 
8616   /// Get the location to use for a subobject in diagnostics.
8617   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8618     // FIXME: For an indirect virtual base, the direct base leading to
8619     // the indirect virtual base would be a more useful choice.
8620     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8621       return B->getBaseTypeLoc();
8622     else
8623       return Subobj.get<FieldDecl*>()->getLocation();
8624   }
8625 
8626   enum BasesToVisit {
8627     /// Visit all non-virtual (direct) bases.
8628     VisitNonVirtualBases,
8629     /// Visit all direct bases, virtual or not.
8630     VisitDirectBases,
8631     /// Visit all non-virtual bases, and all virtual bases if the class
8632     /// is not abstract.
8633     VisitPotentiallyConstructedBases,
8634     /// Visit all direct or virtual bases.
8635     VisitAllBases
8636   };
8637 
8638   // Visit the bases and members of the class.
8639   bool visit(BasesToVisit Bases) {
8640     CXXRecordDecl *RD = MD->getParent();
8641 
8642     if (Bases == VisitPotentiallyConstructedBases)
8643       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8644 
8645     for (auto &B : RD->bases())
8646       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8647           getDerived().visitBase(&B))
8648         return true;
8649 
8650     if (Bases == VisitAllBases)
8651       for (auto &B : RD->vbases())
8652         if (getDerived().visitBase(&B))
8653           return true;
8654 
8655     for (auto *F : RD->fields())
8656       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8657           getDerived().visitField(F))
8658         return true;
8659 
8660     return false;
8661   }
8662 };
8663 }
8664 
8665 namespace {
8666 struct SpecialMemberDeletionInfo
8667     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8668   bool Diagnose;
8669 
8670   SourceLocation Loc;
8671 
8672   bool AllFieldsAreConst;
8673 
8674   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8675                             Sema::CXXSpecialMember CSM,
8676                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8677       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8678         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8679 
8680   bool inUnion() const { return MD->getParent()->isUnion(); }
8681 
8682   Sema::CXXSpecialMember getEffectiveCSM() {
8683     return ICI ? Sema::CXXInvalid : CSM;
8684   }
8685 
8686   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8687 
8688   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8689   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8690 
8691   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8692   bool shouldDeleteForField(FieldDecl *FD);
8693   bool shouldDeleteForAllConstMembers();
8694 
8695   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8696                                      unsigned Quals);
8697   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8698                                     Sema::SpecialMemberOverloadResult SMOR,
8699                                     bool IsDtorCallInCtor);
8700 
8701   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8702 };
8703 }
8704 
8705 /// Is the given special member inaccessible when used on the given
8706 /// sub-object.
8707 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8708                                              CXXMethodDecl *target) {
8709   /// If we're operating on a base class, the object type is the
8710   /// type of this special member.
8711   QualType objectTy;
8712   AccessSpecifier access = target->getAccess();
8713   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8714     objectTy = S.Context.getTypeDeclType(MD->getParent());
8715     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8716 
8717   // If we're operating on a field, the object type is the type of the field.
8718   } else {
8719     objectTy = S.Context.getTypeDeclType(target->getParent());
8720   }
8721 
8722   return S.isMemberAccessibleForDeletion(
8723       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8724 }
8725 
8726 /// Check whether we should delete a special member due to the implicit
8727 /// definition containing a call to a special member of a subobject.
8728 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8729     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8730     bool IsDtorCallInCtor) {
8731   CXXMethodDecl *Decl = SMOR.getMethod();
8732   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8733 
8734   int DiagKind = -1;
8735 
8736   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8737     DiagKind = !Decl ? 0 : 1;
8738   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8739     DiagKind = 2;
8740   else if (!isAccessible(Subobj, Decl))
8741     DiagKind = 3;
8742   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8743            !Decl->isTrivial()) {
8744     // A member of a union must have a trivial corresponding special member.
8745     // As a weird special case, a destructor call from a union's constructor
8746     // must be accessible and non-deleted, but need not be trivial. Such a
8747     // destructor is never actually called, but is semantically checked as
8748     // if it were.
8749     DiagKind = 4;
8750   }
8751 
8752   if (DiagKind == -1)
8753     return false;
8754 
8755   if (Diagnose) {
8756     if (Field) {
8757       S.Diag(Field->getLocation(),
8758              diag::note_deleted_special_member_class_subobject)
8759         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8760         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8761     } else {
8762       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8763       S.Diag(Base->getBeginLoc(),
8764              diag::note_deleted_special_member_class_subobject)
8765           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8766           << Base->getType() << DiagKind << IsDtorCallInCtor
8767           << /*IsObjCPtr*/false;
8768     }
8769 
8770     if (DiagKind == 1)
8771       S.NoteDeletedFunction(Decl);
8772     // FIXME: Explain inaccessibility if DiagKind == 3.
8773   }
8774 
8775   return true;
8776 }
8777 
8778 /// Check whether we should delete a special member function due to having a
8779 /// direct or virtual base class or non-static data member of class type M.
8780 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8781     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8782   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8783   bool IsMutable = Field && Field->isMutable();
8784 
8785   // C++11 [class.ctor]p5:
8786   // -- any direct or virtual base class, or non-static data member with no
8787   //    brace-or-equal-initializer, has class type M (or array thereof) and
8788   //    either M has no default constructor or overload resolution as applied
8789   //    to M's default constructor results in an ambiguity or in a function
8790   //    that is deleted or inaccessible
8791   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8792   // -- a direct or virtual base class B that cannot be copied/moved because
8793   //    overload resolution, as applied to B's corresponding special member,
8794   //    results in an ambiguity or a function that is deleted or inaccessible
8795   //    from the defaulted special member
8796   // C++11 [class.dtor]p5:
8797   // -- any direct or virtual base class [...] has a type with a destructor
8798   //    that is deleted or inaccessible
8799   if (!(CSM == Sema::CXXDefaultConstructor &&
8800         Field && Field->hasInClassInitializer()) &&
8801       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8802                                    false))
8803     return true;
8804 
8805   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8806   // -- any direct or virtual base class or non-static data member has a
8807   //    type with a destructor that is deleted or inaccessible
8808   if (IsConstructor) {
8809     Sema::SpecialMemberOverloadResult SMOR =
8810         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8811                               false, false, false, false, false);
8812     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8813       return true;
8814   }
8815 
8816   return false;
8817 }
8818 
8819 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8820     FieldDecl *FD, QualType FieldType) {
8821   // The defaulted special functions are defined as deleted if this is a variant
8822   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8823   // type under ARC.
8824   if (!FieldType.hasNonTrivialObjCLifetime())
8825     return false;
8826 
8827   // Don't make the defaulted default constructor defined as deleted if the
8828   // member has an in-class initializer.
8829   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8830     return false;
8831 
8832   if (Diagnose) {
8833     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8834     S.Diag(FD->getLocation(),
8835            diag::note_deleted_special_member_class_subobject)
8836         << getEffectiveCSM() << ParentClass << /*IsField*/true
8837         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8838   }
8839 
8840   return true;
8841 }
8842 
8843 /// Check whether we should delete a special member function due to the class
8844 /// having a particular direct or virtual base class.
8845 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8846   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8847   // If program is correct, BaseClass cannot be null, but if it is, the error
8848   // must be reported elsewhere.
8849   if (!BaseClass)
8850     return false;
8851   // If we have an inheriting constructor, check whether we're calling an
8852   // inherited constructor instead of a default constructor.
8853   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8854   if (auto *BaseCtor = SMOR.getMethod()) {
8855     // Note that we do not check access along this path; other than that,
8856     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8857     // FIXME: Check that the base has a usable destructor! Sink this into
8858     // shouldDeleteForClassSubobject.
8859     if (BaseCtor->isDeleted() && Diagnose) {
8860       S.Diag(Base->getBeginLoc(),
8861              diag::note_deleted_special_member_class_subobject)
8862           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8863           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8864           << /*IsObjCPtr*/false;
8865       S.NoteDeletedFunction(BaseCtor);
8866     }
8867     return BaseCtor->isDeleted();
8868   }
8869   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8870 }
8871 
8872 /// Check whether we should delete a special member function due to the class
8873 /// having a particular non-static data member.
8874 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8875   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8876   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8877 
8878   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8879     return true;
8880 
8881   if (CSM == Sema::CXXDefaultConstructor) {
8882     // For a default constructor, all references must be initialized in-class
8883     // and, if a union, it must have a non-const member.
8884     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8885       if (Diagnose)
8886         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8887           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8888       return true;
8889     }
8890     // C++11 [class.ctor]p5: any non-variant non-static data member of
8891     // const-qualified type (or array thereof) with no
8892     // brace-or-equal-initializer does not have a user-provided default
8893     // constructor.
8894     if (!inUnion() && FieldType.isConstQualified() &&
8895         !FD->hasInClassInitializer() &&
8896         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8897       if (Diagnose)
8898         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8899           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8900       return true;
8901     }
8902 
8903     if (inUnion() && !FieldType.isConstQualified())
8904       AllFieldsAreConst = false;
8905   } else if (CSM == Sema::CXXCopyConstructor) {
8906     // For a copy constructor, data members must not be of rvalue reference
8907     // type.
8908     if (FieldType->isRValueReferenceType()) {
8909       if (Diagnose)
8910         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8911           << MD->getParent() << FD << FieldType;
8912       return true;
8913     }
8914   } else if (IsAssignment) {
8915     // For an assignment operator, data members must not be of reference type.
8916     if (FieldType->isReferenceType()) {
8917       if (Diagnose)
8918         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8919           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8920       return true;
8921     }
8922     if (!FieldRecord && FieldType.isConstQualified()) {
8923       // C++11 [class.copy]p23:
8924       // -- a non-static data member of const non-class type (or array thereof)
8925       if (Diagnose)
8926         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8927           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8928       return true;
8929     }
8930   }
8931 
8932   if (FieldRecord) {
8933     // Some additional restrictions exist on the variant members.
8934     if (!inUnion() && FieldRecord->isUnion() &&
8935         FieldRecord->isAnonymousStructOrUnion()) {
8936       bool AllVariantFieldsAreConst = true;
8937 
8938       // FIXME: Handle anonymous unions declared within anonymous unions.
8939       for (auto *UI : FieldRecord->fields()) {
8940         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8941 
8942         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8943           return true;
8944 
8945         if (!UnionFieldType.isConstQualified())
8946           AllVariantFieldsAreConst = false;
8947 
8948         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8949         if (UnionFieldRecord &&
8950             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8951                                           UnionFieldType.getCVRQualifiers()))
8952           return true;
8953       }
8954 
8955       // At least one member in each anonymous union must be non-const
8956       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8957           !FieldRecord->field_empty()) {
8958         if (Diagnose)
8959           S.Diag(FieldRecord->getLocation(),
8960                  diag::note_deleted_default_ctor_all_const)
8961             << !!ICI << MD->getParent() << /*anonymous union*/1;
8962         return true;
8963       }
8964 
8965       // Don't check the implicit member of the anonymous union type.
8966       // This is technically non-conformant, but sanity demands it.
8967       return false;
8968     }
8969 
8970     if (shouldDeleteForClassSubobject(FieldRecord, FD,
8971                                       FieldType.getCVRQualifiers()))
8972       return true;
8973   }
8974 
8975   return false;
8976 }
8977 
8978 /// C++11 [class.ctor] p5:
8979 ///   A defaulted default constructor for a class X is defined as deleted if
8980 /// X is a union and all of its variant members are of const-qualified type.
8981 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8982   // This is a silly definition, because it gives an empty union a deleted
8983   // default constructor. Don't do that.
8984   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
8985     bool AnyFields = false;
8986     for (auto *F : MD->getParent()->fields())
8987       if ((AnyFields = !F->isUnnamedBitfield()))
8988         break;
8989     if (!AnyFields)
8990       return false;
8991     if (Diagnose)
8992       S.Diag(MD->getParent()->getLocation(),
8993              diag::note_deleted_default_ctor_all_const)
8994         << !!ICI << MD->getParent() << /*not anonymous union*/0;
8995     return true;
8996   }
8997   return false;
8998 }
8999 
9000 /// Determine whether a defaulted special member function should be defined as
9001 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9002 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9003 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9004                                      InheritedConstructorInfo *ICI,
9005                                      bool Diagnose) {
9006   if (MD->isInvalidDecl())
9007     return false;
9008   CXXRecordDecl *RD = MD->getParent();
9009   assert(!RD->isDependentType() && "do deletion after instantiation");
9010   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9011     return false;
9012 
9013   // C++11 [expr.lambda.prim]p19:
9014   //   The closure type associated with a lambda-expression has a
9015   //   deleted (8.4.3) default constructor and a deleted copy
9016   //   assignment operator.
9017   // C++2a adds back these operators if the lambda has no lambda-capture.
9018   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9019       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9020     if (Diagnose)
9021       Diag(RD->getLocation(), diag::note_lambda_decl);
9022     return true;
9023   }
9024 
9025   // For an anonymous struct or union, the copy and assignment special members
9026   // will never be used, so skip the check. For an anonymous union declared at
9027   // namespace scope, the constructor and destructor are used.
9028   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9029       RD->isAnonymousStructOrUnion())
9030     return false;
9031 
9032   // C++11 [class.copy]p7, p18:
9033   //   If the class definition declares a move constructor or move assignment
9034   //   operator, an implicitly declared copy constructor or copy assignment
9035   //   operator is defined as deleted.
9036   if (MD->isImplicit() &&
9037       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9038     CXXMethodDecl *UserDeclaredMove = nullptr;
9039 
9040     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9041     // deletion of the corresponding copy operation, not both copy operations.
9042     // MSVC 2015 has adopted the standards conforming behavior.
9043     bool DeletesOnlyMatchingCopy =
9044         getLangOpts().MSVCCompat &&
9045         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9046 
9047     if (RD->hasUserDeclaredMoveConstructor() &&
9048         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9049       if (!Diagnose) return true;
9050 
9051       // Find any user-declared move constructor.
9052       for (auto *I : RD->ctors()) {
9053         if (I->isMoveConstructor()) {
9054           UserDeclaredMove = I;
9055           break;
9056         }
9057       }
9058       assert(UserDeclaredMove);
9059     } else if (RD->hasUserDeclaredMoveAssignment() &&
9060                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9061       if (!Diagnose) return true;
9062 
9063       // Find any user-declared move assignment operator.
9064       for (auto *I : RD->methods()) {
9065         if (I->isMoveAssignmentOperator()) {
9066           UserDeclaredMove = I;
9067           break;
9068         }
9069       }
9070       assert(UserDeclaredMove);
9071     }
9072 
9073     if (UserDeclaredMove) {
9074       Diag(UserDeclaredMove->getLocation(),
9075            diag::note_deleted_copy_user_declared_move)
9076         << (CSM == CXXCopyAssignment) << RD
9077         << UserDeclaredMove->isMoveAssignmentOperator();
9078       return true;
9079     }
9080   }
9081 
9082   // Do access control from the special member function
9083   ContextRAII MethodContext(*this, MD);
9084 
9085   // C++11 [class.dtor]p5:
9086   // -- for a virtual destructor, lookup of the non-array deallocation function
9087   //    results in an ambiguity or in a function that is deleted or inaccessible
9088   if (CSM == CXXDestructor && MD->isVirtual()) {
9089     FunctionDecl *OperatorDelete = nullptr;
9090     DeclarationName Name =
9091       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9092     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9093                                  OperatorDelete, /*Diagnose*/false)) {
9094       if (Diagnose)
9095         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9096       return true;
9097     }
9098   }
9099 
9100   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9101 
9102   // Per DR1611, do not consider virtual bases of constructors of abstract
9103   // classes, since we are not going to construct them.
9104   // Per DR1658, do not consider virtual bases of destructors of abstract
9105   // classes either.
9106   // Per DR2180, for assignment operators we only assign (and thus only
9107   // consider) direct bases.
9108   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9109                                  : SMI.VisitPotentiallyConstructedBases))
9110     return true;
9111 
9112   if (SMI.shouldDeleteForAllConstMembers())
9113     return true;
9114 
9115   if (getLangOpts().CUDA) {
9116     // We should delete the special member in CUDA mode if target inference
9117     // failed.
9118     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9119     // is treated as certain special member, which may not reflect what special
9120     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9121     // expects CSM to match MD, therefore recalculate CSM.
9122     assert(ICI || CSM == getSpecialMember(MD));
9123     auto RealCSM = CSM;
9124     if (ICI)
9125       RealCSM = getSpecialMember(MD);
9126 
9127     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9128                                                    SMI.ConstArg, Diagnose);
9129   }
9130 
9131   return false;
9132 }
9133 
9134 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9135   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9136   assert(DFK && "not a defaultable function");
9137   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9138 
9139   if (DFK.isSpecialMember()) {
9140     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9141                               nullptr, /*Diagnose=*/true);
9142   } else {
9143     DefaultedComparisonAnalyzer(
9144         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9145         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9146         .visit();
9147   }
9148 }
9149 
9150 /// Perform lookup for a special member of the specified kind, and determine
9151 /// whether it is trivial. If the triviality can be determined without the
9152 /// lookup, skip it. This is intended for use when determining whether a
9153 /// special member of a containing object is trivial, and thus does not ever
9154 /// perform overload resolution for default constructors.
9155 ///
9156 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9157 /// member that was most likely to be intended to be trivial, if any.
9158 ///
9159 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9160 /// determine whether the special member is trivial.
9161 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9162                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9163                                      bool ConstRHS,
9164                                      Sema::TrivialABIHandling TAH,
9165                                      CXXMethodDecl **Selected) {
9166   if (Selected)
9167     *Selected = nullptr;
9168 
9169   switch (CSM) {
9170   case Sema::CXXInvalid:
9171     llvm_unreachable("not a special member");
9172 
9173   case Sema::CXXDefaultConstructor:
9174     // C++11 [class.ctor]p5:
9175     //   A default constructor is trivial if:
9176     //    - all the [direct subobjects] have trivial default constructors
9177     //
9178     // Note, no overload resolution is performed in this case.
9179     if (RD->hasTrivialDefaultConstructor())
9180       return true;
9181 
9182     if (Selected) {
9183       // If there's a default constructor which could have been trivial, dig it
9184       // out. Otherwise, if there's any user-provided default constructor, point
9185       // to that as an example of why there's not a trivial one.
9186       CXXConstructorDecl *DefCtor = nullptr;
9187       if (RD->needsImplicitDefaultConstructor())
9188         S.DeclareImplicitDefaultConstructor(RD);
9189       for (auto *CI : RD->ctors()) {
9190         if (!CI->isDefaultConstructor())
9191           continue;
9192         DefCtor = CI;
9193         if (!DefCtor->isUserProvided())
9194           break;
9195       }
9196 
9197       *Selected = DefCtor;
9198     }
9199 
9200     return false;
9201 
9202   case Sema::CXXDestructor:
9203     // C++11 [class.dtor]p5:
9204     //   A destructor is trivial if:
9205     //    - all the direct [subobjects] have trivial destructors
9206     if (RD->hasTrivialDestructor() ||
9207         (TAH == Sema::TAH_ConsiderTrivialABI &&
9208          RD->hasTrivialDestructorForCall()))
9209       return true;
9210 
9211     if (Selected) {
9212       if (RD->needsImplicitDestructor())
9213         S.DeclareImplicitDestructor(RD);
9214       *Selected = RD->getDestructor();
9215     }
9216 
9217     return false;
9218 
9219   case Sema::CXXCopyConstructor:
9220     // C++11 [class.copy]p12:
9221     //   A copy constructor is trivial if:
9222     //    - the constructor selected to copy each direct [subobject] is trivial
9223     if (RD->hasTrivialCopyConstructor() ||
9224         (TAH == Sema::TAH_ConsiderTrivialABI &&
9225          RD->hasTrivialCopyConstructorForCall())) {
9226       if (Quals == Qualifiers::Const)
9227         // We must either select the trivial copy constructor or reach an
9228         // ambiguity; no need to actually perform overload resolution.
9229         return true;
9230     } else if (!Selected) {
9231       return false;
9232     }
9233     // In C++98, we are not supposed to perform overload resolution here, but we
9234     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9235     // cases like B as having a non-trivial copy constructor:
9236     //   struct A { template<typename T> A(T&); };
9237     //   struct B { mutable A a; };
9238     goto NeedOverloadResolution;
9239 
9240   case Sema::CXXCopyAssignment:
9241     // C++11 [class.copy]p25:
9242     //   A copy assignment operator is trivial if:
9243     //    - the assignment operator selected to copy each direct [subobject] is
9244     //      trivial
9245     if (RD->hasTrivialCopyAssignment()) {
9246       if (Quals == Qualifiers::Const)
9247         return true;
9248     } else if (!Selected) {
9249       return false;
9250     }
9251     // In C++98, we are not supposed to perform overload resolution here, but we
9252     // treat that as a language defect.
9253     goto NeedOverloadResolution;
9254 
9255   case Sema::CXXMoveConstructor:
9256   case Sema::CXXMoveAssignment:
9257   NeedOverloadResolution:
9258     Sema::SpecialMemberOverloadResult SMOR =
9259         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9260 
9261     // The standard doesn't describe how to behave if the lookup is ambiguous.
9262     // We treat it as not making the member non-trivial, just like the standard
9263     // mandates for the default constructor. This should rarely matter, because
9264     // the member will also be deleted.
9265     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9266       return true;
9267 
9268     if (!SMOR.getMethod()) {
9269       assert(SMOR.getKind() ==
9270              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9271       return false;
9272     }
9273 
9274     // We deliberately don't check if we found a deleted special member. We're
9275     // not supposed to!
9276     if (Selected)
9277       *Selected = SMOR.getMethod();
9278 
9279     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9280         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9281       return SMOR.getMethod()->isTrivialForCall();
9282     return SMOR.getMethod()->isTrivial();
9283   }
9284 
9285   llvm_unreachable("unknown special method kind");
9286 }
9287 
9288 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9289   for (auto *CI : RD->ctors())
9290     if (!CI->isImplicit())
9291       return CI;
9292 
9293   // Look for constructor templates.
9294   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9295   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9296     if (CXXConstructorDecl *CD =
9297           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9298       return CD;
9299   }
9300 
9301   return nullptr;
9302 }
9303 
9304 /// The kind of subobject we are checking for triviality. The values of this
9305 /// enumeration are used in diagnostics.
9306 enum TrivialSubobjectKind {
9307   /// The subobject is a base class.
9308   TSK_BaseClass,
9309   /// The subobject is a non-static data member.
9310   TSK_Field,
9311   /// The object is actually the complete object.
9312   TSK_CompleteObject
9313 };
9314 
9315 /// Check whether the special member selected for a given type would be trivial.
9316 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9317                                       QualType SubType, bool ConstRHS,
9318                                       Sema::CXXSpecialMember CSM,
9319                                       TrivialSubobjectKind Kind,
9320                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9321   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9322   if (!SubRD)
9323     return true;
9324 
9325   CXXMethodDecl *Selected;
9326   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9327                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9328     return true;
9329 
9330   if (Diagnose) {
9331     if (ConstRHS)
9332       SubType.addConst();
9333 
9334     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9335       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9336         << Kind << SubType.getUnqualifiedType();
9337       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9338         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9339     } else if (!Selected)
9340       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9341         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9342     else if (Selected->isUserProvided()) {
9343       if (Kind == TSK_CompleteObject)
9344         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9345           << Kind << SubType.getUnqualifiedType() << CSM;
9346       else {
9347         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9348           << Kind << SubType.getUnqualifiedType() << CSM;
9349         S.Diag(Selected->getLocation(), diag::note_declared_at);
9350       }
9351     } else {
9352       if (Kind != TSK_CompleteObject)
9353         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9354           << Kind << SubType.getUnqualifiedType() << CSM;
9355 
9356       // Explain why the defaulted or deleted special member isn't trivial.
9357       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9358                                Diagnose);
9359     }
9360   }
9361 
9362   return false;
9363 }
9364 
9365 /// Check whether the members of a class type allow a special member to be
9366 /// trivial.
9367 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9368                                      Sema::CXXSpecialMember CSM,
9369                                      bool ConstArg,
9370                                      Sema::TrivialABIHandling TAH,
9371                                      bool Diagnose) {
9372   for (const auto *FI : RD->fields()) {
9373     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9374       continue;
9375 
9376     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9377 
9378     // Pretend anonymous struct or union members are members of this class.
9379     if (FI->isAnonymousStructOrUnion()) {
9380       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9381                                     CSM, ConstArg, TAH, Diagnose))
9382         return false;
9383       continue;
9384     }
9385 
9386     // C++11 [class.ctor]p5:
9387     //   A default constructor is trivial if [...]
9388     //    -- no non-static data member of its class has a
9389     //       brace-or-equal-initializer
9390     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9391       if (Diagnose)
9392         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
9393       return false;
9394     }
9395 
9396     // Objective C ARC 4.3.5:
9397     //   [...] nontrivally ownership-qualified types are [...] not trivially
9398     //   default constructible, copy constructible, move constructible, copy
9399     //   assignable, move assignable, or destructible [...]
9400     if (FieldType.hasNonTrivialObjCLifetime()) {
9401       if (Diagnose)
9402         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9403           << RD << FieldType.getObjCLifetime();
9404       return false;
9405     }
9406 
9407     bool ConstRHS = ConstArg && !FI->isMutable();
9408     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9409                                    CSM, TSK_Field, TAH, Diagnose))
9410       return false;
9411   }
9412 
9413   return true;
9414 }
9415 
9416 /// Diagnose why the specified class does not have a trivial special member of
9417 /// the given kind.
9418 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9419   QualType Ty = Context.getRecordType(RD);
9420 
9421   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9422   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9423                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9424                             /*Diagnose*/true);
9425 }
9426 
9427 /// Determine whether a defaulted or deleted special member function is trivial,
9428 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9429 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9430 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9431                                   TrivialABIHandling TAH, bool Diagnose) {
9432   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9433 
9434   CXXRecordDecl *RD = MD->getParent();
9435 
9436   bool ConstArg = false;
9437 
9438   // C++11 [class.copy]p12, p25: [DR1593]
9439   //   A [special member] is trivial if [...] its parameter-type-list is
9440   //   equivalent to the parameter-type-list of an implicit declaration [...]
9441   switch (CSM) {
9442   case CXXDefaultConstructor:
9443   case CXXDestructor:
9444     // Trivial default constructors and destructors cannot have parameters.
9445     break;
9446 
9447   case CXXCopyConstructor:
9448   case CXXCopyAssignment: {
9449     // Trivial copy operations always have const, non-volatile parameter types.
9450     ConstArg = true;
9451     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9452     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9453     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9454       if (Diagnose)
9455         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9456           << Param0->getSourceRange() << Param0->getType()
9457           << Context.getLValueReferenceType(
9458                Context.getRecordType(RD).withConst());
9459       return false;
9460     }
9461     break;
9462   }
9463 
9464   case CXXMoveConstructor:
9465   case CXXMoveAssignment: {
9466     // Trivial move operations always have non-cv-qualified parameters.
9467     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9468     const RValueReferenceType *RT =
9469       Param0->getType()->getAs<RValueReferenceType>();
9470     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9471       if (Diagnose)
9472         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9473           << Param0->getSourceRange() << Param0->getType()
9474           << Context.getRValueReferenceType(Context.getRecordType(RD));
9475       return false;
9476     }
9477     break;
9478   }
9479 
9480   case CXXInvalid:
9481     llvm_unreachable("not a special member");
9482   }
9483 
9484   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9485     if (Diagnose)
9486       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9487            diag::note_nontrivial_default_arg)
9488         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9489     return false;
9490   }
9491   if (MD->isVariadic()) {
9492     if (Diagnose)
9493       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9494     return false;
9495   }
9496 
9497   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9498   //   A copy/move [constructor or assignment operator] is trivial if
9499   //    -- the [member] selected to copy/move each direct base class subobject
9500   //       is trivial
9501   //
9502   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9503   //   A [default constructor or destructor] is trivial if
9504   //    -- all the direct base classes have trivial [default constructors or
9505   //       destructors]
9506   for (const auto &BI : RD->bases())
9507     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9508                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9509       return false;
9510 
9511   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9512   //   A copy/move [constructor or assignment operator] for a class X is
9513   //   trivial if
9514   //    -- for each non-static data member of X that is of class type (or array
9515   //       thereof), the constructor selected to copy/move that member is
9516   //       trivial
9517   //
9518   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9519   //   A [default constructor or destructor] is trivial if
9520   //    -- for all of the non-static data members of its class that are of class
9521   //       type (or array thereof), each such class has a trivial [default
9522   //       constructor or destructor]
9523   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9524     return false;
9525 
9526   // C++11 [class.dtor]p5:
9527   //   A destructor is trivial if [...]
9528   //    -- the destructor is not virtual
9529   if (CSM == CXXDestructor && MD->isVirtual()) {
9530     if (Diagnose)
9531       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9532     return false;
9533   }
9534 
9535   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9536   //   A [special member] for class X is trivial if [...]
9537   //    -- class X has no virtual functions and no virtual base classes
9538   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9539     if (!Diagnose)
9540       return false;
9541 
9542     if (RD->getNumVBases()) {
9543       // Check for virtual bases. We already know that the corresponding
9544       // member in all bases is trivial, so vbases must all be direct.
9545       CXXBaseSpecifier &BS = *RD->vbases_begin();
9546       assert(BS.isVirtual());
9547       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9548       return false;
9549     }
9550 
9551     // Must have a virtual method.
9552     for (const auto *MI : RD->methods()) {
9553       if (MI->isVirtual()) {
9554         SourceLocation MLoc = MI->getBeginLoc();
9555         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9556         return false;
9557       }
9558     }
9559 
9560     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9561   }
9562 
9563   // Looks like it's trivial!
9564   return true;
9565 }
9566 
9567 namespace {
9568 struct FindHiddenVirtualMethod {
9569   Sema *S;
9570   CXXMethodDecl *Method;
9571   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9572   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9573 
9574 private:
9575   /// Check whether any most overridden method from MD in Methods
9576   static bool CheckMostOverridenMethods(
9577       const CXXMethodDecl *MD,
9578       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9579     if (MD->size_overridden_methods() == 0)
9580       return Methods.count(MD->getCanonicalDecl());
9581     for (const CXXMethodDecl *O : MD->overridden_methods())
9582       if (CheckMostOverridenMethods(O, Methods))
9583         return true;
9584     return false;
9585   }
9586 
9587 public:
9588   /// Member lookup function that determines whether a given C++
9589   /// method overloads virtual methods in a base class without overriding any,
9590   /// to be used with CXXRecordDecl::lookupInBases().
9591   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9592     RecordDecl *BaseRecord =
9593         Specifier->getType()->castAs<RecordType>()->getDecl();
9594 
9595     DeclarationName Name = Method->getDeclName();
9596     assert(Name.getNameKind() == DeclarationName::Identifier);
9597 
9598     bool foundSameNameMethod = false;
9599     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9600     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9601          Path.Decls = Path.Decls.slice(1)) {
9602       NamedDecl *D = Path.Decls.front();
9603       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9604         MD = MD->getCanonicalDecl();
9605         foundSameNameMethod = true;
9606         // Interested only in hidden virtual methods.
9607         if (!MD->isVirtual())
9608           continue;
9609         // If the method we are checking overrides a method from its base
9610         // don't warn about the other overloaded methods. Clang deviates from
9611         // GCC by only diagnosing overloads of inherited virtual functions that
9612         // do not override any other virtual functions in the base. GCC's
9613         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9614         // function from a base class. These cases may be better served by a
9615         // warning (not specific to virtual functions) on call sites when the
9616         // call would select a different function from the base class, were it
9617         // visible.
9618         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9619         if (!S->IsOverload(Method, MD, false))
9620           return true;
9621         // Collect the overload only if its hidden.
9622         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9623           overloadedMethods.push_back(MD);
9624       }
9625     }
9626 
9627     if (foundSameNameMethod)
9628       OverloadedMethods.append(overloadedMethods.begin(),
9629                                overloadedMethods.end());
9630     return foundSameNameMethod;
9631   }
9632 };
9633 } // end anonymous namespace
9634 
9635 /// Add the most overriden methods from MD to Methods
9636 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9637                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9638   if (MD->size_overridden_methods() == 0)
9639     Methods.insert(MD->getCanonicalDecl());
9640   else
9641     for (const CXXMethodDecl *O : MD->overridden_methods())
9642       AddMostOverridenMethods(O, Methods);
9643 }
9644 
9645 /// Check if a method overloads virtual methods in a base class without
9646 /// overriding any.
9647 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9648                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9649   if (!MD->getDeclName().isIdentifier())
9650     return;
9651 
9652   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9653                      /*bool RecordPaths=*/false,
9654                      /*bool DetectVirtual=*/false);
9655   FindHiddenVirtualMethod FHVM;
9656   FHVM.Method = MD;
9657   FHVM.S = this;
9658 
9659   // Keep the base methods that were overridden or introduced in the subclass
9660   // by 'using' in a set. A base method not in this set is hidden.
9661   CXXRecordDecl *DC = MD->getParent();
9662   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9663   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9664     NamedDecl *ND = *I;
9665     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9666       ND = shad->getTargetDecl();
9667     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9668       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9669   }
9670 
9671   if (DC->lookupInBases(FHVM, Paths))
9672     OverloadedMethods = FHVM.OverloadedMethods;
9673 }
9674 
9675 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9676                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9677   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9678     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9679     PartialDiagnostic PD = PDiag(
9680          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9681     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9682     Diag(overloadedMD->getLocation(), PD);
9683   }
9684 }
9685 
9686 /// Diagnose methods which overload virtual methods in a base class
9687 /// without overriding any.
9688 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9689   if (MD->isInvalidDecl())
9690     return;
9691 
9692   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9693     return;
9694 
9695   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9696   FindHiddenVirtualMethods(MD, OverloadedMethods);
9697   if (!OverloadedMethods.empty()) {
9698     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9699       << MD << (OverloadedMethods.size() > 1);
9700 
9701     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9702   }
9703 }
9704 
9705 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9706   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9707     // No diagnostics if this is a template instantiation.
9708     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9709       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9710            diag::ext_cannot_use_trivial_abi) << &RD;
9711       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9712            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9713     }
9714     RD.dropAttr<TrivialABIAttr>();
9715   };
9716 
9717   // Ill-formed if the copy and move constructors are deleted.
9718   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9719     if (RD.needsImplicitCopyConstructor() &&
9720         !RD.defaultedCopyConstructorIsDeleted())
9721       return true;
9722     if (RD.needsImplicitMoveConstructor() &&
9723         !RD.defaultedMoveConstructorIsDeleted())
9724       return true;
9725     for (const CXXConstructorDecl *CD : RD.ctors())
9726       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9727         return true;
9728     return false;
9729   };
9730 
9731   if (!HasNonDeletedCopyOrMoveConstructor()) {
9732     PrintDiagAndRemoveAttr(0);
9733     return;
9734   }
9735 
9736   // Ill-formed if the struct has virtual functions.
9737   if (RD.isPolymorphic()) {
9738     PrintDiagAndRemoveAttr(1);
9739     return;
9740   }
9741 
9742   for (const auto &B : RD.bases()) {
9743     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9744     // virtual base.
9745     if (!B.getType()->isDependentType() &&
9746         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9747       PrintDiagAndRemoveAttr(2);
9748       return;
9749     }
9750 
9751     if (B.isVirtual()) {
9752       PrintDiagAndRemoveAttr(3);
9753       return;
9754     }
9755   }
9756 
9757   for (const auto *FD : RD.fields()) {
9758     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9759     // non-trivial for the purpose of calls.
9760     QualType FT = FD->getType();
9761     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9762       PrintDiagAndRemoveAttr(4);
9763       return;
9764     }
9765 
9766     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9767       if (!RT->isDependentType() &&
9768           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9769         PrintDiagAndRemoveAttr(5);
9770         return;
9771       }
9772   }
9773 }
9774 
9775 void Sema::ActOnFinishCXXMemberSpecification(
9776     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9777     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9778   if (!TagDecl)
9779     return;
9780 
9781   AdjustDeclIfTemplate(TagDecl);
9782 
9783   for (const ParsedAttr &AL : AttrList) {
9784     if (AL.getKind() != ParsedAttr::AT_Visibility)
9785       continue;
9786     AL.setInvalid();
9787     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9788   }
9789 
9790   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9791               // strict aliasing violation!
9792               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9793               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9794 
9795   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9796 }
9797 
9798 /// Find the equality comparison functions that should be implicitly declared
9799 /// in a given class definition, per C++2a [class.compare.default]p3.
9800 static void findImplicitlyDeclaredEqualityComparisons(
9801     ASTContext &Ctx, CXXRecordDecl *RD,
9802     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9803   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9804   if (!RD->lookup(EqEq).empty())
9805     // Member operator== explicitly declared: no implicit operator==s.
9806     return;
9807 
9808   // Traverse friends looking for an '==' or a '<=>'.
9809   for (FriendDecl *Friend : RD->friends()) {
9810     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9811     if (!FD) continue;
9812 
9813     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9814       // Friend operator== explicitly declared: no implicit operator==s.
9815       Spaceships.clear();
9816       return;
9817     }
9818 
9819     if (FD->getOverloadedOperator() == OO_Spaceship &&
9820         FD->isExplicitlyDefaulted())
9821       Spaceships.push_back(FD);
9822   }
9823 
9824   // Look for members named 'operator<=>'.
9825   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9826   for (NamedDecl *ND : RD->lookup(Cmp)) {
9827     // Note that we could find a non-function here (either a function template
9828     // or a using-declaration). Neither case results in an implicit
9829     // 'operator=='.
9830     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9831       if (FD->isExplicitlyDefaulted())
9832         Spaceships.push_back(FD);
9833   }
9834 }
9835 
9836 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9837 /// special functions, such as the default constructor, copy
9838 /// constructor, or destructor, to the given C++ class (C++
9839 /// [special]p1).  This routine can only be executed just before the
9840 /// definition of the class is complete.
9841 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9842   if (ClassDecl->needsImplicitDefaultConstructor()) {
9843     ++getASTContext().NumImplicitDefaultConstructors;
9844 
9845     if (ClassDecl->hasInheritedConstructor())
9846       DeclareImplicitDefaultConstructor(ClassDecl);
9847   }
9848 
9849   if (ClassDecl->needsImplicitCopyConstructor()) {
9850     ++getASTContext().NumImplicitCopyConstructors;
9851 
9852     // If the properties or semantics of the copy constructor couldn't be
9853     // determined while the class was being declared, force a declaration
9854     // of it now.
9855     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9856         ClassDecl->hasInheritedConstructor())
9857       DeclareImplicitCopyConstructor(ClassDecl);
9858     // For the MS ABI we need to know whether the copy ctor is deleted. A
9859     // prerequisite for deleting the implicit copy ctor is that the class has a
9860     // move ctor or move assignment that is either user-declared or whose
9861     // semantics are inherited from a subobject. FIXME: We should provide a more
9862     // direct way for CodeGen to ask whether the constructor was deleted.
9863     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9864              (ClassDecl->hasUserDeclaredMoveConstructor() ||
9865               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9866               ClassDecl->hasUserDeclaredMoveAssignment() ||
9867               ClassDecl->needsOverloadResolutionForMoveAssignment()))
9868       DeclareImplicitCopyConstructor(ClassDecl);
9869   }
9870 
9871   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
9872     ++getASTContext().NumImplicitMoveConstructors;
9873 
9874     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9875         ClassDecl->hasInheritedConstructor())
9876       DeclareImplicitMoveConstructor(ClassDecl);
9877   }
9878 
9879   if (ClassDecl->needsImplicitCopyAssignment()) {
9880     ++getASTContext().NumImplicitCopyAssignmentOperators;
9881 
9882     // If we have a dynamic class, then the copy assignment operator may be
9883     // virtual, so we have to declare it immediately. This ensures that, e.g.,
9884     // it shows up in the right place in the vtable and that we diagnose
9885     // problems with the implicit exception specification.
9886     if (ClassDecl->isDynamicClass() ||
9887         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9888         ClassDecl->hasInheritedAssignment())
9889       DeclareImplicitCopyAssignment(ClassDecl);
9890   }
9891 
9892   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9893     ++getASTContext().NumImplicitMoveAssignmentOperators;
9894 
9895     // Likewise for the move assignment operator.
9896     if (ClassDecl->isDynamicClass() ||
9897         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9898         ClassDecl->hasInheritedAssignment())
9899       DeclareImplicitMoveAssignment(ClassDecl);
9900   }
9901 
9902   if (ClassDecl->needsImplicitDestructor()) {
9903     ++getASTContext().NumImplicitDestructors;
9904 
9905     // If we have a dynamic class, then the destructor may be virtual, so we
9906     // have to declare the destructor immediately. This ensures that, e.g., it
9907     // shows up in the right place in the vtable and that we diagnose problems
9908     // with the implicit exception specification.
9909     if (ClassDecl->isDynamicClass() ||
9910         ClassDecl->needsOverloadResolutionForDestructor())
9911       DeclareImplicitDestructor(ClassDecl);
9912   }
9913 
9914   // C++2a [class.compare.default]p3:
9915   //   If the member-specification does not explicitly declare any member or
9916   //   friend named operator==, an == operator function is declared implicitly
9917   //   for each defaulted three-way comparison operator function defined in the
9918   //   member-specification
9919   // FIXME: Consider doing this lazily.
9920   if (getLangOpts().CPlusPlus20) {
9921     llvm::SmallVector<FunctionDecl*, 4> DefaultedSpaceships;
9922     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9923                                               DefaultedSpaceships);
9924     for (auto *FD : DefaultedSpaceships)
9925       DeclareImplicitEqualityComparison(ClassDecl, FD);
9926   }
9927 }
9928 
9929 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
9930   if (!D)
9931     return 0;
9932 
9933   // The order of template parameters is not important here. All names
9934   // get added to the same scope.
9935   SmallVector<TemplateParameterList *, 4> ParameterLists;
9936 
9937   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9938     D = TD->getTemplatedDecl();
9939 
9940   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9941     ParameterLists.push_back(PSD->getTemplateParameters());
9942 
9943   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9944     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9945       ParameterLists.push_back(DD->getTemplateParameterList(i));
9946 
9947     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9948       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9949         ParameterLists.push_back(FTD->getTemplateParameters());
9950     }
9951   }
9952 
9953   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9954     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9955       ParameterLists.push_back(TD->getTemplateParameterList(i));
9956 
9957     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9958       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9959         ParameterLists.push_back(CTD->getTemplateParameters());
9960     }
9961   }
9962 
9963   unsigned Count = 0;
9964   for (TemplateParameterList *Params : ParameterLists) {
9965     if (Params->size() > 0)
9966       // Ignore explicit specializations; they don't contribute to the template
9967       // depth.
9968       ++Count;
9969     for (NamedDecl *Param : *Params) {
9970       if (Param->getDeclName()) {
9971         S->AddDecl(Param);
9972         IdResolver.AddDecl(Param);
9973       }
9974     }
9975   }
9976 
9977   return Count;
9978 }
9979 
9980 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
9981   if (!RecordD) return;
9982   AdjustDeclIfTemplate(RecordD);
9983   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
9984   PushDeclContext(S, Record);
9985 }
9986 
9987 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
9988   if (!RecordD) return;
9989   PopDeclContext();
9990 }
9991 
9992 /// This is used to implement the constant expression evaluation part of the
9993 /// attribute enable_if extension. There is nothing in standard C++ which would
9994 /// require reentering parameters.
9995 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
9996   if (!Param)
9997     return;
9998 
9999   S->AddDecl(Param);
10000   if (Param->getDeclName())
10001     IdResolver.AddDecl(Param);
10002 }
10003 
10004 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10005 /// parsing a top-level (non-nested) C++ class, and we are now
10006 /// parsing those parts of the given Method declaration that could
10007 /// not be parsed earlier (C++ [class.mem]p2), such as default
10008 /// arguments. This action should enter the scope of the given
10009 /// Method declaration as if we had just parsed the qualified method
10010 /// name. However, it should not bring the parameters into scope;
10011 /// that will be performed by ActOnDelayedCXXMethodParameter.
10012 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10013 }
10014 
10015 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10016 /// C++ method declaration. We're (re-)introducing the given
10017 /// function parameter into scope for use in parsing later parts of
10018 /// the method declaration. For example, we could see an
10019 /// ActOnParamDefaultArgument event for this parameter.
10020 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10021   if (!ParamD)
10022     return;
10023 
10024   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10025 
10026   S->AddDecl(Param);
10027   if (Param->getDeclName())
10028     IdResolver.AddDecl(Param);
10029 }
10030 
10031 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10032 /// processing the delayed method declaration for Method. The method
10033 /// declaration is now considered finished. There may be a separate
10034 /// ActOnStartOfFunctionDef action later (not necessarily
10035 /// immediately!) for this method, if it was also defined inside the
10036 /// class body.
10037 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10038   if (!MethodD)
10039     return;
10040 
10041   AdjustDeclIfTemplate(MethodD);
10042 
10043   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10044 
10045   // Now that we have our default arguments, check the constructor
10046   // again. It could produce additional diagnostics or affect whether
10047   // the class has implicitly-declared destructors, among other
10048   // things.
10049   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10050     CheckConstructor(Constructor);
10051 
10052   // Check the default arguments, which we may have added.
10053   if (!Method->isInvalidDecl())
10054     CheckCXXDefaultArguments(Method);
10055 }
10056 
10057 // Emit the given diagnostic for each non-address-space qualifier.
10058 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10059 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10060   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10061   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10062     bool DiagOccured = false;
10063     FTI.MethodQualifiers->forEachQualifier(
10064         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10065                                    SourceLocation SL) {
10066           // This diagnostic should be emitted on any qualifier except an addr
10067           // space qualifier. However, forEachQualifier currently doesn't visit
10068           // addr space qualifiers, so there's no way to write this condition
10069           // right now; we just diagnose on everything.
10070           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10071           DiagOccured = true;
10072         });
10073     if (DiagOccured)
10074       D.setInvalidType();
10075   }
10076 }
10077 
10078 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10079 /// the well-formedness of the constructor declarator @p D with type @p
10080 /// R. If there are any errors in the declarator, this routine will
10081 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10082 /// will be updated to reflect a well-formed type for the constructor and
10083 /// returned.
10084 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10085                                           StorageClass &SC) {
10086   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10087 
10088   // C++ [class.ctor]p3:
10089   //   A constructor shall not be virtual (10.3) or static (9.4). A
10090   //   constructor can be invoked for a const, volatile or const
10091   //   volatile object. A constructor shall not be declared const,
10092   //   volatile, or const volatile (9.3.2).
10093   if (isVirtual) {
10094     if (!D.isInvalidType())
10095       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10096         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10097         << SourceRange(D.getIdentifierLoc());
10098     D.setInvalidType();
10099   }
10100   if (SC == SC_Static) {
10101     if (!D.isInvalidType())
10102       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10103         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10104         << SourceRange(D.getIdentifierLoc());
10105     D.setInvalidType();
10106     SC = SC_None;
10107   }
10108 
10109   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10110     diagnoseIgnoredQualifiers(
10111         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10112         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10113         D.getDeclSpec().getRestrictSpecLoc(),
10114         D.getDeclSpec().getAtomicSpecLoc());
10115     D.setInvalidType();
10116   }
10117 
10118   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10119 
10120   // C++0x [class.ctor]p4:
10121   //   A constructor shall not be declared with a ref-qualifier.
10122   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10123   if (FTI.hasRefQualifier()) {
10124     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10125       << FTI.RefQualifierIsLValueRef
10126       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10127     D.setInvalidType();
10128   }
10129 
10130   // Rebuild the function type "R" without any type qualifiers (in
10131   // case any of the errors above fired) and with "void" as the
10132   // return type, since constructors don't have return types.
10133   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10134   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10135     return R;
10136 
10137   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10138   EPI.TypeQuals = Qualifiers();
10139   EPI.RefQualifier = RQ_None;
10140 
10141   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10142 }
10143 
10144 /// CheckConstructor - Checks a fully-formed constructor for
10145 /// well-formedness, issuing any diagnostics required. Returns true if
10146 /// the constructor declarator is invalid.
10147 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10148   CXXRecordDecl *ClassDecl
10149     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10150   if (!ClassDecl)
10151     return Constructor->setInvalidDecl();
10152 
10153   // C++ [class.copy]p3:
10154   //   A declaration of a constructor for a class X is ill-formed if
10155   //   its first parameter is of type (optionally cv-qualified) X and
10156   //   either there are no other parameters or else all other
10157   //   parameters have default arguments.
10158   if (!Constructor->isInvalidDecl() &&
10159       Constructor->hasOneParamOrDefaultArgs() &&
10160       Constructor->getTemplateSpecializationKind() !=
10161           TSK_ImplicitInstantiation) {
10162     QualType ParamType = Constructor->getParamDecl(0)->getType();
10163     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10164     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10165       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10166       const char *ConstRef
10167         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10168                                                         : " const &";
10169       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10170         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10171 
10172       // FIXME: Rather that making the constructor invalid, we should endeavor
10173       // to fix the type.
10174       Constructor->setInvalidDecl();
10175     }
10176   }
10177 }
10178 
10179 /// CheckDestructor - Checks a fully-formed destructor definition for
10180 /// well-formedness, issuing any diagnostics required.  Returns true
10181 /// on error.
10182 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10183   CXXRecordDecl *RD = Destructor->getParent();
10184 
10185   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10186     SourceLocation Loc;
10187 
10188     if (!Destructor->isImplicit())
10189       Loc = Destructor->getLocation();
10190     else
10191       Loc = RD->getLocation();
10192 
10193     // If we have a virtual destructor, look up the deallocation function
10194     if (FunctionDecl *OperatorDelete =
10195             FindDeallocationFunctionForDestructor(Loc, RD)) {
10196       Expr *ThisArg = nullptr;
10197 
10198       // If the notional 'delete this' expression requires a non-trivial
10199       // conversion from 'this' to the type of a destroying operator delete's
10200       // first parameter, perform that conversion now.
10201       if (OperatorDelete->isDestroyingOperatorDelete()) {
10202         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10203         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10204           // C++ [class.dtor]p13:
10205           //   ... as if for the expression 'delete this' appearing in a
10206           //   non-virtual destructor of the destructor's class.
10207           ContextRAII SwitchContext(*this, Destructor);
10208           ExprResult This =
10209               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10210           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10211           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10212           if (This.isInvalid()) {
10213             // FIXME: Register this as a context note so that it comes out
10214             // in the right order.
10215             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10216             return true;
10217           }
10218           ThisArg = This.get();
10219         }
10220       }
10221 
10222       DiagnoseUseOfDecl(OperatorDelete, Loc);
10223       MarkFunctionReferenced(Loc, OperatorDelete);
10224       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10225     }
10226   }
10227 
10228   return false;
10229 }
10230 
10231 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10232 /// the well-formednes of the destructor declarator @p D with type @p
10233 /// R. If there are any errors in the declarator, this routine will
10234 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10235 /// will be updated to reflect a well-formed type for the destructor and
10236 /// returned.
10237 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10238                                          StorageClass& SC) {
10239   // C++ [class.dtor]p1:
10240   //   [...] A typedef-name that names a class is a class-name
10241   //   (7.1.3); however, a typedef-name that names a class shall not
10242   //   be used as the identifier in the declarator for a destructor
10243   //   declaration.
10244   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10245   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10246     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10247       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10248   else if (const TemplateSpecializationType *TST =
10249              DeclaratorType->getAs<TemplateSpecializationType>())
10250     if (TST->isTypeAlias())
10251       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10252         << DeclaratorType << 1;
10253 
10254   // C++ [class.dtor]p2:
10255   //   A destructor is used to destroy objects of its class type. A
10256   //   destructor takes no parameters, and no return type can be
10257   //   specified for it (not even void). The address of a destructor
10258   //   shall not be taken. A destructor shall not be static. A
10259   //   destructor can be invoked for a const, volatile or const
10260   //   volatile object. A destructor shall not be declared const,
10261   //   volatile or const volatile (9.3.2).
10262   if (SC == SC_Static) {
10263     if (!D.isInvalidType())
10264       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10265         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10266         << SourceRange(D.getIdentifierLoc())
10267         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10268 
10269     SC = SC_None;
10270   }
10271   if (!D.isInvalidType()) {
10272     // Destructors don't have return types, but the parser will
10273     // happily parse something like:
10274     //
10275     //   class X {
10276     //     float ~X();
10277     //   };
10278     //
10279     // The return type will be eliminated later.
10280     if (D.getDeclSpec().hasTypeSpecifier())
10281       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10282         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10283         << SourceRange(D.getIdentifierLoc());
10284     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10285       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10286                                 SourceLocation(),
10287                                 D.getDeclSpec().getConstSpecLoc(),
10288                                 D.getDeclSpec().getVolatileSpecLoc(),
10289                                 D.getDeclSpec().getRestrictSpecLoc(),
10290                                 D.getDeclSpec().getAtomicSpecLoc());
10291       D.setInvalidType();
10292     }
10293   }
10294 
10295   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10296 
10297   // C++0x [class.dtor]p2:
10298   //   A destructor shall not be declared with a ref-qualifier.
10299   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10300   if (FTI.hasRefQualifier()) {
10301     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10302       << FTI.RefQualifierIsLValueRef
10303       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10304     D.setInvalidType();
10305   }
10306 
10307   // Make sure we don't have any parameters.
10308   if (FTIHasNonVoidParameters(FTI)) {
10309     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10310 
10311     // Delete the parameters.
10312     FTI.freeParams();
10313     D.setInvalidType();
10314   }
10315 
10316   // Make sure the destructor isn't variadic.
10317   if (FTI.isVariadic) {
10318     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10319     D.setInvalidType();
10320   }
10321 
10322   // Rebuild the function type "R" without any type qualifiers or
10323   // parameters (in case any of the errors above fired) and with
10324   // "void" as the return type, since destructors don't have return
10325   // types.
10326   if (!D.isInvalidType())
10327     return R;
10328 
10329   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10330   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10331   EPI.Variadic = false;
10332   EPI.TypeQuals = Qualifiers();
10333   EPI.RefQualifier = RQ_None;
10334   return Context.getFunctionType(Context.VoidTy, None, EPI);
10335 }
10336 
10337 static void extendLeft(SourceRange &R, SourceRange Before) {
10338   if (Before.isInvalid())
10339     return;
10340   R.setBegin(Before.getBegin());
10341   if (R.getEnd().isInvalid())
10342     R.setEnd(Before.getEnd());
10343 }
10344 
10345 static void extendRight(SourceRange &R, SourceRange After) {
10346   if (After.isInvalid())
10347     return;
10348   if (R.getBegin().isInvalid())
10349     R.setBegin(After.getBegin());
10350   R.setEnd(After.getEnd());
10351 }
10352 
10353 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10354 /// well-formednes of the conversion function declarator @p D with
10355 /// type @p R. If there are any errors in the declarator, this routine
10356 /// will emit diagnostics and return true. Otherwise, it will return
10357 /// false. Either way, the type @p R will be updated to reflect a
10358 /// well-formed type for the conversion operator.
10359 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10360                                      StorageClass& SC) {
10361   // C++ [class.conv.fct]p1:
10362   //   Neither parameter types nor return type can be specified. The
10363   //   type of a conversion function (8.3.5) is "function taking no
10364   //   parameter returning conversion-type-id."
10365   if (SC == SC_Static) {
10366     if (!D.isInvalidType())
10367       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10368         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10369         << D.getName().getSourceRange();
10370     D.setInvalidType();
10371     SC = SC_None;
10372   }
10373 
10374   TypeSourceInfo *ConvTSI = nullptr;
10375   QualType ConvType =
10376       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10377 
10378   const DeclSpec &DS = D.getDeclSpec();
10379   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10380     // Conversion functions don't have return types, but the parser will
10381     // happily parse something like:
10382     //
10383     //   class X {
10384     //     float operator bool();
10385     //   };
10386     //
10387     // The return type will be changed later anyway.
10388     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10389       << SourceRange(DS.getTypeSpecTypeLoc())
10390       << SourceRange(D.getIdentifierLoc());
10391     D.setInvalidType();
10392   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10393     // It's also plausible that the user writes type qualifiers in the wrong
10394     // place, such as:
10395     //   struct S { const operator int(); };
10396     // FIXME: we could provide a fixit to move the qualifiers onto the
10397     // conversion type.
10398     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10399         << SourceRange(D.getIdentifierLoc()) << 0;
10400     D.setInvalidType();
10401   }
10402 
10403   const auto *Proto = R->castAs<FunctionProtoType>();
10404 
10405   // Make sure we don't have any parameters.
10406   if (Proto->getNumParams() > 0) {
10407     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10408 
10409     // Delete the parameters.
10410     D.getFunctionTypeInfo().freeParams();
10411     D.setInvalidType();
10412   } else if (Proto->isVariadic()) {
10413     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10414     D.setInvalidType();
10415   }
10416 
10417   // Diagnose "&operator bool()" and other such nonsense.  This
10418   // is actually a gcc extension which we don't support.
10419   if (Proto->getReturnType() != ConvType) {
10420     bool NeedsTypedef = false;
10421     SourceRange Before, After;
10422 
10423     // Walk the chunks and extract information on them for our diagnostic.
10424     bool PastFunctionChunk = false;
10425     for (auto &Chunk : D.type_objects()) {
10426       switch (Chunk.Kind) {
10427       case DeclaratorChunk::Function:
10428         if (!PastFunctionChunk) {
10429           if (Chunk.Fun.HasTrailingReturnType) {
10430             TypeSourceInfo *TRT = nullptr;
10431             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10432             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10433           }
10434           PastFunctionChunk = true;
10435           break;
10436         }
10437         LLVM_FALLTHROUGH;
10438       case DeclaratorChunk::Array:
10439         NeedsTypedef = true;
10440         extendRight(After, Chunk.getSourceRange());
10441         break;
10442 
10443       case DeclaratorChunk::Pointer:
10444       case DeclaratorChunk::BlockPointer:
10445       case DeclaratorChunk::Reference:
10446       case DeclaratorChunk::MemberPointer:
10447       case DeclaratorChunk::Pipe:
10448         extendLeft(Before, Chunk.getSourceRange());
10449         break;
10450 
10451       case DeclaratorChunk::Paren:
10452         extendLeft(Before, Chunk.Loc);
10453         extendRight(After, Chunk.EndLoc);
10454         break;
10455       }
10456     }
10457 
10458     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10459                          After.isValid()  ? After.getBegin() :
10460                                             D.getIdentifierLoc();
10461     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10462     DB << Before << After;
10463 
10464     if (!NeedsTypedef) {
10465       DB << /*don't need a typedef*/0;
10466 
10467       // If we can provide a correct fix-it hint, do so.
10468       if (After.isInvalid() && ConvTSI) {
10469         SourceLocation InsertLoc =
10470             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10471         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10472            << FixItHint::CreateInsertionFromRange(
10473                   InsertLoc, CharSourceRange::getTokenRange(Before))
10474            << FixItHint::CreateRemoval(Before);
10475       }
10476     } else if (!Proto->getReturnType()->isDependentType()) {
10477       DB << /*typedef*/1 << Proto->getReturnType();
10478     } else if (getLangOpts().CPlusPlus11) {
10479       DB << /*alias template*/2 << Proto->getReturnType();
10480     } else {
10481       DB << /*might not be fixable*/3;
10482     }
10483 
10484     // Recover by incorporating the other type chunks into the result type.
10485     // Note, this does *not* change the name of the function. This is compatible
10486     // with the GCC extension:
10487     //   struct S { &operator int(); } s;
10488     //   int &r = s.operator int(); // ok in GCC
10489     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10490     ConvType = Proto->getReturnType();
10491   }
10492 
10493   // C++ [class.conv.fct]p4:
10494   //   The conversion-type-id shall not represent a function type nor
10495   //   an array type.
10496   if (ConvType->isArrayType()) {
10497     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10498     ConvType = Context.getPointerType(ConvType);
10499     D.setInvalidType();
10500   } else if (ConvType->isFunctionType()) {
10501     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10502     ConvType = Context.getPointerType(ConvType);
10503     D.setInvalidType();
10504   }
10505 
10506   // Rebuild the function type "R" without any parameters (in case any
10507   // of the errors above fired) and with the conversion type as the
10508   // return type.
10509   if (D.isInvalidType())
10510     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10511 
10512   // C++0x explicit conversion operators.
10513   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10514     Diag(DS.getExplicitSpecLoc(),
10515          getLangOpts().CPlusPlus11
10516              ? diag::warn_cxx98_compat_explicit_conversion_functions
10517              : diag::ext_explicit_conversion_functions)
10518         << SourceRange(DS.getExplicitSpecRange());
10519 }
10520 
10521 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10522 /// the declaration of the given C++ conversion function. This routine
10523 /// is responsible for recording the conversion function in the C++
10524 /// class, if possible.
10525 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10526   assert(Conversion && "Expected to receive a conversion function declaration");
10527 
10528   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10529 
10530   // Make sure we aren't redeclaring the conversion function.
10531   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10532   // C++ [class.conv.fct]p1:
10533   //   [...] A conversion function is never used to convert a
10534   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10535   //   same object type (or a reference to it), to a (possibly
10536   //   cv-qualified) base class of that type (or a reference to it),
10537   //   or to (possibly cv-qualified) void.
10538   QualType ClassType
10539     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10540   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10541     ConvType = ConvTypeRef->getPointeeType();
10542   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10543       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10544     /* Suppress diagnostics for instantiations. */;
10545   else if (Conversion->size_overridden_methods() != 0)
10546     /* Suppress diagnostics for overriding virtual function in a base class. */;
10547   else if (ConvType->isRecordType()) {
10548     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10549     if (ConvType == ClassType)
10550       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10551         << ClassType;
10552     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10553       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10554         <<  ClassType << ConvType;
10555   } else if (ConvType->isVoidType()) {
10556     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10557       << ClassType << ConvType;
10558   }
10559 
10560   if (FunctionTemplateDecl *ConversionTemplate
10561                                 = Conversion->getDescribedFunctionTemplate())
10562     return ConversionTemplate;
10563 
10564   return Conversion;
10565 }
10566 
10567 namespace {
10568 /// Utility class to accumulate and print a diagnostic listing the invalid
10569 /// specifier(s) on a declaration.
10570 struct BadSpecifierDiagnoser {
10571   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10572       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10573   ~BadSpecifierDiagnoser() {
10574     Diagnostic << Specifiers;
10575   }
10576 
10577   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10578     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10579   }
10580   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10581     return check(SpecLoc,
10582                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10583   }
10584   void check(SourceLocation SpecLoc, const char *Spec) {
10585     if (SpecLoc.isInvalid()) return;
10586     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10587     if (!Specifiers.empty()) Specifiers += " ";
10588     Specifiers += Spec;
10589   }
10590 
10591   Sema &S;
10592   Sema::SemaDiagnosticBuilder Diagnostic;
10593   std::string Specifiers;
10594 };
10595 }
10596 
10597 /// Check the validity of a declarator that we parsed for a deduction-guide.
10598 /// These aren't actually declarators in the grammar, so we need to check that
10599 /// the user didn't specify any pieces that are not part of the deduction-guide
10600 /// grammar.
10601 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10602                                          StorageClass &SC) {
10603   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10604   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10605   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10606 
10607   // C++ [temp.deduct.guide]p3:
10608   //   A deduction-gide shall be declared in the same scope as the
10609   //   corresponding class template.
10610   if (!CurContext->getRedeclContext()->Equals(
10611           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10612     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10613       << GuidedTemplateDecl;
10614     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10615   }
10616 
10617   auto &DS = D.getMutableDeclSpec();
10618   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10619   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10620       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10621       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10622     BadSpecifierDiagnoser Diagnoser(
10623         *this, D.getIdentifierLoc(),
10624         diag::err_deduction_guide_invalid_specifier);
10625 
10626     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10627     DS.ClearStorageClassSpecs();
10628     SC = SC_None;
10629 
10630     // 'explicit' is permitted.
10631     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10632     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10633     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10634     DS.ClearConstexprSpec();
10635 
10636     Diagnoser.check(DS.getConstSpecLoc(), "const");
10637     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10638     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10639     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10640     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10641     DS.ClearTypeQualifiers();
10642 
10643     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10644     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10645     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10646     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10647     DS.ClearTypeSpecType();
10648   }
10649 
10650   if (D.isInvalidType())
10651     return;
10652 
10653   // Check the declarator is simple enough.
10654   bool FoundFunction = false;
10655   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10656     if (Chunk.Kind == DeclaratorChunk::Paren)
10657       continue;
10658     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10659       Diag(D.getDeclSpec().getBeginLoc(),
10660            diag::err_deduction_guide_with_complex_decl)
10661           << D.getSourceRange();
10662       break;
10663     }
10664     if (!Chunk.Fun.hasTrailingReturnType()) {
10665       Diag(D.getName().getBeginLoc(),
10666            diag::err_deduction_guide_no_trailing_return_type);
10667       break;
10668     }
10669 
10670     // Check that the return type is written as a specialization of
10671     // the template specified as the deduction-guide's name.
10672     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10673     TypeSourceInfo *TSI = nullptr;
10674     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10675     assert(TSI && "deduction guide has valid type but invalid return type?");
10676     bool AcceptableReturnType = false;
10677     bool MightInstantiateToSpecialization = false;
10678     if (auto RetTST =
10679             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10680       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10681       bool TemplateMatches =
10682           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10683       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10684         AcceptableReturnType = true;
10685       else {
10686         // This could still instantiate to the right type, unless we know it
10687         // names the wrong class template.
10688         auto *TD = SpecifiedName.getAsTemplateDecl();
10689         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10690                                              !TemplateMatches);
10691       }
10692     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10693       MightInstantiateToSpecialization = true;
10694     }
10695 
10696     if (!AcceptableReturnType) {
10697       Diag(TSI->getTypeLoc().getBeginLoc(),
10698            diag::err_deduction_guide_bad_trailing_return_type)
10699           << GuidedTemplate << TSI->getType()
10700           << MightInstantiateToSpecialization
10701           << TSI->getTypeLoc().getSourceRange();
10702     }
10703 
10704     // Keep going to check that we don't have any inner declarator pieces (we
10705     // could still have a function returning a pointer to a function).
10706     FoundFunction = true;
10707   }
10708 
10709   if (D.isFunctionDefinition())
10710     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10711 }
10712 
10713 //===----------------------------------------------------------------------===//
10714 // Namespace Handling
10715 //===----------------------------------------------------------------------===//
10716 
10717 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10718 /// reopened.
10719 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10720                                             SourceLocation Loc,
10721                                             IdentifierInfo *II, bool *IsInline,
10722                                             NamespaceDecl *PrevNS) {
10723   assert(*IsInline != PrevNS->isInline());
10724 
10725   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10726   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10727   // inline namespaces, with the intention of bringing names into namespace std.
10728   //
10729   // We support this just well enough to get that case working; this is not
10730   // sufficient to support reopening namespaces as inline in general.
10731   if (*IsInline && II && II->getName().startswith("__atomic") &&
10732       S.getSourceManager().isInSystemHeader(Loc)) {
10733     // Mark all prior declarations of the namespace as inline.
10734     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10735          NS = NS->getPreviousDecl())
10736       NS->setInline(*IsInline);
10737     // Patch up the lookup table for the containing namespace. This isn't really
10738     // correct, but it's good enough for this particular case.
10739     for (auto *I : PrevNS->decls())
10740       if (auto *ND = dyn_cast<NamedDecl>(I))
10741         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10742     return;
10743   }
10744 
10745   if (PrevNS->isInline())
10746     // The user probably just forgot the 'inline', so suggest that it
10747     // be added back.
10748     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10749       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10750   else
10751     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10752 
10753   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10754   *IsInline = PrevNS->isInline();
10755 }
10756 
10757 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10758 /// definition.
10759 Decl *Sema::ActOnStartNamespaceDef(
10760     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10761     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10762     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10763   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10764   // For anonymous namespace, take the location of the left brace.
10765   SourceLocation Loc = II ? IdentLoc : LBrace;
10766   bool IsInline = InlineLoc.isValid();
10767   bool IsInvalid = false;
10768   bool IsStd = false;
10769   bool AddToKnown = false;
10770   Scope *DeclRegionScope = NamespcScope->getParent();
10771 
10772   NamespaceDecl *PrevNS = nullptr;
10773   if (II) {
10774     // C++ [namespace.def]p2:
10775     //   The identifier in an original-namespace-definition shall not
10776     //   have been previously defined in the declarative region in
10777     //   which the original-namespace-definition appears. The
10778     //   identifier in an original-namespace-definition is the name of
10779     //   the namespace. Subsequently in that declarative region, it is
10780     //   treated as an original-namespace-name.
10781     //
10782     // Since namespace names are unique in their scope, and we don't
10783     // look through using directives, just look for any ordinary names
10784     // as if by qualified name lookup.
10785     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10786                    ForExternalRedeclaration);
10787     LookupQualifiedName(R, CurContext->getRedeclContext());
10788     NamedDecl *PrevDecl =
10789         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10790     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10791 
10792     if (PrevNS) {
10793       // This is an extended namespace definition.
10794       if (IsInline != PrevNS->isInline())
10795         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10796                                         &IsInline, PrevNS);
10797     } else if (PrevDecl) {
10798       // This is an invalid name redefinition.
10799       Diag(Loc, diag::err_redefinition_different_kind)
10800         << II;
10801       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10802       IsInvalid = true;
10803       // Continue on to push Namespc as current DeclContext and return it.
10804     } else if (II->isStr("std") &&
10805                CurContext->getRedeclContext()->isTranslationUnit()) {
10806       // This is the first "real" definition of the namespace "std", so update
10807       // our cache of the "std" namespace to point at this definition.
10808       PrevNS = getStdNamespace();
10809       IsStd = true;
10810       AddToKnown = !IsInline;
10811     } else {
10812       // We've seen this namespace for the first time.
10813       AddToKnown = !IsInline;
10814     }
10815   } else {
10816     // Anonymous namespaces.
10817 
10818     // Determine whether the parent already has an anonymous namespace.
10819     DeclContext *Parent = CurContext->getRedeclContext();
10820     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10821       PrevNS = TU->getAnonymousNamespace();
10822     } else {
10823       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10824       PrevNS = ND->getAnonymousNamespace();
10825     }
10826 
10827     if (PrevNS && IsInline != PrevNS->isInline())
10828       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10829                                       &IsInline, PrevNS);
10830   }
10831 
10832   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10833                                                  StartLoc, Loc, II, PrevNS);
10834   if (IsInvalid)
10835     Namespc->setInvalidDecl();
10836 
10837   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10838   AddPragmaAttributes(DeclRegionScope, Namespc);
10839 
10840   // FIXME: Should we be merging attributes?
10841   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10842     PushNamespaceVisibilityAttr(Attr, Loc);
10843 
10844   if (IsStd)
10845     StdNamespace = Namespc;
10846   if (AddToKnown)
10847     KnownNamespaces[Namespc] = false;
10848 
10849   if (II) {
10850     PushOnScopeChains(Namespc, DeclRegionScope);
10851   } else {
10852     // Link the anonymous namespace into its parent.
10853     DeclContext *Parent = CurContext->getRedeclContext();
10854     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10855       TU->setAnonymousNamespace(Namespc);
10856     } else {
10857       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10858     }
10859 
10860     CurContext->addDecl(Namespc);
10861 
10862     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10863     //   behaves as if it were replaced by
10864     //     namespace unique { /* empty body */ }
10865     //     using namespace unique;
10866     //     namespace unique { namespace-body }
10867     //   where all occurrences of 'unique' in a translation unit are
10868     //   replaced by the same identifier and this identifier differs
10869     //   from all other identifiers in the entire program.
10870 
10871     // We just create the namespace with an empty name and then add an
10872     // implicit using declaration, just like the standard suggests.
10873     //
10874     // CodeGen enforces the "universally unique" aspect by giving all
10875     // declarations semantically contained within an anonymous
10876     // namespace internal linkage.
10877 
10878     if (!PrevNS) {
10879       UD = UsingDirectiveDecl::Create(Context, Parent,
10880                                       /* 'using' */ LBrace,
10881                                       /* 'namespace' */ SourceLocation(),
10882                                       /* qualifier */ NestedNameSpecifierLoc(),
10883                                       /* identifier */ SourceLocation(),
10884                                       Namespc,
10885                                       /* Ancestor */ Parent);
10886       UD->setImplicit();
10887       Parent->addDecl(UD);
10888     }
10889   }
10890 
10891   ActOnDocumentableDecl(Namespc);
10892 
10893   // Although we could have an invalid decl (i.e. the namespace name is a
10894   // redefinition), push it as current DeclContext and try to continue parsing.
10895   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10896   // for the namespace has the declarations that showed up in that particular
10897   // namespace definition.
10898   PushDeclContext(NamespcScope, Namespc);
10899   return Namespc;
10900 }
10901 
10902 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10903 /// is a namespace alias, returns the namespace it points to.
10904 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10905   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10906     return AD->getNamespace();
10907   return dyn_cast_or_null<NamespaceDecl>(D);
10908 }
10909 
10910 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10911 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10912 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10913   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10914   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10915   Namespc->setRBraceLoc(RBrace);
10916   PopDeclContext();
10917   if (Namespc->hasAttr<VisibilityAttr>())
10918     PopPragmaVisibility(true, RBrace);
10919   // If this namespace contains an export-declaration, export it now.
10920   if (DeferredExportedNamespaces.erase(Namespc))
10921     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10922 }
10923 
10924 CXXRecordDecl *Sema::getStdBadAlloc() const {
10925   return cast_or_null<CXXRecordDecl>(
10926                                   StdBadAlloc.get(Context.getExternalSource()));
10927 }
10928 
10929 EnumDecl *Sema::getStdAlignValT() const {
10930   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10931 }
10932 
10933 NamespaceDecl *Sema::getStdNamespace() const {
10934   return cast_or_null<NamespaceDecl>(
10935                                  StdNamespace.get(Context.getExternalSource()));
10936 }
10937 
10938 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10939   if (!StdExperimentalNamespaceCache) {
10940     if (auto Std = getStdNamespace()) {
10941       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10942                           SourceLocation(), LookupNamespaceName);
10943       if (!LookupQualifiedName(Result, Std) ||
10944           !(StdExperimentalNamespaceCache =
10945                 Result.getAsSingle<NamespaceDecl>()))
10946         Result.suppressDiagnostics();
10947     }
10948   }
10949   return StdExperimentalNamespaceCache;
10950 }
10951 
10952 namespace {
10953 
10954 enum UnsupportedSTLSelect {
10955   USS_InvalidMember,
10956   USS_MissingMember,
10957   USS_NonTrivial,
10958   USS_Other
10959 };
10960 
10961 struct InvalidSTLDiagnoser {
10962   Sema &S;
10963   SourceLocation Loc;
10964   QualType TyForDiags;
10965 
10966   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
10967                       const VarDecl *VD = nullptr) {
10968     {
10969       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
10970                << TyForDiags << ((int)Sel);
10971       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
10972         assert(!Name.empty());
10973         D << Name;
10974       }
10975     }
10976     if (Sel == USS_InvalidMember) {
10977       S.Diag(VD->getLocation(), diag::note_var_declared_here)
10978           << VD << VD->getSourceRange();
10979     }
10980     return QualType();
10981   }
10982 };
10983 } // namespace
10984 
10985 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
10986                                            SourceLocation Loc,
10987                                            ComparisonCategoryUsage Usage) {
10988   assert(getLangOpts().CPlusPlus &&
10989          "Looking for comparison category type outside of C++.");
10990 
10991   // Use an elaborated type for diagnostics which has a name containing the
10992   // prepended 'std' namespace but not any inline namespace names.
10993   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
10994     auto *NNS =
10995         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
10996     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
10997   };
10998 
10999   // Check if we've already successfully checked the comparison category type
11000   // before. If so, skip checking it again.
11001   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11002   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11003     // The only thing we need to check is that the type has a reachable
11004     // definition in the current context.
11005     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11006       return QualType();
11007 
11008     return Info->getType();
11009   }
11010 
11011   // If lookup failed
11012   if (!Info) {
11013     std::string NameForDiags = "std::";
11014     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11015     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11016         << NameForDiags << (int)Usage;
11017     return QualType();
11018   }
11019 
11020   assert(Info->Kind == Kind);
11021   assert(Info->Record);
11022 
11023   // Update the Record decl in case we encountered a forward declaration on our
11024   // first pass. FIXME: This is a bit of a hack.
11025   if (Info->Record->hasDefinition())
11026     Info->Record = Info->Record->getDefinition();
11027 
11028   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11029     return QualType();
11030 
11031   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11032 
11033   if (!Info->Record->isTriviallyCopyable())
11034     return UnsupportedSTLError(USS_NonTrivial);
11035 
11036   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11037     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11038     // Tolerate empty base classes.
11039     if (Base->isEmpty())
11040       continue;
11041     // Reject STL implementations which have at least one non-empty base.
11042     return UnsupportedSTLError();
11043   }
11044 
11045   // Check that the STL has implemented the types using a single integer field.
11046   // This expectation allows better codegen for builtin operators. We require:
11047   //   (1) The class has exactly one field.
11048   //   (2) The field is an integral or enumeration type.
11049   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11050   if (std::distance(FIt, FEnd) != 1 ||
11051       !FIt->getType()->isIntegralOrEnumerationType()) {
11052     return UnsupportedSTLError();
11053   }
11054 
11055   // Build each of the require values and store them in Info.
11056   for (ComparisonCategoryResult CCR :
11057        ComparisonCategories::getPossibleResultsForType(Kind)) {
11058     StringRef MemName = ComparisonCategories::getResultString(CCR);
11059     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11060 
11061     if (!ValInfo)
11062       return UnsupportedSTLError(USS_MissingMember, MemName);
11063 
11064     VarDecl *VD = ValInfo->VD;
11065     assert(VD && "should not be null!");
11066 
11067     // Attempt to diagnose reasons why the STL definition of this type
11068     // might be foobar, including it failing to be a constant expression.
11069     // TODO Handle more ways the lookup or result can be invalid.
11070     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11071         !VD->checkInitIsICE())
11072       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11073 
11074     // Attempt to evaluate the var decl as a constant expression and extract
11075     // the value of its first field as a ICE. If this fails, the STL
11076     // implementation is not supported.
11077     if (!ValInfo->hasValidIntValue())
11078       return UnsupportedSTLError();
11079 
11080     MarkVariableReferenced(Loc, VD);
11081   }
11082 
11083   // We've successfully built the required types and expressions. Update
11084   // the cache and return the newly cached value.
11085   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11086   return Info->getType();
11087 }
11088 
11089 /// Retrieve the special "std" namespace, which may require us to
11090 /// implicitly define the namespace.
11091 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11092   if (!StdNamespace) {
11093     // The "std" namespace has not yet been defined, so build one implicitly.
11094     StdNamespace = NamespaceDecl::Create(Context,
11095                                          Context.getTranslationUnitDecl(),
11096                                          /*Inline=*/false,
11097                                          SourceLocation(), SourceLocation(),
11098                                          &PP.getIdentifierTable().get("std"),
11099                                          /*PrevDecl=*/nullptr);
11100     getStdNamespace()->setImplicit(true);
11101   }
11102 
11103   return getStdNamespace();
11104 }
11105 
11106 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11107   assert(getLangOpts().CPlusPlus &&
11108          "Looking for std::initializer_list outside of C++.");
11109 
11110   // We're looking for implicit instantiations of
11111   // template <typename E> class std::initializer_list.
11112 
11113   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11114     return false;
11115 
11116   ClassTemplateDecl *Template = nullptr;
11117   const TemplateArgument *Arguments = nullptr;
11118 
11119   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11120 
11121     ClassTemplateSpecializationDecl *Specialization =
11122         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11123     if (!Specialization)
11124       return false;
11125 
11126     Template = Specialization->getSpecializedTemplate();
11127     Arguments = Specialization->getTemplateArgs().data();
11128   } else if (const TemplateSpecializationType *TST =
11129                  Ty->getAs<TemplateSpecializationType>()) {
11130     Template = dyn_cast_or_null<ClassTemplateDecl>(
11131         TST->getTemplateName().getAsTemplateDecl());
11132     Arguments = TST->getArgs();
11133   }
11134   if (!Template)
11135     return false;
11136 
11137   if (!StdInitializerList) {
11138     // Haven't recognized std::initializer_list yet, maybe this is it.
11139     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11140     if (TemplateClass->getIdentifier() !=
11141             &PP.getIdentifierTable().get("initializer_list") ||
11142         !getStdNamespace()->InEnclosingNamespaceSetOf(
11143             TemplateClass->getDeclContext()))
11144       return false;
11145     // This is a template called std::initializer_list, but is it the right
11146     // template?
11147     TemplateParameterList *Params = Template->getTemplateParameters();
11148     if (Params->getMinRequiredArguments() != 1)
11149       return false;
11150     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11151       return false;
11152 
11153     // It's the right template.
11154     StdInitializerList = Template;
11155   }
11156 
11157   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11158     return false;
11159 
11160   // This is an instance of std::initializer_list. Find the argument type.
11161   if (Element)
11162     *Element = Arguments[0].getAsType();
11163   return true;
11164 }
11165 
11166 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11167   NamespaceDecl *Std = S.getStdNamespace();
11168   if (!Std) {
11169     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11170     return nullptr;
11171   }
11172 
11173   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11174                       Loc, Sema::LookupOrdinaryName);
11175   if (!S.LookupQualifiedName(Result, Std)) {
11176     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11177     return nullptr;
11178   }
11179   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11180   if (!Template) {
11181     Result.suppressDiagnostics();
11182     // We found something weird. Complain about the first thing we found.
11183     NamedDecl *Found = *Result.begin();
11184     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11185     return nullptr;
11186   }
11187 
11188   // We found some template called std::initializer_list. Now verify that it's
11189   // correct.
11190   TemplateParameterList *Params = Template->getTemplateParameters();
11191   if (Params->getMinRequiredArguments() != 1 ||
11192       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11193     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11194     return nullptr;
11195   }
11196 
11197   return Template;
11198 }
11199 
11200 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11201   if (!StdInitializerList) {
11202     StdInitializerList = LookupStdInitializerList(*this, Loc);
11203     if (!StdInitializerList)
11204       return QualType();
11205   }
11206 
11207   TemplateArgumentListInfo Args(Loc, Loc);
11208   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11209                                        Context.getTrivialTypeSourceInfo(Element,
11210                                                                         Loc)));
11211   return Context.getCanonicalType(
11212       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11213 }
11214 
11215 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11216   // C++ [dcl.init.list]p2:
11217   //   A constructor is an initializer-list constructor if its first parameter
11218   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11219   //   std::initializer_list<E> for some type E, and either there are no other
11220   //   parameters or else all other parameters have default arguments.
11221   if (!Ctor->hasOneParamOrDefaultArgs())
11222     return false;
11223 
11224   QualType ArgType = Ctor->getParamDecl(0)->getType();
11225   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11226     ArgType = RT->getPointeeType().getUnqualifiedType();
11227 
11228   return isStdInitializerList(ArgType, nullptr);
11229 }
11230 
11231 /// Determine whether a using statement is in a context where it will be
11232 /// apply in all contexts.
11233 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11234   switch (CurContext->getDeclKind()) {
11235     case Decl::TranslationUnit:
11236       return true;
11237     case Decl::LinkageSpec:
11238       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11239     default:
11240       return false;
11241   }
11242 }
11243 
11244 namespace {
11245 
11246 // Callback to only accept typo corrections that are namespaces.
11247 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11248 public:
11249   bool ValidateCandidate(const TypoCorrection &candidate) override {
11250     if (NamedDecl *ND = candidate.getCorrectionDecl())
11251       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11252     return false;
11253   }
11254 
11255   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11256     return std::make_unique<NamespaceValidatorCCC>(*this);
11257   }
11258 };
11259 
11260 }
11261 
11262 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11263                                        CXXScopeSpec &SS,
11264                                        SourceLocation IdentLoc,
11265                                        IdentifierInfo *Ident) {
11266   R.clear();
11267   NamespaceValidatorCCC CCC{};
11268   if (TypoCorrection Corrected =
11269           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11270                         Sema::CTK_ErrorRecovery)) {
11271     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11272       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11273       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11274                               Ident->getName().equals(CorrectedStr);
11275       S.diagnoseTypo(Corrected,
11276                      S.PDiag(diag::err_using_directive_member_suggest)
11277                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11278                      S.PDiag(diag::note_namespace_defined_here));
11279     } else {
11280       S.diagnoseTypo(Corrected,
11281                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11282                      S.PDiag(diag::note_namespace_defined_here));
11283     }
11284     R.addDecl(Corrected.getFoundDecl());
11285     return true;
11286   }
11287   return false;
11288 }
11289 
11290 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11291                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11292                                 SourceLocation IdentLoc,
11293                                 IdentifierInfo *NamespcName,
11294                                 const ParsedAttributesView &AttrList) {
11295   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11296   assert(NamespcName && "Invalid NamespcName.");
11297   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11298 
11299   // This can only happen along a recovery path.
11300   while (S->isTemplateParamScope())
11301     S = S->getParent();
11302   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11303 
11304   UsingDirectiveDecl *UDir = nullptr;
11305   NestedNameSpecifier *Qualifier = nullptr;
11306   if (SS.isSet())
11307     Qualifier = SS.getScopeRep();
11308 
11309   // Lookup namespace name.
11310   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11311   LookupParsedName(R, S, &SS);
11312   if (R.isAmbiguous())
11313     return nullptr;
11314 
11315   if (R.empty()) {
11316     R.clear();
11317     // Allow "using namespace std;" or "using namespace ::std;" even if
11318     // "std" hasn't been defined yet, for GCC compatibility.
11319     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11320         NamespcName->isStr("std")) {
11321       Diag(IdentLoc, diag::ext_using_undefined_std);
11322       R.addDecl(getOrCreateStdNamespace());
11323       R.resolveKind();
11324     }
11325     // Otherwise, attempt typo correction.
11326     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11327   }
11328 
11329   if (!R.empty()) {
11330     NamedDecl *Named = R.getRepresentativeDecl();
11331     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11332     assert(NS && "expected namespace decl");
11333 
11334     // The use of a nested name specifier may trigger deprecation warnings.
11335     DiagnoseUseOfDecl(Named, IdentLoc);
11336 
11337     // C++ [namespace.udir]p1:
11338     //   A using-directive specifies that the names in the nominated
11339     //   namespace can be used in the scope in which the
11340     //   using-directive appears after the using-directive. During
11341     //   unqualified name lookup (3.4.1), the names appear as if they
11342     //   were declared in the nearest enclosing namespace which
11343     //   contains both the using-directive and the nominated
11344     //   namespace. [Note: in this context, "contains" means "contains
11345     //   directly or indirectly". ]
11346 
11347     // Find enclosing context containing both using-directive and
11348     // nominated namespace.
11349     DeclContext *CommonAncestor = NS;
11350     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11351       CommonAncestor = CommonAncestor->getParent();
11352 
11353     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11354                                       SS.getWithLocInContext(Context),
11355                                       IdentLoc, Named, CommonAncestor);
11356 
11357     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11358         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11359       Diag(IdentLoc, diag::warn_using_directive_in_header);
11360     }
11361 
11362     PushUsingDirective(S, UDir);
11363   } else {
11364     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11365   }
11366 
11367   if (UDir)
11368     ProcessDeclAttributeList(S, UDir, AttrList);
11369 
11370   return UDir;
11371 }
11372 
11373 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11374   // If the scope has an associated entity and the using directive is at
11375   // namespace or translation unit scope, add the UsingDirectiveDecl into
11376   // its lookup structure so qualified name lookup can find it.
11377   DeclContext *Ctx = S->getEntity();
11378   if (Ctx && !Ctx->isFunctionOrMethod())
11379     Ctx->addDecl(UDir);
11380   else
11381     // Otherwise, it is at block scope. The using-directives will affect lookup
11382     // only to the end of the scope.
11383     S->PushUsingDirective(UDir);
11384 }
11385 
11386 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11387                                   SourceLocation UsingLoc,
11388                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11389                                   UnqualifiedId &Name,
11390                                   SourceLocation EllipsisLoc,
11391                                   const ParsedAttributesView &AttrList) {
11392   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11393 
11394   if (SS.isEmpty()) {
11395     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11396     return nullptr;
11397   }
11398 
11399   switch (Name.getKind()) {
11400   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11401   case UnqualifiedIdKind::IK_Identifier:
11402   case UnqualifiedIdKind::IK_OperatorFunctionId:
11403   case UnqualifiedIdKind::IK_LiteralOperatorId:
11404   case UnqualifiedIdKind::IK_ConversionFunctionId:
11405     break;
11406 
11407   case UnqualifiedIdKind::IK_ConstructorName:
11408   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11409     // C++11 inheriting constructors.
11410     Diag(Name.getBeginLoc(),
11411          getLangOpts().CPlusPlus11
11412              ? diag::warn_cxx98_compat_using_decl_constructor
11413              : diag::err_using_decl_constructor)
11414         << SS.getRange();
11415 
11416     if (getLangOpts().CPlusPlus11) break;
11417 
11418     return nullptr;
11419 
11420   case UnqualifiedIdKind::IK_DestructorName:
11421     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11422     return nullptr;
11423 
11424   case UnqualifiedIdKind::IK_TemplateId:
11425     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11426         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11427     return nullptr;
11428 
11429   case UnqualifiedIdKind::IK_DeductionGuideName:
11430     llvm_unreachable("cannot parse qualified deduction guide name");
11431   }
11432 
11433   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11434   DeclarationName TargetName = TargetNameInfo.getName();
11435   if (!TargetName)
11436     return nullptr;
11437 
11438   // Warn about access declarations.
11439   if (UsingLoc.isInvalid()) {
11440     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11441                                  ? diag::err_access_decl
11442                                  : diag::warn_access_decl_deprecated)
11443         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11444   }
11445 
11446   if (EllipsisLoc.isInvalid()) {
11447     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11448         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11449       return nullptr;
11450   } else {
11451     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11452         !TargetNameInfo.containsUnexpandedParameterPack()) {
11453       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11454         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11455       EllipsisLoc = SourceLocation();
11456     }
11457   }
11458 
11459   NamedDecl *UD =
11460       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11461                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11462                             /*IsInstantiation*/false);
11463   if (UD)
11464     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11465 
11466   return UD;
11467 }
11468 
11469 /// Determine whether a using declaration considers the given
11470 /// declarations as "equivalent", e.g., if they are redeclarations of
11471 /// the same entity or are both typedefs of the same type.
11472 static bool
11473 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11474   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11475     return true;
11476 
11477   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11478     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11479       return Context.hasSameType(TD1->getUnderlyingType(),
11480                                  TD2->getUnderlyingType());
11481 
11482   return false;
11483 }
11484 
11485 
11486 /// Determines whether to create a using shadow decl for a particular
11487 /// decl, given the set of decls existing prior to this using lookup.
11488 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11489                                 const LookupResult &Previous,
11490                                 UsingShadowDecl *&PrevShadow) {
11491   // Diagnose finding a decl which is not from a base class of the
11492   // current class.  We do this now because there are cases where this
11493   // function will silently decide not to build a shadow decl, which
11494   // will pre-empt further diagnostics.
11495   //
11496   // We don't need to do this in C++11 because we do the check once on
11497   // the qualifier.
11498   //
11499   // FIXME: diagnose the following if we care enough:
11500   //   struct A { int foo; };
11501   //   struct B : A { using A::foo; };
11502   //   template <class T> struct C : A {};
11503   //   template <class T> struct D : C<T> { using B::foo; } // <---
11504   // This is invalid (during instantiation) in C++03 because B::foo
11505   // resolves to the using decl in B, which is not a base class of D<T>.
11506   // We can't diagnose it immediately because C<T> is an unknown
11507   // specialization.  The UsingShadowDecl in D<T> then points directly
11508   // to A::foo, which will look well-formed when we instantiate.
11509   // The right solution is to not collapse the shadow-decl chain.
11510   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11511     DeclContext *OrigDC = Orig->getDeclContext();
11512 
11513     // Handle enums and anonymous structs.
11514     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11515     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11516     while (OrigRec->isAnonymousStructOrUnion())
11517       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11518 
11519     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11520       if (OrigDC == CurContext) {
11521         Diag(Using->getLocation(),
11522              diag::err_using_decl_nested_name_specifier_is_current_class)
11523           << Using->getQualifierLoc().getSourceRange();
11524         Diag(Orig->getLocation(), diag::note_using_decl_target);
11525         Using->setInvalidDecl();
11526         return true;
11527       }
11528 
11529       Diag(Using->getQualifierLoc().getBeginLoc(),
11530            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11531         << Using->getQualifier()
11532         << cast<CXXRecordDecl>(CurContext)
11533         << Using->getQualifierLoc().getSourceRange();
11534       Diag(Orig->getLocation(), diag::note_using_decl_target);
11535       Using->setInvalidDecl();
11536       return true;
11537     }
11538   }
11539 
11540   if (Previous.empty()) return false;
11541 
11542   NamedDecl *Target = Orig;
11543   if (isa<UsingShadowDecl>(Target))
11544     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11545 
11546   // If the target happens to be one of the previous declarations, we
11547   // don't have a conflict.
11548   //
11549   // FIXME: but we might be increasing its access, in which case we
11550   // should redeclare it.
11551   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11552   bool FoundEquivalentDecl = false;
11553   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11554          I != E; ++I) {
11555     NamedDecl *D = (*I)->getUnderlyingDecl();
11556     // We can have UsingDecls in our Previous results because we use the same
11557     // LookupResult for checking whether the UsingDecl itself is a valid
11558     // redeclaration.
11559     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11560       continue;
11561 
11562     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11563       // C++ [class.mem]p19:
11564       //   If T is the name of a class, then [every named member other than
11565       //   a non-static data member] shall have a name different from T
11566       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11567           !isa<IndirectFieldDecl>(Target) &&
11568           !isa<UnresolvedUsingValueDecl>(Target) &&
11569           DiagnoseClassNameShadow(
11570               CurContext,
11571               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11572         return true;
11573     }
11574 
11575     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11576       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11577         PrevShadow = Shadow;
11578       FoundEquivalentDecl = true;
11579     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11580       // We don't conflict with an existing using shadow decl of an equivalent
11581       // declaration, but we're not a redeclaration of it.
11582       FoundEquivalentDecl = true;
11583     }
11584 
11585     if (isVisible(D))
11586       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11587   }
11588 
11589   if (FoundEquivalentDecl)
11590     return false;
11591 
11592   if (FunctionDecl *FD = Target->getAsFunction()) {
11593     NamedDecl *OldDecl = nullptr;
11594     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11595                           /*IsForUsingDecl*/ true)) {
11596     case Ovl_Overload:
11597       return false;
11598 
11599     case Ovl_NonFunction:
11600       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11601       break;
11602 
11603     // We found a decl with the exact signature.
11604     case Ovl_Match:
11605       // If we're in a record, we want to hide the target, so we
11606       // return true (without a diagnostic) to tell the caller not to
11607       // build a shadow decl.
11608       if (CurContext->isRecord())
11609         return true;
11610 
11611       // If we're not in a record, this is an error.
11612       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11613       break;
11614     }
11615 
11616     Diag(Target->getLocation(), diag::note_using_decl_target);
11617     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11618     Using->setInvalidDecl();
11619     return true;
11620   }
11621 
11622   // Target is not a function.
11623 
11624   if (isa<TagDecl>(Target)) {
11625     // No conflict between a tag and a non-tag.
11626     if (!Tag) return false;
11627 
11628     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11629     Diag(Target->getLocation(), diag::note_using_decl_target);
11630     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11631     Using->setInvalidDecl();
11632     return true;
11633   }
11634 
11635   // No conflict between a tag and a non-tag.
11636   if (!NonTag) return false;
11637 
11638   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11639   Diag(Target->getLocation(), diag::note_using_decl_target);
11640   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11641   Using->setInvalidDecl();
11642   return true;
11643 }
11644 
11645 /// Determine whether a direct base class is a virtual base class.
11646 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11647   if (!Derived->getNumVBases())
11648     return false;
11649   for (auto &B : Derived->bases())
11650     if (B.getType()->getAsCXXRecordDecl() == Base)
11651       return B.isVirtual();
11652   llvm_unreachable("not a direct base class");
11653 }
11654 
11655 /// Builds a shadow declaration corresponding to a 'using' declaration.
11656 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11657                                             UsingDecl *UD,
11658                                             NamedDecl *Orig,
11659                                             UsingShadowDecl *PrevDecl) {
11660   // If we resolved to another shadow declaration, just coalesce them.
11661   NamedDecl *Target = Orig;
11662   if (isa<UsingShadowDecl>(Target)) {
11663     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11664     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11665   }
11666 
11667   NamedDecl *NonTemplateTarget = Target;
11668   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11669     NonTemplateTarget = TargetTD->getTemplatedDecl();
11670 
11671   UsingShadowDecl *Shadow;
11672   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11673     bool IsVirtualBase =
11674         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11675                             UD->getQualifier()->getAsRecordDecl());
11676     Shadow = ConstructorUsingShadowDecl::Create(
11677         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11678   } else {
11679     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11680                                      Target);
11681   }
11682   UD->addShadowDecl(Shadow);
11683 
11684   Shadow->setAccess(UD->getAccess());
11685   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11686     Shadow->setInvalidDecl();
11687 
11688   Shadow->setPreviousDecl(PrevDecl);
11689 
11690   if (S)
11691     PushOnScopeChains(Shadow, S);
11692   else
11693     CurContext->addDecl(Shadow);
11694 
11695 
11696   return Shadow;
11697 }
11698 
11699 /// Hides a using shadow declaration.  This is required by the current
11700 /// using-decl implementation when a resolvable using declaration in a
11701 /// class is followed by a declaration which would hide or override
11702 /// one or more of the using decl's targets; for example:
11703 ///
11704 ///   struct Base { void foo(int); };
11705 ///   struct Derived : Base {
11706 ///     using Base::foo;
11707 ///     void foo(int);
11708 ///   };
11709 ///
11710 /// The governing language is C++03 [namespace.udecl]p12:
11711 ///
11712 ///   When a using-declaration brings names from a base class into a
11713 ///   derived class scope, member functions in the derived class
11714 ///   override and/or hide member functions with the same name and
11715 ///   parameter types in a base class (rather than conflicting).
11716 ///
11717 /// There are two ways to implement this:
11718 ///   (1) optimistically create shadow decls when they're not hidden
11719 ///       by existing declarations, or
11720 ///   (2) don't create any shadow decls (or at least don't make them
11721 ///       visible) until we've fully parsed/instantiated the class.
11722 /// The problem with (1) is that we might have to retroactively remove
11723 /// a shadow decl, which requires several O(n) operations because the
11724 /// decl structures are (very reasonably) not designed for removal.
11725 /// (2) avoids this but is very fiddly and phase-dependent.
11726 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11727   if (Shadow->getDeclName().getNameKind() ==
11728         DeclarationName::CXXConversionFunctionName)
11729     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11730 
11731   // Remove it from the DeclContext...
11732   Shadow->getDeclContext()->removeDecl(Shadow);
11733 
11734   // ...and the scope, if applicable...
11735   if (S) {
11736     S->RemoveDecl(Shadow);
11737     IdResolver.RemoveDecl(Shadow);
11738   }
11739 
11740   // ...and the using decl.
11741   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11742 
11743   // TODO: complain somehow if Shadow was used.  It shouldn't
11744   // be possible for this to happen, because...?
11745 }
11746 
11747 /// Find the base specifier for a base class with the given type.
11748 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11749                                                 QualType DesiredBase,
11750                                                 bool &AnyDependentBases) {
11751   // Check whether the named type is a direct base class.
11752   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11753     .getUnqualifiedType();
11754   for (auto &Base : Derived->bases()) {
11755     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11756     if (CanonicalDesiredBase == BaseType)
11757       return &Base;
11758     if (BaseType->isDependentType())
11759       AnyDependentBases = true;
11760   }
11761   return nullptr;
11762 }
11763 
11764 namespace {
11765 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11766 public:
11767   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11768                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11769       : HasTypenameKeyword(HasTypenameKeyword),
11770         IsInstantiation(IsInstantiation), OldNNS(NNS),
11771         RequireMemberOf(RequireMemberOf) {}
11772 
11773   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11774     NamedDecl *ND = Candidate.getCorrectionDecl();
11775 
11776     // Keywords are not valid here.
11777     if (!ND || isa<NamespaceDecl>(ND))
11778       return false;
11779 
11780     // Completely unqualified names are invalid for a 'using' declaration.
11781     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11782       return false;
11783 
11784     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11785     // reject.
11786 
11787     if (RequireMemberOf) {
11788       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11789       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11790         // No-one ever wants a using-declaration to name an injected-class-name
11791         // of a base class, unless they're declaring an inheriting constructor.
11792         ASTContext &Ctx = ND->getASTContext();
11793         if (!Ctx.getLangOpts().CPlusPlus11)
11794           return false;
11795         QualType FoundType = Ctx.getRecordType(FoundRecord);
11796 
11797         // Check that the injected-class-name is named as a member of its own
11798         // type; we don't want to suggest 'using Derived::Base;', since that
11799         // means something else.
11800         NestedNameSpecifier *Specifier =
11801             Candidate.WillReplaceSpecifier()
11802                 ? Candidate.getCorrectionSpecifier()
11803                 : OldNNS;
11804         if (!Specifier->getAsType() ||
11805             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11806           return false;
11807 
11808         // Check that this inheriting constructor declaration actually names a
11809         // direct base class of the current class.
11810         bool AnyDependentBases = false;
11811         if (!findDirectBaseWithType(RequireMemberOf,
11812                                     Ctx.getRecordType(FoundRecord),
11813                                     AnyDependentBases) &&
11814             !AnyDependentBases)
11815           return false;
11816       } else {
11817         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11818         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11819           return false;
11820 
11821         // FIXME: Check that the base class member is accessible?
11822       }
11823     } else {
11824       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11825       if (FoundRecord && FoundRecord->isInjectedClassName())
11826         return false;
11827     }
11828 
11829     if (isa<TypeDecl>(ND))
11830       return HasTypenameKeyword || !IsInstantiation;
11831 
11832     return !HasTypenameKeyword;
11833   }
11834 
11835   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11836     return std::make_unique<UsingValidatorCCC>(*this);
11837   }
11838 
11839 private:
11840   bool HasTypenameKeyword;
11841   bool IsInstantiation;
11842   NestedNameSpecifier *OldNNS;
11843   CXXRecordDecl *RequireMemberOf;
11844 };
11845 } // end anonymous namespace
11846 
11847 /// Builds a using declaration.
11848 ///
11849 /// \param IsInstantiation - Whether this call arises from an
11850 ///   instantiation of an unresolved using declaration.  We treat
11851 ///   the lookup differently for these declarations.
11852 NamedDecl *Sema::BuildUsingDeclaration(
11853     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11854     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11855     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11856     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11857   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11858   SourceLocation IdentLoc = NameInfo.getLoc();
11859   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11860 
11861   // FIXME: We ignore attributes for now.
11862 
11863   // For an inheriting constructor declaration, the name of the using
11864   // declaration is the name of a constructor in this class, not in the
11865   // base class.
11866   DeclarationNameInfo UsingName = NameInfo;
11867   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11868     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11869       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11870           Context.getCanonicalType(Context.getRecordType(RD))));
11871 
11872   // Do the redeclaration lookup in the current scope.
11873   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11874                         ForVisibleRedeclaration);
11875   Previous.setHideTags(false);
11876   if (S) {
11877     LookupName(Previous, S);
11878 
11879     // It is really dumb that we have to do this.
11880     LookupResult::Filter F = Previous.makeFilter();
11881     while (F.hasNext()) {
11882       NamedDecl *D = F.next();
11883       if (!isDeclInScope(D, CurContext, S))
11884         F.erase();
11885       // If we found a local extern declaration that's not ordinarily visible,
11886       // and this declaration is being added to a non-block scope, ignore it.
11887       // We're only checking for scope conflicts here, not also for violations
11888       // of the linkage rules.
11889       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11890                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11891         F.erase();
11892     }
11893     F.done();
11894   } else {
11895     assert(IsInstantiation && "no scope in non-instantiation");
11896     if (CurContext->isRecord())
11897       LookupQualifiedName(Previous, CurContext);
11898     else {
11899       // No redeclaration check is needed here; in non-member contexts we
11900       // diagnosed all possible conflicts with other using-declarations when
11901       // building the template:
11902       //
11903       // For a dependent non-type using declaration, the only valid case is
11904       // if we instantiate to a single enumerator. We check for conflicts
11905       // between shadow declarations we introduce, and we check in the template
11906       // definition for conflicts between a non-type using declaration and any
11907       // other declaration, which together covers all cases.
11908       //
11909       // A dependent typename using declaration will never successfully
11910       // instantiate, since it will always name a class member, so we reject
11911       // that in the template definition.
11912     }
11913   }
11914 
11915   // Check for invalid redeclarations.
11916   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11917                                   SS, IdentLoc, Previous))
11918     return nullptr;
11919 
11920   // Check for bad qualifiers.
11921   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11922                               IdentLoc))
11923     return nullptr;
11924 
11925   DeclContext *LookupContext = computeDeclContext(SS);
11926   NamedDecl *D;
11927   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11928   if (!LookupContext || EllipsisLoc.isValid()) {
11929     if (HasTypenameKeyword) {
11930       // FIXME: not all declaration name kinds are legal here
11931       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11932                                               UsingLoc, TypenameLoc,
11933                                               QualifierLoc,
11934                                               IdentLoc, NameInfo.getName(),
11935                                               EllipsisLoc);
11936     } else {
11937       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11938                                            QualifierLoc, NameInfo, EllipsisLoc);
11939     }
11940     D->setAccess(AS);
11941     CurContext->addDecl(D);
11942     return D;
11943   }
11944 
11945   auto Build = [&](bool Invalid) {
11946     UsingDecl *UD =
11947         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11948                           UsingName, HasTypenameKeyword);
11949     UD->setAccess(AS);
11950     CurContext->addDecl(UD);
11951     UD->setInvalidDecl(Invalid);
11952     return UD;
11953   };
11954   auto BuildInvalid = [&]{ return Build(true); };
11955   auto BuildValid = [&]{ return Build(false); };
11956 
11957   if (RequireCompleteDeclContext(SS, LookupContext))
11958     return BuildInvalid();
11959 
11960   // Look up the target name.
11961   LookupResult R(*this, NameInfo, LookupOrdinaryName);
11962 
11963   // Unlike most lookups, we don't always want to hide tag
11964   // declarations: tag names are visible through the using declaration
11965   // even if hidden by ordinary names, *except* in a dependent context
11966   // where it's important for the sanity of two-phase lookup.
11967   if (!IsInstantiation)
11968     R.setHideTags(false);
11969 
11970   // For the purposes of this lookup, we have a base object type
11971   // equal to that of the current context.
11972   if (CurContext->isRecord()) {
11973     R.setBaseObjectType(
11974                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
11975   }
11976 
11977   LookupQualifiedName(R, LookupContext);
11978 
11979   // Try to correct typos if possible. If constructor name lookup finds no
11980   // results, that means the named class has no explicit constructors, and we
11981   // suppressed declaring implicit ones (probably because it's dependent or
11982   // invalid).
11983   if (R.empty() &&
11984       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
11985     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
11986     // it will believe that glibc provides a ::gets in cases where it does not,
11987     // and will try to pull it into namespace std with a using-declaration.
11988     // Just ignore the using-declaration in that case.
11989     auto *II = NameInfo.getName().getAsIdentifierInfo();
11990     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
11991         CurContext->isStdNamespace() &&
11992         isa<TranslationUnitDecl>(LookupContext) &&
11993         getSourceManager().isInSystemHeader(UsingLoc))
11994       return nullptr;
11995     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
11996                           dyn_cast<CXXRecordDecl>(CurContext));
11997     if (TypoCorrection Corrected =
11998             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
11999                         CTK_ErrorRecovery)) {
12000       // We reject candidates where DroppedSpecifier == true, hence the
12001       // literal '0' below.
12002       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12003                                 << NameInfo.getName() << LookupContext << 0
12004                                 << SS.getRange());
12005 
12006       // If we picked a correction with no attached Decl we can't do anything
12007       // useful with it, bail out.
12008       NamedDecl *ND = Corrected.getCorrectionDecl();
12009       if (!ND)
12010         return BuildInvalid();
12011 
12012       // If we corrected to an inheriting constructor, handle it as one.
12013       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12014       if (RD && RD->isInjectedClassName()) {
12015         // The parent of the injected class name is the class itself.
12016         RD = cast<CXXRecordDecl>(RD->getParent());
12017 
12018         // Fix up the information we'll use to build the using declaration.
12019         if (Corrected.WillReplaceSpecifier()) {
12020           NestedNameSpecifierLocBuilder Builder;
12021           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12022                               QualifierLoc.getSourceRange());
12023           QualifierLoc = Builder.getWithLocInContext(Context);
12024         }
12025 
12026         // In this case, the name we introduce is the name of a derived class
12027         // constructor.
12028         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12029         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12030             Context.getCanonicalType(Context.getRecordType(CurClass))));
12031         UsingName.setNamedTypeInfo(nullptr);
12032         for (auto *Ctor : LookupConstructors(RD))
12033           R.addDecl(Ctor);
12034         R.resolveKind();
12035       } else {
12036         // FIXME: Pick up all the declarations if we found an overloaded
12037         // function.
12038         UsingName.setName(ND->getDeclName());
12039         R.addDecl(ND);
12040       }
12041     } else {
12042       Diag(IdentLoc, diag::err_no_member)
12043         << NameInfo.getName() << LookupContext << SS.getRange();
12044       return BuildInvalid();
12045     }
12046   }
12047 
12048   if (R.isAmbiguous())
12049     return BuildInvalid();
12050 
12051   if (HasTypenameKeyword) {
12052     // If we asked for a typename and got a non-type decl, error out.
12053     if (!R.getAsSingle<TypeDecl>()) {
12054       Diag(IdentLoc, diag::err_using_typename_non_type);
12055       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12056         Diag((*I)->getUnderlyingDecl()->getLocation(),
12057              diag::note_using_decl_target);
12058       return BuildInvalid();
12059     }
12060   } else {
12061     // If we asked for a non-typename and we got a type, error out,
12062     // but only if this is an instantiation of an unresolved using
12063     // decl.  Otherwise just silently find the type name.
12064     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12065       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12066       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12067       return BuildInvalid();
12068     }
12069   }
12070 
12071   // C++14 [namespace.udecl]p6:
12072   // A using-declaration shall not name a namespace.
12073   if (R.getAsSingle<NamespaceDecl>()) {
12074     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12075       << SS.getRange();
12076     return BuildInvalid();
12077   }
12078 
12079   // C++14 [namespace.udecl]p7:
12080   // A using-declaration shall not name a scoped enumerator.
12081   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12082     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12083       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12084         << SS.getRange();
12085       return BuildInvalid();
12086     }
12087   }
12088 
12089   UsingDecl *UD = BuildValid();
12090 
12091   // Some additional rules apply to inheriting constructors.
12092   if (UsingName.getName().getNameKind() ==
12093         DeclarationName::CXXConstructorName) {
12094     // Suppress access diagnostics; the access check is instead performed at the
12095     // point of use for an inheriting constructor.
12096     R.suppressDiagnostics();
12097     if (CheckInheritingConstructorUsingDecl(UD))
12098       return UD;
12099   }
12100 
12101   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12102     UsingShadowDecl *PrevDecl = nullptr;
12103     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12104       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12105   }
12106 
12107   return UD;
12108 }
12109 
12110 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12111                                     ArrayRef<NamedDecl *> Expansions) {
12112   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12113          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12114          isa<UsingPackDecl>(InstantiatedFrom));
12115 
12116   auto *UPD =
12117       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12118   UPD->setAccess(InstantiatedFrom->getAccess());
12119   CurContext->addDecl(UPD);
12120   return UPD;
12121 }
12122 
12123 /// Additional checks for a using declaration referring to a constructor name.
12124 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12125   assert(!UD->hasTypename() && "expecting a constructor name");
12126 
12127   const Type *SourceType = UD->getQualifier()->getAsType();
12128   assert(SourceType &&
12129          "Using decl naming constructor doesn't have type in scope spec.");
12130   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12131 
12132   // Check whether the named type is a direct base class.
12133   bool AnyDependentBases = false;
12134   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12135                                       AnyDependentBases);
12136   if (!Base && !AnyDependentBases) {
12137     Diag(UD->getUsingLoc(),
12138          diag::err_using_decl_constructor_not_in_direct_base)
12139       << UD->getNameInfo().getSourceRange()
12140       << QualType(SourceType, 0) << TargetClass;
12141     UD->setInvalidDecl();
12142     return true;
12143   }
12144 
12145   if (Base)
12146     Base->setInheritConstructors();
12147 
12148   return false;
12149 }
12150 
12151 /// Checks that the given using declaration is not an invalid
12152 /// redeclaration.  Note that this is checking only for the using decl
12153 /// itself, not for any ill-formedness among the UsingShadowDecls.
12154 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12155                                        bool HasTypenameKeyword,
12156                                        const CXXScopeSpec &SS,
12157                                        SourceLocation NameLoc,
12158                                        const LookupResult &Prev) {
12159   NestedNameSpecifier *Qual = SS.getScopeRep();
12160 
12161   // C++03 [namespace.udecl]p8:
12162   // C++0x [namespace.udecl]p10:
12163   //   A using-declaration is a declaration and can therefore be used
12164   //   repeatedly where (and only where) multiple declarations are
12165   //   allowed.
12166   //
12167   // That's in non-member contexts.
12168   if (!CurContext->getRedeclContext()->isRecord()) {
12169     // A dependent qualifier outside a class can only ever resolve to an
12170     // enumeration type. Therefore it conflicts with any other non-type
12171     // declaration in the same scope.
12172     // FIXME: How should we check for dependent type-type conflicts at block
12173     // scope?
12174     if (Qual->isDependent() && !HasTypenameKeyword) {
12175       for (auto *D : Prev) {
12176         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12177           bool OldCouldBeEnumerator =
12178               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12179           Diag(NameLoc,
12180                OldCouldBeEnumerator ? diag::err_redefinition
12181                                     : diag::err_redefinition_different_kind)
12182               << Prev.getLookupName();
12183           Diag(D->getLocation(), diag::note_previous_definition);
12184           return true;
12185         }
12186       }
12187     }
12188     return false;
12189   }
12190 
12191   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12192     NamedDecl *D = *I;
12193 
12194     bool DTypename;
12195     NestedNameSpecifier *DQual;
12196     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12197       DTypename = UD->hasTypename();
12198       DQual = UD->getQualifier();
12199     } else if (UnresolvedUsingValueDecl *UD
12200                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12201       DTypename = false;
12202       DQual = UD->getQualifier();
12203     } else if (UnresolvedUsingTypenameDecl *UD
12204                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12205       DTypename = true;
12206       DQual = UD->getQualifier();
12207     } else continue;
12208 
12209     // using decls differ if one says 'typename' and the other doesn't.
12210     // FIXME: non-dependent using decls?
12211     if (HasTypenameKeyword != DTypename) continue;
12212 
12213     // using decls differ if they name different scopes (but note that
12214     // template instantiation can cause this check to trigger when it
12215     // didn't before instantiation).
12216     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12217         Context.getCanonicalNestedNameSpecifier(DQual))
12218       continue;
12219 
12220     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12221     Diag(D->getLocation(), diag::note_using_decl) << 1;
12222     return true;
12223   }
12224 
12225   return false;
12226 }
12227 
12228 
12229 /// Checks that the given nested-name qualifier used in a using decl
12230 /// in the current context is appropriately related to the current
12231 /// scope.  If an error is found, diagnoses it and returns true.
12232 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12233                                    bool HasTypename,
12234                                    const CXXScopeSpec &SS,
12235                                    const DeclarationNameInfo &NameInfo,
12236                                    SourceLocation NameLoc) {
12237   DeclContext *NamedContext = computeDeclContext(SS);
12238 
12239   if (!CurContext->isRecord()) {
12240     // C++03 [namespace.udecl]p3:
12241     // C++0x [namespace.udecl]p8:
12242     //   A using-declaration for a class member shall be a member-declaration.
12243 
12244     // If we weren't able to compute a valid scope, it might validly be a
12245     // dependent class scope or a dependent enumeration unscoped scope. If
12246     // we have a 'typename' keyword, the scope must resolve to a class type.
12247     if ((HasTypename && !NamedContext) ||
12248         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12249       auto *RD = NamedContext
12250                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12251                      : nullptr;
12252       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12253         RD = nullptr;
12254 
12255       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12256         << SS.getRange();
12257 
12258       // If we have a complete, non-dependent source type, try to suggest a
12259       // way to get the same effect.
12260       if (!RD)
12261         return true;
12262 
12263       // Find what this using-declaration was referring to.
12264       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12265       R.setHideTags(false);
12266       R.suppressDiagnostics();
12267       LookupQualifiedName(R, RD);
12268 
12269       if (R.getAsSingle<TypeDecl>()) {
12270         if (getLangOpts().CPlusPlus11) {
12271           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12272           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12273             << 0 // alias declaration
12274             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12275                                           NameInfo.getName().getAsString() +
12276                                               " = ");
12277         } else {
12278           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12279           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12280           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12281             << 1 // typedef declaration
12282             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12283             << FixItHint::CreateInsertion(
12284                    InsertLoc, " " + NameInfo.getName().getAsString());
12285         }
12286       } else if (R.getAsSingle<VarDecl>()) {
12287         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12288         // repeating the type of the static data member here.
12289         FixItHint FixIt;
12290         if (getLangOpts().CPlusPlus11) {
12291           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12292           FixIt = FixItHint::CreateReplacement(
12293               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12294         }
12295 
12296         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12297           << 2 // reference declaration
12298           << FixIt;
12299       } else if (R.getAsSingle<EnumConstantDecl>()) {
12300         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12301         // repeating the type of the enumeration here, and we can't do so if
12302         // the type is anonymous.
12303         FixItHint FixIt;
12304         if (getLangOpts().CPlusPlus11) {
12305           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12306           FixIt = FixItHint::CreateReplacement(
12307               UsingLoc,
12308               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12309         }
12310 
12311         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12312           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12313           << FixIt;
12314       }
12315       return true;
12316     }
12317 
12318     // Otherwise, this might be valid.
12319     return false;
12320   }
12321 
12322   // The current scope is a record.
12323 
12324   // If the named context is dependent, we can't decide much.
12325   if (!NamedContext) {
12326     // FIXME: in C++0x, we can diagnose if we can prove that the
12327     // nested-name-specifier does not refer to a base class, which is
12328     // still possible in some cases.
12329 
12330     // Otherwise we have to conservatively report that things might be
12331     // okay.
12332     return false;
12333   }
12334 
12335   if (!NamedContext->isRecord()) {
12336     // Ideally this would point at the last name in the specifier,
12337     // but we don't have that level of source info.
12338     Diag(SS.getRange().getBegin(),
12339          diag::err_using_decl_nested_name_specifier_is_not_class)
12340       << SS.getScopeRep() << SS.getRange();
12341     return true;
12342   }
12343 
12344   if (!NamedContext->isDependentContext() &&
12345       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12346     return true;
12347 
12348   if (getLangOpts().CPlusPlus11) {
12349     // C++11 [namespace.udecl]p3:
12350     //   In a using-declaration used as a member-declaration, the
12351     //   nested-name-specifier shall name a base class of the class
12352     //   being defined.
12353 
12354     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12355                                  cast<CXXRecordDecl>(NamedContext))) {
12356       if (CurContext == NamedContext) {
12357         Diag(NameLoc,
12358              diag::err_using_decl_nested_name_specifier_is_current_class)
12359           << SS.getRange();
12360         return true;
12361       }
12362 
12363       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12364         Diag(SS.getRange().getBegin(),
12365              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12366           << SS.getScopeRep()
12367           << cast<CXXRecordDecl>(CurContext)
12368           << SS.getRange();
12369       }
12370       return true;
12371     }
12372 
12373     return false;
12374   }
12375 
12376   // C++03 [namespace.udecl]p4:
12377   //   A using-declaration used as a member-declaration shall refer
12378   //   to a member of a base class of the class being defined [etc.].
12379 
12380   // Salient point: SS doesn't have to name a base class as long as
12381   // lookup only finds members from base classes.  Therefore we can
12382   // diagnose here only if we can prove that that can't happen,
12383   // i.e. if the class hierarchies provably don't intersect.
12384 
12385   // TODO: it would be nice if "definitely valid" results were cached
12386   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12387   // need to be repeated.
12388 
12389   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12390   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12391     Bases.insert(Base);
12392     return true;
12393   };
12394 
12395   // Collect all bases. Return false if we find a dependent base.
12396   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12397     return false;
12398 
12399   // Returns true if the base is dependent or is one of the accumulated base
12400   // classes.
12401   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12402     return !Bases.count(Base);
12403   };
12404 
12405   // Return false if the class has a dependent base or if it or one
12406   // of its bases is present in the base set of the current context.
12407   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12408       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12409     return false;
12410 
12411   Diag(SS.getRange().getBegin(),
12412        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12413     << SS.getScopeRep()
12414     << cast<CXXRecordDecl>(CurContext)
12415     << SS.getRange();
12416 
12417   return true;
12418 }
12419 
12420 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12421                                   MultiTemplateParamsArg TemplateParamLists,
12422                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12423                                   const ParsedAttributesView &AttrList,
12424                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12425   // Skip up to the relevant declaration scope.
12426   while (S->isTemplateParamScope())
12427     S = S->getParent();
12428   assert((S->getFlags() & Scope::DeclScope) &&
12429          "got alias-declaration outside of declaration scope");
12430 
12431   if (Type.isInvalid())
12432     return nullptr;
12433 
12434   bool Invalid = false;
12435   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12436   TypeSourceInfo *TInfo = nullptr;
12437   GetTypeFromParser(Type.get(), &TInfo);
12438 
12439   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12440     return nullptr;
12441 
12442   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12443                                       UPPC_DeclarationType)) {
12444     Invalid = true;
12445     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12446                                              TInfo->getTypeLoc().getBeginLoc());
12447   }
12448 
12449   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12450                         TemplateParamLists.size()
12451                             ? forRedeclarationInCurContext()
12452                             : ForVisibleRedeclaration);
12453   LookupName(Previous, S);
12454 
12455   // Warn about shadowing the name of a template parameter.
12456   if (Previous.isSingleResult() &&
12457       Previous.getFoundDecl()->isTemplateParameter()) {
12458     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12459     Previous.clear();
12460   }
12461 
12462   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12463          "name in alias declaration must be an identifier");
12464   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12465                                                Name.StartLocation,
12466                                                Name.Identifier, TInfo);
12467 
12468   NewTD->setAccess(AS);
12469 
12470   if (Invalid)
12471     NewTD->setInvalidDecl();
12472 
12473   ProcessDeclAttributeList(S, NewTD, AttrList);
12474   AddPragmaAttributes(S, NewTD);
12475 
12476   CheckTypedefForVariablyModifiedType(S, NewTD);
12477   Invalid |= NewTD->isInvalidDecl();
12478 
12479   bool Redeclaration = false;
12480 
12481   NamedDecl *NewND;
12482   if (TemplateParamLists.size()) {
12483     TypeAliasTemplateDecl *OldDecl = nullptr;
12484     TemplateParameterList *OldTemplateParams = nullptr;
12485 
12486     if (TemplateParamLists.size() != 1) {
12487       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12488         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12489          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12490     }
12491     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12492 
12493     // Check that we can declare a template here.
12494     if (CheckTemplateDeclScope(S, TemplateParams))
12495       return nullptr;
12496 
12497     // Only consider previous declarations in the same scope.
12498     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12499                          /*ExplicitInstantiationOrSpecialization*/false);
12500     if (!Previous.empty()) {
12501       Redeclaration = true;
12502 
12503       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12504       if (!OldDecl && !Invalid) {
12505         Diag(UsingLoc, diag::err_redefinition_different_kind)
12506           << Name.Identifier;
12507 
12508         NamedDecl *OldD = Previous.getRepresentativeDecl();
12509         if (OldD->getLocation().isValid())
12510           Diag(OldD->getLocation(), diag::note_previous_definition);
12511 
12512         Invalid = true;
12513       }
12514 
12515       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12516         if (TemplateParameterListsAreEqual(TemplateParams,
12517                                            OldDecl->getTemplateParameters(),
12518                                            /*Complain=*/true,
12519                                            TPL_TemplateMatch))
12520           OldTemplateParams =
12521               OldDecl->getMostRecentDecl()->getTemplateParameters();
12522         else
12523           Invalid = true;
12524 
12525         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12526         if (!Invalid &&
12527             !Context.hasSameType(OldTD->getUnderlyingType(),
12528                                  NewTD->getUnderlyingType())) {
12529           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12530           // but we can't reasonably accept it.
12531           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12532             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12533           if (OldTD->getLocation().isValid())
12534             Diag(OldTD->getLocation(), diag::note_previous_definition);
12535           Invalid = true;
12536         }
12537       }
12538     }
12539 
12540     // Merge any previous default template arguments into our parameters,
12541     // and check the parameter list.
12542     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12543                                    TPC_TypeAliasTemplate))
12544       return nullptr;
12545 
12546     TypeAliasTemplateDecl *NewDecl =
12547       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12548                                     Name.Identifier, TemplateParams,
12549                                     NewTD);
12550     NewTD->setDescribedAliasTemplate(NewDecl);
12551 
12552     NewDecl->setAccess(AS);
12553 
12554     if (Invalid)
12555       NewDecl->setInvalidDecl();
12556     else if (OldDecl) {
12557       NewDecl->setPreviousDecl(OldDecl);
12558       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12559     }
12560 
12561     NewND = NewDecl;
12562   } else {
12563     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12564       setTagNameForLinkagePurposes(TD, NewTD);
12565       handleTagNumbering(TD, S);
12566     }
12567     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12568     NewND = NewTD;
12569   }
12570 
12571   PushOnScopeChains(NewND, S);
12572   ActOnDocumentableDecl(NewND);
12573   return NewND;
12574 }
12575 
12576 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12577                                    SourceLocation AliasLoc,
12578                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12579                                    SourceLocation IdentLoc,
12580                                    IdentifierInfo *Ident) {
12581 
12582   // Lookup the namespace name.
12583   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12584   LookupParsedName(R, S, &SS);
12585 
12586   if (R.isAmbiguous())
12587     return nullptr;
12588 
12589   if (R.empty()) {
12590     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12591       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12592       return nullptr;
12593     }
12594   }
12595   assert(!R.isAmbiguous() && !R.empty());
12596   NamedDecl *ND = R.getRepresentativeDecl();
12597 
12598   // Check if we have a previous declaration with the same name.
12599   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12600                      ForVisibleRedeclaration);
12601   LookupName(PrevR, S);
12602 
12603   // Check we're not shadowing a template parameter.
12604   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12605     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12606     PrevR.clear();
12607   }
12608 
12609   // Filter out any other lookup result from an enclosing scope.
12610   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12611                        /*AllowInlineNamespace*/false);
12612 
12613   // Find the previous declaration and check that we can redeclare it.
12614   NamespaceAliasDecl *Prev = nullptr;
12615   if (PrevR.isSingleResult()) {
12616     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12617     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12618       // We already have an alias with the same name that points to the same
12619       // namespace; check that it matches.
12620       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12621         Prev = AD;
12622       } else if (isVisible(PrevDecl)) {
12623         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12624           << Alias;
12625         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12626           << AD->getNamespace();
12627         return nullptr;
12628       }
12629     } else if (isVisible(PrevDecl)) {
12630       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12631                             ? diag::err_redefinition
12632                             : diag::err_redefinition_different_kind;
12633       Diag(AliasLoc, DiagID) << Alias;
12634       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12635       return nullptr;
12636     }
12637   }
12638 
12639   // The use of a nested name specifier may trigger deprecation warnings.
12640   DiagnoseUseOfDecl(ND, IdentLoc);
12641 
12642   NamespaceAliasDecl *AliasDecl =
12643     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12644                                Alias, SS.getWithLocInContext(Context),
12645                                IdentLoc, ND);
12646   if (Prev)
12647     AliasDecl->setPreviousDecl(Prev);
12648 
12649   PushOnScopeChains(AliasDecl, S);
12650   return AliasDecl;
12651 }
12652 
12653 namespace {
12654 struct SpecialMemberExceptionSpecInfo
12655     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12656   SourceLocation Loc;
12657   Sema::ImplicitExceptionSpecification ExceptSpec;
12658 
12659   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12660                                  Sema::CXXSpecialMember CSM,
12661                                  Sema::InheritedConstructorInfo *ICI,
12662                                  SourceLocation Loc)
12663       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12664 
12665   bool visitBase(CXXBaseSpecifier *Base);
12666   bool visitField(FieldDecl *FD);
12667 
12668   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12669                            unsigned Quals);
12670 
12671   void visitSubobjectCall(Subobject Subobj,
12672                           Sema::SpecialMemberOverloadResult SMOR);
12673 };
12674 }
12675 
12676 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12677   auto *RT = Base->getType()->getAs<RecordType>();
12678   if (!RT)
12679     return false;
12680 
12681   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12682   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12683   if (auto *BaseCtor = SMOR.getMethod()) {
12684     visitSubobjectCall(Base, BaseCtor);
12685     return false;
12686   }
12687 
12688   visitClassSubobject(BaseClass, Base, 0);
12689   return false;
12690 }
12691 
12692 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12693   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12694     Expr *E = FD->getInClassInitializer();
12695     if (!E)
12696       // FIXME: It's a little wasteful to build and throw away a
12697       // CXXDefaultInitExpr here.
12698       // FIXME: We should have a single context note pointing at Loc, and
12699       // this location should be MD->getLocation() instead, since that's
12700       // the location where we actually use the default init expression.
12701       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12702     if (E)
12703       ExceptSpec.CalledExpr(E);
12704   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12705                             ->getAs<RecordType>()) {
12706     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12707                         FD->getType().getCVRQualifiers());
12708   }
12709   return false;
12710 }
12711 
12712 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12713                                                          Subobject Subobj,
12714                                                          unsigned Quals) {
12715   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12716   bool IsMutable = Field && Field->isMutable();
12717   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12718 }
12719 
12720 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12721     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12722   // Note, if lookup fails, it doesn't matter what exception specification we
12723   // choose because the special member will be deleted.
12724   if (CXXMethodDecl *MD = SMOR.getMethod())
12725     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12726 }
12727 
12728 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12729   llvm::APSInt Result;
12730   ExprResult Converted = CheckConvertedConstantExpression(
12731       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12732   ExplicitSpec.setExpr(Converted.get());
12733   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12734     ExplicitSpec.setKind(Result.getBoolValue()
12735                              ? ExplicitSpecKind::ResolvedTrue
12736                              : ExplicitSpecKind::ResolvedFalse);
12737     return true;
12738   }
12739   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12740   return false;
12741 }
12742 
12743 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12744   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12745   if (!ExplicitExpr->isTypeDependent())
12746     tryResolveExplicitSpecifier(ES);
12747   return ES;
12748 }
12749 
12750 static Sema::ImplicitExceptionSpecification
12751 ComputeDefaultedSpecialMemberExceptionSpec(
12752     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12753     Sema::InheritedConstructorInfo *ICI) {
12754   ComputingExceptionSpec CES(S, MD, Loc);
12755 
12756   CXXRecordDecl *ClassDecl = MD->getParent();
12757 
12758   // C++ [except.spec]p14:
12759   //   An implicitly declared special member function (Clause 12) shall have an
12760   //   exception-specification. [...]
12761   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12762   if (ClassDecl->isInvalidDecl())
12763     return Info.ExceptSpec;
12764 
12765   // FIXME: If this diagnostic fires, we're probably missing a check for
12766   // attempting to resolve an exception specification before it's known
12767   // at a higher level.
12768   if (S.RequireCompleteType(MD->getLocation(),
12769                             S.Context.getRecordType(ClassDecl),
12770                             diag::err_exception_spec_incomplete_type))
12771     return Info.ExceptSpec;
12772 
12773   // C++1z [except.spec]p7:
12774   //   [Look for exceptions thrown by] a constructor selected [...] to
12775   //   initialize a potentially constructed subobject,
12776   // C++1z [except.spec]p8:
12777   //   The exception specification for an implicitly-declared destructor, or a
12778   //   destructor without a noexcept-specifier, is potentially-throwing if and
12779   //   only if any of the destructors for any of its potentially constructed
12780   //   subojects is potentially throwing.
12781   // FIXME: We respect the first rule but ignore the "potentially constructed"
12782   // in the second rule to resolve a core issue (no number yet) that would have
12783   // us reject:
12784   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12785   //   struct B : A {};
12786   //   struct C : B { void f(); };
12787   // ... due to giving B::~B() a non-throwing exception specification.
12788   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12789                                 : Info.VisitAllBases);
12790 
12791   return Info.ExceptSpec;
12792 }
12793 
12794 namespace {
12795 /// RAII object to register a special member as being currently declared.
12796 struct DeclaringSpecialMember {
12797   Sema &S;
12798   Sema::SpecialMemberDecl D;
12799   Sema::ContextRAII SavedContext;
12800   bool WasAlreadyBeingDeclared;
12801 
12802   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12803       : S(S), D(RD, CSM), SavedContext(S, RD) {
12804     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12805     if (WasAlreadyBeingDeclared)
12806       // This almost never happens, but if it does, ensure that our cache
12807       // doesn't contain a stale result.
12808       S.SpecialMemberCache.clear();
12809     else {
12810       // Register a note to be produced if we encounter an error while
12811       // declaring the special member.
12812       Sema::CodeSynthesisContext Ctx;
12813       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12814       // FIXME: We don't have a location to use here. Using the class's
12815       // location maintains the fiction that we declare all special members
12816       // with the class, but (1) it's not clear that lying about that helps our
12817       // users understand what's going on, and (2) there may be outer contexts
12818       // on the stack (some of which are relevant) and printing them exposes
12819       // our lies.
12820       Ctx.PointOfInstantiation = RD->getLocation();
12821       Ctx.Entity = RD;
12822       Ctx.SpecialMember = CSM;
12823       S.pushCodeSynthesisContext(Ctx);
12824     }
12825   }
12826   ~DeclaringSpecialMember() {
12827     if (!WasAlreadyBeingDeclared) {
12828       S.SpecialMembersBeingDeclared.erase(D);
12829       S.popCodeSynthesisContext();
12830     }
12831   }
12832 
12833   /// Are we already trying to declare this special member?
12834   bool isAlreadyBeingDeclared() const {
12835     return WasAlreadyBeingDeclared;
12836   }
12837 };
12838 }
12839 
12840 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12841   // Look up any existing declarations, but don't trigger declaration of all
12842   // implicit special members with this name.
12843   DeclarationName Name = FD->getDeclName();
12844   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12845                  ForExternalRedeclaration);
12846   for (auto *D : FD->getParent()->lookup(Name))
12847     if (auto *Acceptable = R.getAcceptableDecl(D))
12848       R.addDecl(Acceptable);
12849   R.resolveKind();
12850   R.suppressDiagnostics();
12851 
12852   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12853 }
12854 
12855 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12856                                           QualType ResultTy,
12857                                           ArrayRef<QualType> Args) {
12858   // Build an exception specification pointing back at this constructor.
12859   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12860 
12861   LangAS AS = getDefaultCXXMethodAddrSpace();
12862   if (AS != LangAS::Default) {
12863     EPI.TypeQuals.addAddressSpace(AS);
12864   }
12865 
12866   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12867   SpecialMem->setType(QT);
12868 }
12869 
12870 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12871                                                      CXXRecordDecl *ClassDecl) {
12872   // C++ [class.ctor]p5:
12873   //   A default constructor for a class X is a constructor of class X
12874   //   that can be called without an argument. If there is no
12875   //   user-declared constructor for class X, a default constructor is
12876   //   implicitly declared. An implicitly-declared default constructor
12877   //   is an inline public member of its class.
12878   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12879          "Should not build implicit default constructor!");
12880 
12881   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12882   if (DSM.isAlreadyBeingDeclared())
12883     return nullptr;
12884 
12885   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12886                                                      CXXDefaultConstructor,
12887                                                      false);
12888 
12889   // Create the actual constructor declaration.
12890   CanQualType ClassType
12891     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12892   SourceLocation ClassLoc = ClassDecl->getLocation();
12893   DeclarationName Name
12894     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12895   DeclarationNameInfo NameInfo(Name, ClassLoc);
12896   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12897       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12898       /*TInfo=*/nullptr, ExplicitSpecifier(),
12899       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12900       Constexpr ? CSK_constexpr : CSK_unspecified);
12901   DefaultCon->setAccess(AS_public);
12902   DefaultCon->setDefaulted();
12903 
12904   if (getLangOpts().CUDA) {
12905     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12906                                             DefaultCon,
12907                                             /* ConstRHS */ false,
12908                                             /* Diagnose */ false);
12909   }
12910 
12911   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12912 
12913   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12914   // constructors is easy to compute.
12915   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12916 
12917   // Note that we have declared this constructor.
12918   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12919 
12920   Scope *S = getScopeForContext(ClassDecl);
12921   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12922 
12923   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12924     SetDeclDeleted(DefaultCon, ClassLoc);
12925 
12926   if (S)
12927     PushOnScopeChains(DefaultCon, S, false);
12928   ClassDecl->addDecl(DefaultCon);
12929 
12930   return DefaultCon;
12931 }
12932 
12933 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12934                                             CXXConstructorDecl *Constructor) {
12935   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12936           !Constructor->doesThisDeclarationHaveABody() &&
12937           !Constructor->isDeleted()) &&
12938     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12939   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12940     return;
12941 
12942   CXXRecordDecl *ClassDecl = Constructor->getParent();
12943   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12944 
12945   SynthesizedFunctionScope Scope(*this, Constructor);
12946 
12947   // The exception specification is needed because we are defining the
12948   // function.
12949   ResolveExceptionSpec(CurrentLocation,
12950                        Constructor->getType()->castAs<FunctionProtoType>());
12951   MarkVTableUsed(CurrentLocation, ClassDecl);
12952 
12953   // Add a context note for diagnostics produced after this point.
12954   Scope.addContextNote(CurrentLocation);
12955 
12956   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12957     Constructor->setInvalidDecl();
12958     return;
12959   }
12960 
12961   SourceLocation Loc = Constructor->getEndLoc().isValid()
12962                            ? Constructor->getEndLoc()
12963                            : Constructor->getLocation();
12964   Constructor->setBody(new (Context) CompoundStmt(Loc));
12965   Constructor->markUsed(Context);
12966 
12967   if (ASTMutationListener *L = getASTMutationListener()) {
12968     L->CompletedImplicitDefinition(Constructor);
12969   }
12970 
12971   DiagnoseUninitializedFields(*this, Constructor);
12972 }
12973 
12974 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
12975   // Perform any delayed checks on exception specifications.
12976   CheckDelayedMemberExceptionSpecs();
12977 }
12978 
12979 /// Find or create the fake constructor we synthesize to model constructing an
12980 /// object of a derived class via a constructor of a base class.
12981 CXXConstructorDecl *
12982 Sema::findInheritingConstructor(SourceLocation Loc,
12983                                 CXXConstructorDecl *BaseCtor,
12984                                 ConstructorUsingShadowDecl *Shadow) {
12985   CXXRecordDecl *Derived = Shadow->getParent();
12986   SourceLocation UsingLoc = Shadow->getLocation();
12987 
12988   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
12989   // For now we use the name of the base class constructor as a member of the
12990   // derived class to indicate a (fake) inherited constructor name.
12991   DeclarationName Name = BaseCtor->getDeclName();
12992 
12993   // Check to see if we already have a fake constructor for this inherited
12994   // constructor call.
12995   for (NamedDecl *Ctor : Derived->lookup(Name))
12996     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
12997                                ->getInheritedConstructor()
12998                                .getConstructor(),
12999                            BaseCtor))
13000       return cast<CXXConstructorDecl>(Ctor);
13001 
13002   DeclarationNameInfo NameInfo(Name, UsingLoc);
13003   TypeSourceInfo *TInfo =
13004       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13005   FunctionProtoTypeLoc ProtoLoc =
13006       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13007 
13008   // Check the inherited constructor is valid and find the list of base classes
13009   // from which it was inherited.
13010   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13011 
13012   bool Constexpr =
13013       BaseCtor->isConstexpr() &&
13014       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13015                                         false, BaseCtor, &ICI);
13016 
13017   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13018       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13019       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13020       /*isImplicitlyDeclared=*/true,
13021       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13022       InheritedConstructor(Shadow, BaseCtor),
13023       BaseCtor->getTrailingRequiresClause());
13024   if (Shadow->isInvalidDecl())
13025     DerivedCtor->setInvalidDecl();
13026 
13027   // Build an unevaluated exception specification for this fake constructor.
13028   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13029   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13030   EPI.ExceptionSpec.Type = EST_Unevaluated;
13031   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13032   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13033                                                FPT->getParamTypes(), EPI));
13034 
13035   // Build the parameter declarations.
13036   SmallVector<ParmVarDecl *, 16> ParamDecls;
13037   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13038     TypeSourceInfo *TInfo =
13039         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13040     ParmVarDecl *PD = ParmVarDecl::Create(
13041         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13042         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13043     PD->setScopeInfo(0, I);
13044     PD->setImplicit();
13045     // Ensure attributes are propagated onto parameters (this matters for
13046     // format, pass_object_size, ...).
13047     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13048     ParamDecls.push_back(PD);
13049     ProtoLoc.setParam(I, PD);
13050   }
13051 
13052   // Set up the new constructor.
13053   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13054   DerivedCtor->setAccess(BaseCtor->getAccess());
13055   DerivedCtor->setParams(ParamDecls);
13056   Derived->addDecl(DerivedCtor);
13057 
13058   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13059     SetDeclDeleted(DerivedCtor, UsingLoc);
13060 
13061   return DerivedCtor;
13062 }
13063 
13064 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13065   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13066                                Ctor->getInheritedConstructor().getShadowDecl());
13067   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13068                             /*Diagnose*/true);
13069 }
13070 
13071 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13072                                        CXXConstructorDecl *Constructor) {
13073   CXXRecordDecl *ClassDecl = Constructor->getParent();
13074   assert(Constructor->getInheritedConstructor() &&
13075          !Constructor->doesThisDeclarationHaveABody() &&
13076          !Constructor->isDeleted());
13077   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13078     return;
13079 
13080   // Initializations are performed "as if by a defaulted default constructor",
13081   // so enter the appropriate scope.
13082   SynthesizedFunctionScope Scope(*this, Constructor);
13083 
13084   // The exception specification is needed because we are defining the
13085   // function.
13086   ResolveExceptionSpec(CurrentLocation,
13087                        Constructor->getType()->castAs<FunctionProtoType>());
13088   MarkVTableUsed(CurrentLocation, ClassDecl);
13089 
13090   // Add a context note for diagnostics produced after this point.
13091   Scope.addContextNote(CurrentLocation);
13092 
13093   ConstructorUsingShadowDecl *Shadow =
13094       Constructor->getInheritedConstructor().getShadowDecl();
13095   CXXConstructorDecl *InheritedCtor =
13096       Constructor->getInheritedConstructor().getConstructor();
13097 
13098   // [class.inhctor.init]p1:
13099   //   initialization proceeds as if a defaulted default constructor is used to
13100   //   initialize the D object and each base class subobject from which the
13101   //   constructor was inherited
13102 
13103   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13104   CXXRecordDecl *RD = Shadow->getParent();
13105   SourceLocation InitLoc = Shadow->getLocation();
13106 
13107   // Build explicit initializers for all base classes from which the
13108   // constructor was inherited.
13109   SmallVector<CXXCtorInitializer*, 8> Inits;
13110   for (bool VBase : {false, true}) {
13111     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13112       if (B.isVirtual() != VBase)
13113         continue;
13114 
13115       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13116       if (!BaseRD)
13117         continue;
13118 
13119       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13120       if (!BaseCtor.first)
13121         continue;
13122 
13123       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13124       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13125           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13126 
13127       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13128       Inits.push_back(new (Context) CXXCtorInitializer(
13129           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13130           SourceLocation()));
13131     }
13132   }
13133 
13134   // We now proceed as if for a defaulted default constructor, with the relevant
13135   // initializers replaced.
13136 
13137   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13138     Constructor->setInvalidDecl();
13139     return;
13140   }
13141 
13142   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13143   Constructor->markUsed(Context);
13144 
13145   if (ASTMutationListener *L = getASTMutationListener()) {
13146     L->CompletedImplicitDefinition(Constructor);
13147   }
13148 
13149   DiagnoseUninitializedFields(*this, Constructor);
13150 }
13151 
13152 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13153   // C++ [class.dtor]p2:
13154   //   If a class has no user-declared destructor, a destructor is
13155   //   declared implicitly. An implicitly-declared destructor is an
13156   //   inline public member of its class.
13157   assert(ClassDecl->needsImplicitDestructor());
13158 
13159   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13160   if (DSM.isAlreadyBeingDeclared())
13161     return nullptr;
13162 
13163   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13164                                                      CXXDestructor,
13165                                                      false);
13166 
13167   // Create the actual destructor declaration.
13168   CanQualType ClassType
13169     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13170   SourceLocation ClassLoc = ClassDecl->getLocation();
13171   DeclarationName Name
13172     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13173   DeclarationNameInfo NameInfo(Name, ClassLoc);
13174   CXXDestructorDecl *Destructor =
13175       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13176                                 QualType(), nullptr, /*isInline=*/true,
13177                                 /*isImplicitlyDeclared=*/true,
13178                                 Constexpr ? CSK_constexpr : CSK_unspecified);
13179   Destructor->setAccess(AS_public);
13180   Destructor->setDefaulted();
13181 
13182   if (getLangOpts().CUDA) {
13183     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13184                                             Destructor,
13185                                             /* ConstRHS */ false,
13186                                             /* Diagnose */ false);
13187   }
13188 
13189   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13190 
13191   // We don't need to use SpecialMemberIsTrivial here; triviality for
13192   // destructors is easy to compute.
13193   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13194   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13195                                 ClassDecl->hasTrivialDestructorForCall());
13196 
13197   // Note that we have declared this destructor.
13198   ++getASTContext().NumImplicitDestructorsDeclared;
13199 
13200   Scope *S = getScopeForContext(ClassDecl);
13201   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13202 
13203   // We can't check whether an implicit destructor is deleted before we complete
13204   // the definition of the class, because its validity depends on the alignment
13205   // of the class. We'll check this from ActOnFields once the class is complete.
13206   if (ClassDecl->isCompleteDefinition() &&
13207       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13208     SetDeclDeleted(Destructor, ClassLoc);
13209 
13210   // Introduce this destructor into its scope.
13211   if (S)
13212     PushOnScopeChains(Destructor, S, false);
13213   ClassDecl->addDecl(Destructor);
13214 
13215   return Destructor;
13216 }
13217 
13218 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13219                                     CXXDestructorDecl *Destructor) {
13220   assert((Destructor->isDefaulted() &&
13221           !Destructor->doesThisDeclarationHaveABody() &&
13222           !Destructor->isDeleted()) &&
13223          "DefineImplicitDestructor - call it for implicit default dtor");
13224   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13225     return;
13226 
13227   CXXRecordDecl *ClassDecl = Destructor->getParent();
13228   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13229 
13230   SynthesizedFunctionScope Scope(*this, Destructor);
13231 
13232   // The exception specification is needed because we are defining the
13233   // function.
13234   ResolveExceptionSpec(CurrentLocation,
13235                        Destructor->getType()->castAs<FunctionProtoType>());
13236   MarkVTableUsed(CurrentLocation, ClassDecl);
13237 
13238   // Add a context note for diagnostics produced after this point.
13239   Scope.addContextNote(CurrentLocation);
13240 
13241   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13242                                          Destructor->getParent());
13243 
13244   if (CheckDestructor(Destructor)) {
13245     Destructor->setInvalidDecl();
13246     return;
13247   }
13248 
13249   SourceLocation Loc = Destructor->getEndLoc().isValid()
13250                            ? Destructor->getEndLoc()
13251                            : Destructor->getLocation();
13252   Destructor->setBody(new (Context) CompoundStmt(Loc));
13253   Destructor->markUsed(Context);
13254 
13255   if (ASTMutationListener *L = getASTMutationListener()) {
13256     L->CompletedImplicitDefinition(Destructor);
13257   }
13258 }
13259 
13260 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13261                                           CXXDestructorDecl *Destructor) {
13262   if (Destructor->isInvalidDecl())
13263     return;
13264 
13265   CXXRecordDecl *ClassDecl = Destructor->getParent();
13266   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13267          "implicit complete dtors unneeded outside MS ABI");
13268   assert(ClassDecl->getNumVBases() > 0 &&
13269          "complete dtor only exists for classes with vbases");
13270 
13271   SynthesizedFunctionScope Scope(*this, Destructor);
13272 
13273   // Add a context note for diagnostics produced after this point.
13274   Scope.addContextNote(CurrentLocation);
13275 
13276   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13277 }
13278 
13279 /// Perform any semantic analysis which needs to be delayed until all
13280 /// pending class member declarations have been parsed.
13281 void Sema::ActOnFinishCXXMemberDecls() {
13282   // If the context is an invalid C++ class, just suppress these checks.
13283   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13284     if (Record->isInvalidDecl()) {
13285       DelayedOverridingExceptionSpecChecks.clear();
13286       DelayedEquivalentExceptionSpecChecks.clear();
13287       return;
13288     }
13289     checkForMultipleExportedDefaultConstructors(*this, Record);
13290   }
13291 }
13292 
13293 void Sema::ActOnFinishCXXNonNestedClass() {
13294   referenceDLLExportedClassMethods();
13295 
13296   if (!DelayedDllExportMemberFunctions.empty()) {
13297     SmallVector<CXXMethodDecl*, 4> WorkList;
13298     std::swap(DelayedDllExportMemberFunctions, WorkList);
13299     for (CXXMethodDecl *M : WorkList) {
13300       DefineDefaultedFunction(*this, M, M->getLocation());
13301 
13302       // Pass the method to the consumer to get emitted. This is not necessary
13303       // for explicit instantiation definitions, as they will get emitted
13304       // anyway.
13305       if (M->getParent()->getTemplateSpecializationKind() !=
13306           TSK_ExplicitInstantiationDefinition)
13307         ActOnFinishInlineFunctionDef(M);
13308     }
13309   }
13310 }
13311 
13312 void Sema::referenceDLLExportedClassMethods() {
13313   if (!DelayedDllExportClasses.empty()) {
13314     // Calling ReferenceDllExportedMembers might cause the current function to
13315     // be called again, so use a local copy of DelayedDllExportClasses.
13316     SmallVector<CXXRecordDecl *, 4> WorkList;
13317     std::swap(DelayedDllExportClasses, WorkList);
13318     for (CXXRecordDecl *Class : WorkList)
13319       ReferenceDllExportedMembers(*this, Class);
13320   }
13321 }
13322 
13323 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13324   assert(getLangOpts().CPlusPlus11 &&
13325          "adjusting dtor exception specs was introduced in c++11");
13326 
13327   if (Destructor->isDependentContext())
13328     return;
13329 
13330   // C++11 [class.dtor]p3:
13331   //   A declaration of a destructor that does not have an exception-
13332   //   specification is implicitly considered to have the same exception-
13333   //   specification as an implicit declaration.
13334   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13335   if (DtorType->hasExceptionSpec())
13336     return;
13337 
13338   // Replace the destructor's type, building off the existing one. Fortunately,
13339   // the only thing of interest in the destructor type is its extended info.
13340   // The return and arguments are fixed.
13341   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13342   EPI.ExceptionSpec.Type = EST_Unevaluated;
13343   EPI.ExceptionSpec.SourceDecl = Destructor;
13344   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13345 
13346   // FIXME: If the destructor has a body that could throw, and the newly created
13347   // spec doesn't allow exceptions, we should emit a warning, because this
13348   // change in behavior can break conforming C++03 programs at runtime.
13349   // However, we don't have a body or an exception specification yet, so it
13350   // needs to be done somewhere else.
13351 }
13352 
13353 namespace {
13354 /// An abstract base class for all helper classes used in building the
13355 //  copy/move operators. These classes serve as factory functions and help us
13356 //  avoid using the same Expr* in the AST twice.
13357 class ExprBuilder {
13358   ExprBuilder(const ExprBuilder&) = delete;
13359   ExprBuilder &operator=(const ExprBuilder&) = delete;
13360 
13361 protected:
13362   static Expr *assertNotNull(Expr *E) {
13363     assert(E && "Expression construction must not fail.");
13364     return E;
13365   }
13366 
13367 public:
13368   ExprBuilder() {}
13369   virtual ~ExprBuilder() {}
13370 
13371   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13372 };
13373 
13374 class RefBuilder: public ExprBuilder {
13375   VarDecl *Var;
13376   QualType VarType;
13377 
13378 public:
13379   Expr *build(Sema &S, SourceLocation Loc) const override {
13380     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13381   }
13382 
13383   RefBuilder(VarDecl *Var, QualType VarType)
13384       : Var(Var), VarType(VarType) {}
13385 };
13386 
13387 class ThisBuilder: public ExprBuilder {
13388 public:
13389   Expr *build(Sema &S, SourceLocation Loc) const override {
13390     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13391   }
13392 };
13393 
13394 class CastBuilder: public ExprBuilder {
13395   const ExprBuilder &Builder;
13396   QualType Type;
13397   ExprValueKind Kind;
13398   const CXXCastPath &Path;
13399 
13400 public:
13401   Expr *build(Sema &S, SourceLocation Loc) const override {
13402     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13403                                              CK_UncheckedDerivedToBase, Kind,
13404                                              &Path).get());
13405   }
13406 
13407   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13408               const CXXCastPath &Path)
13409       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13410 };
13411 
13412 class DerefBuilder: public ExprBuilder {
13413   const ExprBuilder &Builder;
13414 
13415 public:
13416   Expr *build(Sema &S, SourceLocation Loc) const override {
13417     return assertNotNull(
13418         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13419   }
13420 
13421   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13422 };
13423 
13424 class MemberBuilder: public ExprBuilder {
13425   const ExprBuilder &Builder;
13426   QualType Type;
13427   CXXScopeSpec SS;
13428   bool IsArrow;
13429   LookupResult &MemberLookup;
13430 
13431 public:
13432   Expr *build(Sema &S, SourceLocation Loc) const override {
13433     return assertNotNull(S.BuildMemberReferenceExpr(
13434         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13435         nullptr, MemberLookup, nullptr, nullptr).get());
13436   }
13437 
13438   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13439                 LookupResult &MemberLookup)
13440       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13441         MemberLookup(MemberLookup) {}
13442 };
13443 
13444 class MoveCastBuilder: public ExprBuilder {
13445   const ExprBuilder &Builder;
13446 
13447 public:
13448   Expr *build(Sema &S, SourceLocation Loc) const override {
13449     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13450   }
13451 
13452   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13453 };
13454 
13455 class LvalueConvBuilder: public ExprBuilder {
13456   const ExprBuilder &Builder;
13457 
13458 public:
13459   Expr *build(Sema &S, SourceLocation Loc) const override {
13460     return assertNotNull(
13461         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13462   }
13463 
13464   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13465 };
13466 
13467 class SubscriptBuilder: public ExprBuilder {
13468   const ExprBuilder &Base;
13469   const ExprBuilder &Index;
13470 
13471 public:
13472   Expr *build(Sema &S, SourceLocation Loc) const override {
13473     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13474         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13475   }
13476 
13477   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13478       : Base(Base), Index(Index) {}
13479 };
13480 
13481 } // end anonymous namespace
13482 
13483 /// When generating a defaulted copy or move assignment operator, if a field
13484 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13485 /// do so. This optimization only applies for arrays of scalars, and for arrays
13486 /// of class type where the selected copy/move-assignment operator is trivial.
13487 static StmtResult
13488 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13489                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13490   // Compute the size of the memory buffer to be copied.
13491   QualType SizeType = S.Context.getSizeType();
13492   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13493                    S.Context.getTypeSizeInChars(T).getQuantity());
13494 
13495   // Take the address of the field references for "from" and "to". We
13496   // directly construct UnaryOperators here because semantic analysis
13497   // does not permit us to take the address of an xvalue.
13498   Expr *From = FromB.build(S, Loc);
13499   From = UnaryOperator::Create(
13500       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13501       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatures);
13502   Expr *To = ToB.build(S, Loc);
13503   To = UnaryOperator::Create(S.Context, To, UO_AddrOf,
13504                              S.Context.getPointerType(To->getType()), VK_RValue,
13505                              OK_Ordinary, Loc, false, S.CurFPFeatures);
13506 
13507   const Type *E = T->getBaseElementTypeUnsafe();
13508   bool NeedsCollectableMemCpy =
13509       E->isRecordType() &&
13510       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13511 
13512   // Create a reference to the __builtin_objc_memmove_collectable function
13513   StringRef MemCpyName = NeedsCollectableMemCpy ?
13514     "__builtin_objc_memmove_collectable" :
13515     "__builtin_memcpy";
13516   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13517                  Sema::LookupOrdinaryName);
13518   S.LookupName(R, S.TUScope, true);
13519 
13520   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13521   if (!MemCpy)
13522     // Something went horribly wrong earlier, and we will have complained
13523     // about it.
13524     return StmtError();
13525 
13526   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13527                                             VK_RValue, Loc, nullptr);
13528   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13529 
13530   Expr *CallArgs[] = {
13531     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13532   };
13533   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13534                                     Loc, CallArgs, Loc);
13535 
13536   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13537   return Call.getAs<Stmt>();
13538 }
13539 
13540 /// Builds a statement that copies/moves the given entity from \p From to
13541 /// \c To.
13542 ///
13543 /// This routine is used to copy/move the members of a class with an
13544 /// implicitly-declared copy/move assignment operator. When the entities being
13545 /// copied are arrays, this routine builds for loops to copy them.
13546 ///
13547 /// \param S The Sema object used for type-checking.
13548 ///
13549 /// \param Loc The location where the implicit copy/move is being generated.
13550 ///
13551 /// \param T The type of the expressions being copied/moved. Both expressions
13552 /// must have this type.
13553 ///
13554 /// \param To The expression we are copying/moving to.
13555 ///
13556 /// \param From The expression we are copying/moving from.
13557 ///
13558 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13559 /// Otherwise, it's a non-static member subobject.
13560 ///
13561 /// \param Copying Whether we're copying or moving.
13562 ///
13563 /// \param Depth Internal parameter recording the depth of the recursion.
13564 ///
13565 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13566 /// if a memcpy should be used instead.
13567 static StmtResult
13568 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13569                                  const ExprBuilder &To, const ExprBuilder &From,
13570                                  bool CopyingBaseSubobject, bool Copying,
13571                                  unsigned Depth = 0) {
13572   // C++11 [class.copy]p28:
13573   //   Each subobject is assigned in the manner appropriate to its type:
13574   //
13575   //     - if the subobject is of class type, as if by a call to operator= with
13576   //       the subobject as the object expression and the corresponding
13577   //       subobject of x as a single function argument (as if by explicit
13578   //       qualification; that is, ignoring any possible virtual overriding
13579   //       functions in more derived classes);
13580   //
13581   // C++03 [class.copy]p13:
13582   //     - if the subobject is of class type, the copy assignment operator for
13583   //       the class is used (as if by explicit qualification; that is,
13584   //       ignoring any possible virtual overriding functions in more derived
13585   //       classes);
13586   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13587     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13588 
13589     // Look for operator=.
13590     DeclarationName Name
13591       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13592     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13593     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13594 
13595     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13596     // operator.
13597     if (!S.getLangOpts().CPlusPlus11) {
13598       LookupResult::Filter F = OpLookup.makeFilter();
13599       while (F.hasNext()) {
13600         NamedDecl *D = F.next();
13601         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13602           if (Method->isCopyAssignmentOperator() ||
13603               (!Copying && Method->isMoveAssignmentOperator()))
13604             continue;
13605 
13606         F.erase();
13607       }
13608       F.done();
13609     }
13610 
13611     // Suppress the protected check (C++ [class.protected]) for each of the
13612     // assignment operators we found. This strange dance is required when
13613     // we're assigning via a base classes's copy-assignment operator. To
13614     // ensure that we're getting the right base class subobject (without
13615     // ambiguities), we need to cast "this" to that subobject type; to
13616     // ensure that we don't go through the virtual call mechanism, we need
13617     // to qualify the operator= name with the base class (see below). However,
13618     // this means that if the base class has a protected copy assignment
13619     // operator, the protected member access check will fail. So, we
13620     // rewrite "protected" access to "public" access in this case, since we
13621     // know by construction that we're calling from a derived class.
13622     if (CopyingBaseSubobject) {
13623       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13624            L != LEnd; ++L) {
13625         if (L.getAccess() == AS_protected)
13626           L.setAccess(AS_public);
13627       }
13628     }
13629 
13630     // Create the nested-name-specifier that will be used to qualify the
13631     // reference to operator=; this is required to suppress the virtual
13632     // call mechanism.
13633     CXXScopeSpec SS;
13634     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13635     SS.MakeTrivial(S.Context,
13636                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13637                                                CanonicalT),
13638                    Loc);
13639 
13640     // Create the reference to operator=.
13641     ExprResult OpEqualRef
13642       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13643                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13644                                    /*FirstQualifierInScope=*/nullptr,
13645                                    OpLookup,
13646                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13647                                    /*SuppressQualifierCheck=*/true);
13648     if (OpEqualRef.isInvalid())
13649       return StmtError();
13650 
13651     // Build the call to the assignment operator.
13652 
13653     Expr *FromInst = From.build(S, Loc);
13654     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13655                                                   OpEqualRef.getAs<Expr>(),
13656                                                   Loc, FromInst, Loc);
13657     if (Call.isInvalid())
13658       return StmtError();
13659 
13660     // If we built a call to a trivial 'operator=' while copying an array,
13661     // bail out. We'll replace the whole shebang with a memcpy.
13662     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13663     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13664       return StmtResult((Stmt*)nullptr);
13665 
13666     // Convert to an expression-statement, and clean up any produced
13667     // temporaries.
13668     return S.ActOnExprStmt(Call);
13669   }
13670 
13671   //     - if the subobject is of scalar type, the built-in assignment
13672   //       operator is used.
13673   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13674   if (!ArrayTy) {
13675     ExprResult Assignment = S.CreateBuiltinBinOp(
13676         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13677     if (Assignment.isInvalid())
13678       return StmtError();
13679     return S.ActOnExprStmt(Assignment);
13680   }
13681 
13682   //     - if the subobject is an array, each element is assigned, in the
13683   //       manner appropriate to the element type;
13684 
13685   // Construct a loop over the array bounds, e.g.,
13686   //
13687   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13688   //
13689   // that will copy each of the array elements.
13690   QualType SizeType = S.Context.getSizeType();
13691 
13692   // Create the iteration variable.
13693   IdentifierInfo *IterationVarName = nullptr;
13694   {
13695     SmallString<8> Str;
13696     llvm::raw_svector_ostream OS(Str);
13697     OS << "__i" << Depth;
13698     IterationVarName = &S.Context.Idents.get(OS.str());
13699   }
13700   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13701                                           IterationVarName, SizeType,
13702                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13703                                           SC_None);
13704 
13705   // Initialize the iteration variable to zero.
13706   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13707   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13708 
13709   // Creates a reference to the iteration variable.
13710   RefBuilder IterationVarRef(IterationVar, SizeType);
13711   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13712 
13713   // Create the DeclStmt that holds the iteration variable.
13714   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13715 
13716   // Subscript the "from" and "to" expressions with the iteration variable.
13717   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13718   MoveCastBuilder FromIndexMove(FromIndexCopy);
13719   const ExprBuilder *FromIndex;
13720   if (Copying)
13721     FromIndex = &FromIndexCopy;
13722   else
13723     FromIndex = &FromIndexMove;
13724 
13725   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13726 
13727   // Build the copy/move for an individual element of the array.
13728   StmtResult Copy =
13729     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13730                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13731                                      Copying, Depth + 1);
13732   // Bail out if copying fails or if we determined that we should use memcpy.
13733   if (Copy.isInvalid() || !Copy.get())
13734     return Copy;
13735 
13736   // Create the comparison against the array bound.
13737   llvm::APInt Upper
13738     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13739   Expr *Comparison = BinaryOperator::Create(
13740       S.Context, IterationVarRefRVal.build(S, Loc),
13741       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13742       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatures);
13743 
13744   // Create the pre-increment of the iteration variable. We can determine
13745   // whether the increment will overflow based on the value of the array
13746   // bound.
13747   Expr *Increment = UnaryOperator::Create(
13748       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13749       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatures);
13750 
13751   // Construct the loop that copies all elements of this array.
13752   return S.ActOnForStmt(
13753       Loc, Loc, InitStmt,
13754       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13755       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13756 }
13757 
13758 static StmtResult
13759 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13760                       const ExprBuilder &To, const ExprBuilder &From,
13761                       bool CopyingBaseSubobject, bool Copying) {
13762   // Maybe we should use a memcpy?
13763   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13764       T.isTriviallyCopyableType(S.Context))
13765     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13766 
13767   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13768                                                      CopyingBaseSubobject,
13769                                                      Copying, 0));
13770 
13771   // If we ended up picking a trivial assignment operator for an array of a
13772   // non-trivially-copyable class type, just emit a memcpy.
13773   if (!Result.isInvalid() && !Result.get())
13774     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13775 
13776   return Result;
13777 }
13778 
13779 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13780   // Note: The following rules are largely analoguous to the copy
13781   // constructor rules. Note that virtual bases are not taken into account
13782   // for determining the argument type of the operator. Note also that
13783   // operators taking an object instead of a reference are allowed.
13784   assert(ClassDecl->needsImplicitCopyAssignment());
13785 
13786   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13787   if (DSM.isAlreadyBeingDeclared())
13788     return nullptr;
13789 
13790   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13791   LangAS AS = getDefaultCXXMethodAddrSpace();
13792   if (AS != LangAS::Default)
13793     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13794   QualType RetType = Context.getLValueReferenceType(ArgType);
13795   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13796   if (Const)
13797     ArgType = ArgType.withConst();
13798 
13799   ArgType = Context.getLValueReferenceType(ArgType);
13800 
13801   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13802                                                      CXXCopyAssignment,
13803                                                      Const);
13804 
13805   //   An implicitly-declared copy assignment operator is an inline public
13806   //   member of its class.
13807   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13808   SourceLocation ClassLoc = ClassDecl->getLocation();
13809   DeclarationNameInfo NameInfo(Name, ClassLoc);
13810   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13811       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13812       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13813       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13814       SourceLocation());
13815   CopyAssignment->setAccess(AS_public);
13816   CopyAssignment->setDefaulted();
13817   CopyAssignment->setImplicit();
13818 
13819   if (getLangOpts().CUDA) {
13820     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13821                                             CopyAssignment,
13822                                             /* ConstRHS */ Const,
13823                                             /* Diagnose */ false);
13824   }
13825 
13826   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13827 
13828   // Add the parameter to the operator.
13829   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13830                                                ClassLoc, ClassLoc,
13831                                                /*Id=*/nullptr, ArgType,
13832                                                /*TInfo=*/nullptr, SC_None,
13833                                                nullptr);
13834   CopyAssignment->setParams(FromParam);
13835 
13836   CopyAssignment->setTrivial(
13837     ClassDecl->needsOverloadResolutionForCopyAssignment()
13838       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13839       : ClassDecl->hasTrivialCopyAssignment());
13840 
13841   // Note that we have added this copy-assignment operator.
13842   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13843 
13844   Scope *S = getScopeForContext(ClassDecl);
13845   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13846 
13847   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13848     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13849     SetDeclDeleted(CopyAssignment, ClassLoc);
13850   }
13851 
13852   if (S)
13853     PushOnScopeChains(CopyAssignment, S, false);
13854   ClassDecl->addDecl(CopyAssignment);
13855 
13856   return CopyAssignment;
13857 }
13858 
13859 /// Diagnose an implicit copy operation for a class which is odr-used, but
13860 /// which is deprecated because the class has a user-declared copy constructor,
13861 /// copy assignment operator, or destructor.
13862 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13863   assert(CopyOp->isImplicit());
13864 
13865   CXXRecordDecl *RD = CopyOp->getParent();
13866   CXXMethodDecl *UserDeclaredOperation = nullptr;
13867 
13868   // In Microsoft mode, assignment operations don't affect constructors and
13869   // vice versa.
13870   if (RD->hasUserDeclaredDestructor()) {
13871     UserDeclaredOperation = RD->getDestructor();
13872   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13873              RD->hasUserDeclaredCopyConstructor() &&
13874              !S.getLangOpts().MSVCCompat) {
13875     // Find any user-declared copy constructor.
13876     for (auto *I : RD->ctors()) {
13877       if (I->isCopyConstructor()) {
13878         UserDeclaredOperation = I;
13879         break;
13880       }
13881     }
13882     assert(UserDeclaredOperation);
13883   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13884              RD->hasUserDeclaredCopyAssignment() &&
13885              !S.getLangOpts().MSVCCompat) {
13886     // Find any user-declared move assignment operator.
13887     for (auto *I : RD->methods()) {
13888       if (I->isCopyAssignmentOperator()) {
13889         UserDeclaredOperation = I;
13890         break;
13891       }
13892     }
13893     assert(UserDeclaredOperation);
13894   }
13895 
13896   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13897     S.Diag(UserDeclaredOperation->getLocation(),
13898            isa<CXXDestructorDecl>(UserDeclaredOperation)
13899                ? diag::warn_deprecated_copy_dtor_operation
13900                : diag::warn_deprecated_copy_operation)
13901         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13902   }
13903 }
13904 
13905 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13906                                         CXXMethodDecl *CopyAssignOperator) {
13907   assert((CopyAssignOperator->isDefaulted() &&
13908           CopyAssignOperator->isOverloadedOperator() &&
13909           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13910           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13911           !CopyAssignOperator->isDeleted()) &&
13912          "DefineImplicitCopyAssignment called for wrong function");
13913   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13914     return;
13915 
13916   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13917   if (ClassDecl->isInvalidDecl()) {
13918     CopyAssignOperator->setInvalidDecl();
13919     return;
13920   }
13921 
13922   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13923 
13924   // The exception specification is needed because we are defining the
13925   // function.
13926   ResolveExceptionSpec(CurrentLocation,
13927                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13928 
13929   // Add a context note for diagnostics produced after this point.
13930   Scope.addContextNote(CurrentLocation);
13931 
13932   // C++11 [class.copy]p18:
13933   //   The [definition of an implicitly declared copy assignment operator] is
13934   //   deprecated if the class has a user-declared copy constructor or a
13935   //   user-declared destructor.
13936   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13937     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13938 
13939   // C++0x [class.copy]p30:
13940   //   The implicitly-defined or explicitly-defaulted copy assignment operator
13941   //   for a non-union class X performs memberwise copy assignment of its
13942   //   subobjects. The direct base classes of X are assigned first, in the
13943   //   order of their declaration in the base-specifier-list, and then the
13944   //   immediate non-static data members of X are assigned, in the order in
13945   //   which they were declared in the class definition.
13946 
13947   // The statements that form the synthesized function body.
13948   SmallVector<Stmt*, 8> Statements;
13949 
13950   // The parameter for the "other" object, which we are copying from.
13951   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13952   Qualifiers OtherQuals = Other->getType().getQualifiers();
13953   QualType OtherRefType = Other->getType();
13954   if (const LValueReferenceType *OtherRef
13955                                 = OtherRefType->getAs<LValueReferenceType>()) {
13956     OtherRefType = OtherRef->getPointeeType();
13957     OtherQuals = OtherRefType.getQualifiers();
13958   }
13959 
13960   // Our location for everything implicitly-generated.
13961   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
13962                            ? CopyAssignOperator->getEndLoc()
13963                            : CopyAssignOperator->getLocation();
13964 
13965   // Builds a DeclRefExpr for the "other" object.
13966   RefBuilder OtherRef(Other, OtherRefType);
13967 
13968   // Builds the "this" pointer.
13969   ThisBuilder This;
13970 
13971   // Assign base classes.
13972   bool Invalid = false;
13973   for (auto &Base : ClassDecl->bases()) {
13974     // Form the assignment:
13975     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
13976     QualType BaseType = Base.getType().getUnqualifiedType();
13977     if (!BaseType->isRecordType()) {
13978       Invalid = true;
13979       continue;
13980     }
13981 
13982     CXXCastPath BasePath;
13983     BasePath.push_back(&Base);
13984 
13985     // Construct the "from" expression, which is an implicit cast to the
13986     // appropriately-qualified base type.
13987     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
13988                      VK_LValue, BasePath);
13989 
13990     // Dereference "this".
13991     DerefBuilder DerefThis(This);
13992     CastBuilder To(DerefThis,
13993                    Context.getQualifiedType(
13994                        BaseType, CopyAssignOperator->getMethodQualifiers()),
13995                    VK_LValue, BasePath);
13996 
13997     // Build the copy.
13998     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
13999                                             To, From,
14000                                             /*CopyingBaseSubobject=*/true,
14001                                             /*Copying=*/true);
14002     if (Copy.isInvalid()) {
14003       CopyAssignOperator->setInvalidDecl();
14004       return;
14005     }
14006 
14007     // Success! Record the copy.
14008     Statements.push_back(Copy.getAs<Expr>());
14009   }
14010 
14011   // Assign non-static members.
14012   for (auto *Field : ClassDecl->fields()) {
14013     // FIXME: We should form some kind of AST representation for the implied
14014     // memcpy in a union copy operation.
14015     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14016       continue;
14017 
14018     if (Field->isInvalidDecl()) {
14019       Invalid = true;
14020       continue;
14021     }
14022 
14023     // Check for members of reference type; we can't copy those.
14024     if (Field->getType()->isReferenceType()) {
14025       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14026         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14027       Diag(Field->getLocation(), diag::note_declared_at);
14028       Invalid = true;
14029       continue;
14030     }
14031 
14032     // Check for members of const-qualified, non-class type.
14033     QualType BaseType = Context.getBaseElementType(Field->getType());
14034     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14035       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14036         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14037       Diag(Field->getLocation(), diag::note_declared_at);
14038       Invalid = true;
14039       continue;
14040     }
14041 
14042     // Suppress assigning zero-width bitfields.
14043     if (Field->isZeroLengthBitField(Context))
14044       continue;
14045 
14046     QualType FieldType = Field->getType().getNonReferenceType();
14047     if (FieldType->isIncompleteArrayType()) {
14048       assert(ClassDecl->hasFlexibleArrayMember() &&
14049              "Incomplete array type is not valid");
14050       continue;
14051     }
14052 
14053     // Build references to the field in the object we're copying from and to.
14054     CXXScopeSpec SS; // Intentionally empty
14055     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14056                               LookupMemberName);
14057     MemberLookup.addDecl(Field);
14058     MemberLookup.resolveKind();
14059 
14060     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14061 
14062     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14063 
14064     // Build the copy of this field.
14065     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14066                                             To, From,
14067                                             /*CopyingBaseSubobject=*/false,
14068                                             /*Copying=*/true);
14069     if (Copy.isInvalid()) {
14070       CopyAssignOperator->setInvalidDecl();
14071       return;
14072     }
14073 
14074     // Success! Record the copy.
14075     Statements.push_back(Copy.getAs<Stmt>());
14076   }
14077 
14078   if (!Invalid) {
14079     // Add a "return *this;"
14080     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14081 
14082     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14083     if (Return.isInvalid())
14084       Invalid = true;
14085     else
14086       Statements.push_back(Return.getAs<Stmt>());
14087   }
14088 
14089   if (Invalid) {
14090     CopyAssignOperator->setInvalidDecl();
14091     return;
14092   }
14093 
14094   StmtResult Body;
14095   {
14096     CompoundScopeRAII CompoundScope(*this);
14097     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14098                              /*isStmtExpr=*/false);
14099     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14100   }
14101   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14102   CopyAssignOperator->markUsed(Context);
14103 
14104   if (ASTMutationListener *L = getASTMutationListener()) {
14105     L->CompletedImplicitDefinition(CopyAssignOperator);
14106   }
14107 }
14108 
14109 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14110   assert(ClassDecl->needsImplicitMoveAssignment());
14111 
14112   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14113   if (DSM.isAlreadyBeingDeclared())
14114     return nullptr;
14115 
14116   // Note: The following rules are largely analoguous to the move
14117   // constructor rules.
14118 
14119   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14120   LangAS AS = getDefaultCXXMethodAddrSpace();
14121   if (AS != LangAS::Default)
14122     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14123   QualType RetType = Context.getLValueReferenceType(ArgType);
14124   ArgType = Context.getRValueReferenceType(ArgType);
14125 
14126   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14127                                                      CXXMoveAssignment,
14128                                                      false);
14129 
14130   //   An implicitly-declared move assignment operator is an inline public
14131   //   member of its class.
14132   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14133   SourceLocation ClassLoc = ClassDecl->getLocation();
14134   DeclarationNameInfo NameInfo(Name, ClassLoc);
14135   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14136       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14137       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14138       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14139       SourceLocation());
14140   MoveAssignment->setAccess(AS_public);
14141   MoveAssignment->setDefaulted();
14142   MoveAssignment->setImplicit();
14143 
14144   if (getLangOpts().CUDA) {
14145     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14146                                             MoveAssignment,
14147                                             /* ConstRHS */ false,
14148                                             /* Diagnose */ false);
14149   }
14150 
14151   // Build an exception specification pointing back at this member.
14152   FunctionProtoType::ExtProtoInfo EPI =
14153       getImplicitMethodEPI(*this, MoveAssignment);
14154   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14155 
14156   // Add the parameter to the operator.
14157   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14158                                                ClassLoc, ClassLoc,
14159                                                /*Id=*/nullptr, ArgType,
14160                                                /*TInfo=*/nullptr, SC_None,
14161                                                nullptr);
14162   MoveAssignment->setParams(FromParam);
14163 
14164   MoveAssignment->setTrivial(
14165     ClassDecl->needsOverloadResolutionForMoveAssignment()
14166       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14167       : ClassDecl->hasTrivialMoveAssignment());
14168 
14169   // Note that we have added this copy-assignment operator.
14170   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14171 
14172   Scope *S = getScopeForContext(ClassDecl);
14173   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14174 
14175   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14176     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14177     SetDeclDeleted(MoveAssignment, ClassLoc);
14178   }
14179 
14180   if (S)
14181     PushOnScopeChains(MoveAssignment, S, false);
14182   ClassDecl->addDecl(MoveAssignment);
14183 
14184   return MoveAssignment;
14185 }
14186 
14187 /// Check if we're implicitly defining a move assignment operator for a class
14188 /// with virtual bases. Such a move assignment might move-assign the virtual
14189 /// base multiple times.
14190 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14191                                                SourceLocation CurrentLocation) {
14192   assert(!Class->isDependentContext() && "should not define dependent move");
14193 
14194   // Only a virtual base could get implicitly move-assigned multiple times.
14195   // Only a non-trivial move assignment can observe this. We only want to
14196   // diagnose if we implicitly define an assignment operator that assigns
14197   // two base classes, both of which move-assign the same virtual base.
14198   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14199       Class->getNumBases() < 2)
14200     return;
14201 
14202   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14203   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14204   VBaseMap VBases;
14205 
14206   for (auto &BI : Class->bases()) {
14207     Worklist.push_back(&BI);
14208     while (!Worklist.empty()) {
14209       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14210       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14211 
14212       // If the base has no non-trivial move assignment operators,
14213       // we don't care about moves from it.
14214       if (!Base->hasNonTrivialMoveAssignment())
14215         continue;
14216 
14217       // If there's nothing virtual here, skip it.
14218       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14219         continue;
14220 
14221       // If we're not actually going to call a move assignment for this base,
14222       // or the selected move assignment is trivial, skip it.
14223       Sema::SpecialMemberOverloadResult SMOR =
14224         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14225                               /*ConstArg*/false, /*VolatileArg*/false,
14226                               /*RValueThis*/true, /*ConstThis*/false,
14227                               /*VolatileThis*/false);
14228       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14229           !SMOR.getMethod()->isMoveAssignmentOperator())
14230         continue;
14231 
14232       if (BaseSpec->isVirtual()) {
14233         // We're going to move-assign this virtual base, and its move
14234         // assignment operator is not trivial. If this can happen for
14235         // multiple distinct direct bases of Class, diagnose it. (If it
14236         // only happens in one base, we'll diagnose it when synthesizing
14237         // that base class's move assignment operator.)
14238         CXXBaseSpecifier *&Existing =
14239             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14240                 .first->second;
14241         if (Existing && Existing != &BI) {
14242           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14243             << Class << Base;
14244           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14245               << (Base->getCanonicalDecl() ==
14246                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14247               << Base << Existing->getType() << Existing->getSourceRange();
14248           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14249               << (Base->getCanonicalDecl() ==
14250                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14251               << Base << BI.getType() << BaseSpec->getSourceRange();
14252 
14253           // Only diagnose each vbase once.
14254           Existing = nullptr;
14255         }
14256       } else {
14257         // Only walk over bases that have defaulted move assignment operators.
14258         // We assume that any user-provided move assignment operator handles
14259         // the multiple-moves-of-vbase case itself somehow.
14260         if (!SMOR.getMethod()->isDefaulted())
14261           continue;
14262 
14263         // We're going to move the base classes of Base. Add them to the list.
14264         for (auto &BI : Base->bases())
14265           Worklist.push_back(&BI);
14266       }
14267     }
14268   }
14269 }
14270 
14271 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14272                                         CXXMethodDecl *MoveAssignOperator) {
14273   assert((MoveAssignOperator->isDefaulted() &&
14274           MoveAssignOperator->isOverloadedOperator() &&
14275           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14276           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14277           !MoveAssignOperator->isDeleted()) &&
14278          "DefineImplicitMoveAssignment called for wrong function");
14279   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14280     return;
14281 
14282   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14283   if (ClassDecl->isInvalidDecl()) {
14284     MoveAssignOperator->setInvalidDecl();
14285     return;
14286   }
14287 
14288   // C++0x [class.copy]p28:
14289   //   The implicitly-defined or move assignment operator for a non-union class
14290   //   X performs memberwise move assignment of its subobjects. The direct base
14291   //   classes of X are assigned first, in the order of their declaration in the
14292   //   base-specifier-list, and then the immediate non-static data members of X
14293   //   are assigned, in the order in which they were declared in the class
14294   //   definition.
14295 
14296   // Issue a warning if our implicit move assignment operator will move
14297   // from a virtual base more than once.
14298   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14299 
14300   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14301 
14302   // The exception specification is needed because we are defining the
14303   // function.
14304   ResolveExceptionSpec(CurrentLocation,
14305                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14306 
14307   // Add a context note for diagnostics produced after this point.
14308   Scope.addContextNote(CurrentLocation);
14309 
14310   // The statements that form the synthesized function body.
14311   SmallVector<Stmt*, 8> Statements;
14312 
14313   // The parameter for the "other" object, which we are move from.
14314   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14315   QualType OtherRefType =
14316       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14317 
14318   // Our location for everything implicitly-generated.
14319   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14320                            ? MoveAssignOperator->getEndLoc()
14321                            : MoveAssignOperator->getLocation();
14322 
14323   // Builds a reference to the "other" object.
14324   RefBuilder OtherRef(Other, OtherRefType);
14325   // Cast to rvalue.
14326   MoveCastBuilder MoveOther(OtherRef);
14327 
14328   // Builds the "this" pointer.
14329   ThisBuilder This;
14330 
14331   // Assign base classes.
14332   bool Invalid = false;
14333   for (auto &Base : ClassDecl->bases()) {
14334     // C++11 [class.copy]p28:
14335     //   It is unspecified whether subobjects representing virtual base classes
14336     //   are assigned more than once by the implicitly-defined copy assignment
14337     //   operator.
14338     // FIXME: Do not assign to a vbase that will be assigned by some other base
14339     // class. For a move-assignment, this can result in the vbase being moved
14340     // multiple times.
14341 
14342     // Form the assignment:
14343     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14344     QualType BaseType = Base.getType().getUnqualifiedType();
14345     if (!BaseType->isRecordType()) {
14346       Invalid = true;
14347       continue;
14348     }
14349 
14350     CXXCastPath BasePath;
14351     BasePath.push_back(&Base);
14352 
14353     // Construct the "from" expression, which is an implicit cast to the
14354     // appropriately-qualified base type.
14355     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14356 
14357     // Dereference "this".
14358     DerefBuilder DerefThis(This);
14359 
14360     // Implicitly cast "this" to the appropriately-qualified base type.
14361     CastBuilder To(DerefThis,
14362                    Context.getQualifiedType(
14363                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14364                    VK_LValue, BasePath);
14365 
14366     // Build the move.
14367     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14368                                             To, From,
14369                                             /*CopyingBaseSubobject=*/true,
14370                                             /*Copying=*/false);
14371     if (Move.isInvalid()) {
14372       MoveAssignOperator->setInvalidDecl();
14373       return;
14374     }
14375 
14376     // Success! Record the move.
14377     Statements.push_back(Move.getAs<Expr>());
14378   }
14379 
14380   // Assign non-static members.
14381   for (auto *Field : ClassDecl->fields()) {
14382     // FIXME: We should form some kind of AST representation for the implied
14383     // memcpy in a union copy operation.
14384     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14385       continue;
14386 
14387     if (Field->isInvalidDecl()) {
14388       Invalid = true;
14389       continue;
14390     }
14391 
14392     // Check for members of reference type; we can't move those.
14393     if (Field->getType()->isReferenceType()) {
14394       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14395         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14396       Diag(Field->getLocation(), diag::note_declared_at);
14397       Invalid = true;
14398       continue;
14399     }
14400 
14401     // Check for members of const-qualified, non-class type.
14402     QualType BaseType = Context.getBaseElementType(Field->getType());
14403     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14404       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14405         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14406       Diag(Field->getLocation(), diag::note_declared_at);
14407       Invalid = true;
14408       continue;
14409     }
14410 
14411     // Suppress assigning zero-width bitfields.
14412     if (Field->isZeroLengthBitField(Context))
14413       continue;
14414 
14415     QualType FieldType = Field->getType().getNonReferenceType();
14416     if (FieldType->isIncompleteArrayType()) {
14417       assert(ClassDecl->hasFlexibleArrayMember() &&
14418              "Incomplete array type is not valid");
14419       continue;
14420     }
14421 
14422     // Build references to the field in the object we're copying from and to.
14423     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14424                               LookupMemberName);
14425     MemberLookup.addDecl(Field);
14426     MemberLookup.resolveKind();
14427     MemberBuilder From(MoveOther, OtherRefType,
14428                        /*IsArrow=*/false, MemberLookup);
14429     MemberBuilder To(This, getCurrentThisType(),
14430                      /*IsArrow=*/true, MemberLookup);
14431 
14432     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14433         "Member reference with rvalue base must be rvalue except for reference "
14434         "members, which aren't allowed for move assignment.");
14435 
14436     // Build the move of this field.
14437     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14438                                             To, From,
14439                                             /*CopyingBaseSubobject=*/false,
14440                                             /*Copying=*/false);
14441     if (Move.isInvalid()) {
14442       MoveAssignOperator->setInvalidDecl();
14443       return;
14444     }
14445 
14446     // Success! Record the copy.
14447     Statements.push_back(Move.getAs<Stmt>());
14448   }
14449 
14450   if (!Invalid) {
14451     // Add a "return *this;"
14452     ExprResult ThisObj =
14453         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14454 
14455     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14456     if (Return.isInvalid())
14457       Invalid = true;
14458     else
14459       Statements.push_back(Return.getAs<Stmt>());
14460   }
14461 
14462   if (Invalid) {
14463     MoveAssignOperator->setInvalidDecl();
14464     return;
14465   }
14466 
14467   StmtResult Body;
14468   {
14469     CompoundScopeRAII CompoundScope(*this);
14470     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14471                              /*isStmtExpr=*/false);
14472     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14473   }
14474   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14475   MoveAssignOperator->markUsed(Context);
14476 
14477   if (ASTMutationListener *L = getASTMutationListener()) {
14478     L->CompletedImplicitDefinition(MoveAssignOperator);
14479   }
14480 }
14481 
14482 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14483                                                     CXXRecordDecl *ClassDecl) {
14484   // C++ [class.copy]p4:
14485   //   If the class definition does not explicitly declare a copy
14486   //   constructor, one is declared implicitly.
14487   assert(ClassDecl->needsImplicitCopyConstructor());
14488 
14489   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14490   if (DSM.isAlreadyBeingDeclared())
14491     return nullptr;
14492 
14493   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14494   QualType ArgType = ClassType;
14495   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14496   if (Const)
14497     ArgType = ArgType.withConst();
14498 
14499   LangAS AS = getDefaultCXXMethodAddrSpace();
14500   if (AS != LangAS::Default)
14501     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14502 
14503   ArgType = Context.getLValueReferenceType(ArgType);
14504 
14505   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14506                                                      CXXCopyConstructor,
14507                                                      Const);
14508 
14509   DeclarationName Name
14510     = Context.DeclarationNames.getCXXConstructorName(
14511                                            Context.getCanonicalType(ClassType));
14512   SourceLocation ClassLoc = ClassDecl->getLocation();
14513   DeclarationNameInfo NameInfo(Name, ClassLoc);
14514 
14515   //   An implicitly-declared copy constructor is an inline public
14516   //   member of its class.
14517   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14518       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14519       ExplicitSpecifier(),
14520       /*isInline=*/true,
14521       /*isImplicitlyDeclared=*/true,
14522       Constexpr ? CSK_constexpr : CSK_unspecified);
14523   CopyConstructor->setAccess(AS_public);
14524   CopyConstructor->setDefaulted();
14525 
14526   if (getLangOpts().CUDA) {
14527     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14528                                             CopyConstructor,
14529                                             /* ConstRHS */ Const,
14530                                             /* Diagnose */ false);
14531   }
14532 
14533   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14534 
14535   // Add the parameter to the constructor.
14536   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14537                                                ClassLoc, ClassLoc,
14538                                                /*IdentifierInfo=*/nullptr,
14539                                                ArgType, /*TInfo=*/nullptr,
14540                                                SC_None, nullptr);
14541   CopyConstructor->setParams(FromParam);
14542 
14543   CopyConstructor->setTrivial(
14544       ClassDecl->needsOverloadResolutionForCopyConstructor()
14545           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14546           : ClassDecl->hasTrivialCopyConstructor());
14547 
14548   CopyConstructor->setTrivialForCall(
14549       ClassDecl->hasAttr<TrivialABIAttr>() ||
14550       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14551            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14552              TAH_ConsiderTrivialABI)
14553            : ClassDecl->hasTrivialCopyConstructorForCall()));
14554 
14555   // Note that we have declared this constructor.
14556   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14557 
14558   Scope *S = getScopeForContext(ClassDecl);
14559   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14560 
14561   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14562     ClassDecl->setImplicitCopyConstructorIsDeleted();
14563     SetDeclDeleted(CopyConstructor, ClassLoc);
14564   }
14565 
14566   if (S)
14567     PushOnScopeChains(CopyConstructor, S, false);
14568   ClassDecl->addDecl(CopyConstructor);
14569 
14570   return CopyConstructor;
14571 }
14572 
14573 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14574                                          CXXConstructorDecl *CopyConstructor) {
14575   assert((CopyConstructor->isDefaulted() &&
14576           CopyConstructor->isCopyConstructor() &&
14577           !CopyConstructor->doesThisDeclarationHaveABody() &&
14578           !CopyConstructor->isDeleted()) &&
14579          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14580   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14581     return;
14582 
14583   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14584   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14585 
14586   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14587 
14588   // The exception specification is needed because we are defining the
14589   // function.
14590   ResolveExceptionSpec(CurrentLocation,
14591                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14592   MarkVTableUsed(CurrentLocation, ClassDecl);
14593 
14594   // Add a context note for diagnostics produced after this point.
14595   Scope.addContextNote(CurrentLocation);
14596 
14597   // C++11 [class.copy]p7:
14598   //   The [definition of an implicitly declared copy constructor] is
14599   //   deprecated if the class has a user-declared copy assignment operator
14600   //   or a user-declared destructor.
14601   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14602     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14603 
14604   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14605     CopyConstructor->setInvalidDecl();
14606   }  else {
14607     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14608                              ? CopyConstructor->getEndLoc()
14609                              : CopyConstructor->getLocation();
14610     Sema::CompoundScopeRAII CompoundScope(*this);
14611     CopyConstructor->setBody(
14612         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14613     CopyConstructor->markUsed(Context);
14614   }
14615 
14616   if (ASTMutationListener *L = getASTMutationListener()) {
14617     L->CompletedImplicitDefinition(CopyConstructor);
14618   }
14619 }
14620 
14621 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14622                                                     CXXRecordDecl *ClassDecl) {
14623   assert(ClassDecl->needsImplicitMoveConstructor());
14624 
14625   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14626   if (DSM.isAlreadyBeingDeclared())
14627     return nullptr;
14628 
14629   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14630 
14631   QualType ArgType = ClassType;
14632   LangAS AS = getDefaultCXXMethodAddrSpace();
14633   if (AS != LangAS::Default)
14634     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14635   ArgType = Context.getRValueReferenceType(ArgType);
14636 
14637   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14638                                                      CXXMoveConstructor,
14639                                                      false);
14640 
14641   DeclarationName Name
14642     = Context.DeclarationNames.getCXXConstructorName(
14643                                            Context.getCanonicalType(ClassType));
14644   SourceLocation ClassLoc = ClassDecl->getLocation();
14645   DeclarationNameInfo NameInfo(Name, ClassLoc);
14646 
14647   // C++11 [class.copy]p11:
14648   //   An implicitly-declared copy/move constructor is an inline public
14649   //   member of its class.
14650   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14651       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14652       ExplicitSpecifier(),
14653       /*isInline=*/true,
14654       /*isImplicitlyDeclared=*/true,
14655       Constexpr ? CSK_constexpr : CSK_unspecified);
14656   MoveConstructor->setAccess(AS_public);
14657   MoveConstructor->setDefaulted();
14658 
14659   if (getLangOpts().CUDA) {
14660     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14661                                             MoveConstructor,
14662                                             /* ConstRHS */ false,
14663                                             /* Diagnose */ false);
14664   }
14665 
14666   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14667 
14668   // Add the parameter to the constructor.
14669   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14670                                                ClassLoc, ClassLoc,
14671                                                /*IdentifierInfo=*/nullptr,
14672                                                ArgType, /*TInfo=*/nullptr,
14673                                                SC_None, nullptr);
14674   MoveConstructor->setParams(FromParam);
14675 
14676   MoveConstructor->setTrivial(
14677       ClassDecl->needsOverloadResolutionForMoveConstructor()
14678           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14679           : ClassDecl->hasTrivialMoveConstructor());
14680 
14681   MoveConstructor->setTrivialForCall(
14682       ClassDecl->hasAttr<TrivialABIAttr>() ||
14683       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14684            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14685                                     TAH_ConsiderTrivialABI)
14686            : ClassDecl->hasTrivialMoveConstructorForCall()));
14687 
14688   // Note that we have declared this constructor.
14689   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14690 
14691   Scope *S = getScopeForContext(ClassDecl);
14692   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14693 
14694   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14695     ClassDecl->setImplicitMoveConstructorIsDeleted();
14696     SetDeclDeleted(MoveConstructor, ClassLoc);
14697   }
14698 
14699   if (S)
14700     PushOnScopeChains(MoveConstructor, S, false);
14701   ClassDecl->addDecl(MoveConstructor);
14702 
14703   return MoveConstructor;
14704 }
14705 
14706 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14707                                          CXXConstructorDecl *MoveConstructor) {
14708   assert((MoveConstructor->isDefaulted() &&
14709           MoveConstructor->isMoveConstructor() &&
14710           !MoveConstructor->doesThisDeclarationHaveABody() &&
14711           !MoveConstructor->isDeleted()) &&
14712          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14713   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14714     return;
14715 
14716   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14717   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14718 
14719   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14720 
14721   // The exception specification is needed because we are defining the
14722   // function.
14723   ResolveExceptionSpec(CurrentLocation,
14724                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14725   MarkVTableUsed(CurrentLocation, ClassDecl);
14726 
14727   // Add a context note for diagnostics produced after this point.
14728   Scope.addContextNote(CurrentLocation);
14729 
14730   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14731     MoveConstructor->setInvalidDecl();
14732   } else {
14733     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14734                              ? MoveConstructor->getEndLoc()
14735                              : MoveConstructor->getLocation();
14736     Sema::CompoundScopeRAII CompoundScope(*this);
14737     MoveConstructor->setBody(ActOnCompoundStmt(
14738         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14739     MoveConstructor->markUsed(Context);
14740   }
14741 
14742   if (ASTMutationListener *L = getASTMutationListener()) {
14743     L->CompletedImplicitDefinition(MoveConstructor);
14744   }
14745 }
14746 
14747 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14748   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14749 }
14750 
14751 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14752                             SourceLocation CurrentLocation,
14753                             CXXConversionDecl *Conv) {
14754   SynthesizedFunctionScope Scope(*this, Conv);
14755   assert(!Conv->getReturnType()->isUndeducedType());
14756 
14757   CXXRecordDecl *Lambda = Conv->getParent();
14758   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14759   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14760 
14761   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14762     CallOp = InstantiateFunctionDeclaration(
14763         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14764     if (!CallOp)
14765       return;
14766 
14767     Invoker = InstantiateFunctionDeclaration(
14768         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14769     if (!Invoker)
14770       return;
14771   }
14772 
14773   if (CallOp->isInvalidDecl())
14774     return;
14775 
14776   // Mark the call operator referenced (and add to pending instantiations
14777   // if necessary).
14778   // For both the conversion and static-invoker template specializations
14779   // we construct their body's in this function, so no need to add them
14780   // to the PendingInstantiations.
14781   MarkFunctionReferenced(CurrentLocation, CallOp);
14782 
14783   // Fill in the __invoke function with a dummy implementation. IR generation
14784   // will fill in the actual details. Update its type in case it contained
14785   // an 'auto'.
14786   Invoker->markUsed(Context);
14787   Invoker->setReferenced();
14788   Invoker->setType(Conv->getReturnType()->getPointeeType());
14789   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14790 
14791   // Construct the body of the conversion function { return __invoke; }.
14792   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14793                                        VK_LValue, Conv->getLocation());
14794   assert(FunctionRef && "Can't refer to __invoke function?");
14795   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14796   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14797                                      Conv->getLocation()));
14798   Conv->markUsed(Context);
14799   Conv->setReferenced();
14800 
14801   if (ASTMutationListener *L = getASTMutationListener()) {
14802     L->CompletedImplicitDefinition(Conv);
14803     L->CompletedImplicitDefinition(Invoker);
14804   }
14805 }
14806 
14807 
14808 
14809 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14810        SourceLocation CurrentLocation,
14811        CXXConversionDecl *Conv)
14812 {
14813   assert(!Conv->getParent()->isGenericLambda());
14814 
14815   SynthesizedFunctionScope Scope(*this, Conv);
14816 
14817   // Copy-initialize the lambda object as needed to capture it.
14818   Expr *This = ActOnCXXThis(CurrentLocation).get();
14819   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14820 
14821   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14822                                                         Conv->getLocation(),
14823                                                         Conv, DerefThis);
14824 
14825   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14826   // behavior.  Note that only the general conversion function does this
14827   // (since it's unusable otherwise); in the case where we inline the
14828   // block literal, it has block literal lifetime semantics.
14829   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14830     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14831                                           CK_CopyAndAutoreleaseBlockObject,
14832                                           BuildBlock.get(), nullptr, VK_RValue);
14833 
14834   if (BuildBlock.isInvalid()) {
14835     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14836     Conv->setInvalidDecl();
14837     return;
14838   }
14839 
14840   // Create the return statement that returns the block from the conversion
14841   // function.
14842   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14843   if (Return.isInvalid()) {
14844     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14845     Conv->setInvalidDecl();
14846     return;
14847   }
14848 
14849   // Set the body of the conversion function.
14850   Stmt *ReturnS = Return.get();
14851   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14852                                      Conv->getLocation()));
14853   Conv->markUsed(Context);
14854 
14855   // We're done; notify the mutation listener, if any.
14856   if (ASTMutationListener *L = getASTMutationListener()) {
14857     L->CompletedImplicitDefinition(Conv);
14858   }
14859 }
14860 
14861 /// Determine whether the given list arguments contains exactly one
14862 /// "real" (non-default) argument.
14863 static bool hasOneRealArgument(MultiExprArg Args) {
14864   switch (Args.size()) {
14865   case 0:
14866     return false;
14867 
14868   default:
14869     if (!Args[1]->isDefaultArgument())
14870       return false;
14871 
14872     LLVM_FALLTHROUGH;
14873   case 1:
14874     return !Args[0]->isDefaultArgument();
14875   }
14876 
14877   return false;
14878 }
14879 
14880 ExprResult
14881 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14882                             NamedDecl *FoundDecl,
14883                             CXXConstructorDecl *Constructor,
14884                             MultiExprArg ExprArgs,
14885                             bool HadMultipleCandidates,
14886                             bool IsListInitialization,
14887                             bool IsStdInitListInitialization,
14888                             bool RequiresZeroInit,
14889                             unsigned ConstructKind,
14890                             SourceRange ParenRange) {
14891   bool Elidable = false;
14892 
14893   // C++0x [class.copy]p34:
14894   //   When certain criteria are met, an implementation is allowed to
14895   //   omit the copy/move construction of a class object, even if the
14896   //   copy/move constructor and/or destructor for the object have
14897   //   side effects. [...]
14898   //     - when a temporary class object that has not been bound to a
14899   //       reference (12.2) would be copied/moved to a class object
14900   //       with the same cv-unqualified type, the copy/move operation
14901   //       can be omitted by constructing the temporary object
14902   //       directly into the target of the omitted copy/move
14903   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14904       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14905     Expr *SubExpr = ExprArgs[0];
14906     Elidable = SubExpr->isTemporaryObject(
14907         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14908   }
14909 
14910   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14911                                FoundDecl, Constructor,
14912                                Elidable, ExprArgs, HadMultipleCandidates,
14913                                IsListInitialization,
14914                                IsStdInitListInitialization, RequiresZeroInit,
14915                                ConstructKind, ParenRange);
14916 }
14917 
14918 ExprResult
14919 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14920                             NamedDecl *FoundDecl,
14921                             CXXConstructorDecl *Constructor,
14922                             bool Elidable,
14923                             MultiExprArg ExprArgs,
14924                             bool HadMultipleCandidates,
14925                             bool IsListInitialization,
14926                             bool IsStdInitListInitialization,
14927                             bool RequiresZeroInit,
14928                             unsigned ConstructKind,
14929                             SourceRange ParenRange) {
14930   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14931     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14932     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14933       return ExprError();
14934   }
14935 
14936   return BuildCXXConstructExpr(
14937       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14938       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14939       RequiresZeroInit, ConstructKind, ParenRange);
14940 }
14941 
14942 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14943 /// including handling of its default argument expressions.
14944 ExprResult
14945 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14946                             CXXConstructorDecl *Constructor,
14947                             bool Elidable,
14948                             MultiExprArg ExprArgs,
14949                             bool HadMultipleCandidates,
14950                             bool IsListInitialization,
14951                             bool IsStdInitListInitialization,
14952                             bool RequiresZeroInit,
14953                             unsigned ConstructKind,
14954                             SourceRange ParenRange) {
14955   assert(declaresSameEntity(
14956              Constructor->getParent(),
14957              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14958          "given constructor for wrong type");
14959   MarkFunctionReferenced(ConstructLoc, Constructor);
14960   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
14961     return ExprError();
14962   if (getLangOpts().SYCLIsDevice &&
14963       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
14964     return ExprError();
14965 
14966   return CheckForImmediateInvocation(
14967       CXXConstructExpr::Create(
14968           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
14969           HadMultipleCandidates, IsListInitialization,
14970           IsStdInitListInitialization, RequiresZeroInit,
14971           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
14972           ParenRange),
14973       Constructor);
14974 }
14975 
14976 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
14977   assert(Field->hasInClassInitializer());
14978 
14979   // If we already have the in-class initializer nothing needs to be done.
14980   if (Field->getInClassInitializer())
14981     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
14982 
14983   // If we might have already tried and failed to instantiate, don't try again.
14984   if (Field->isInvalidDecl())
14985     return ExprError();
14986 
14987   // Maybe we haven't instantiated the in-class initializer. Go check the
14988   // pattern FieldDecl to see if it has one.
14989   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
14990 
14991   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
14992     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
14993     DeclContext::lookup_result Lookup =
14994         ClassPattern->lookup(Field->getDeclName());
14995 
14996     // Lookup can return at most two results: the pattern for the field, or the
14997     // injected class name of the parent record. No other member can have the
14998     // same name as the field.
14999     // In modules mode, lookup can return multiple results (coming from
15000     // different modules).
15001     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15002            "more than two lookup results for field name");
15003     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15004     if (!Pattern) {
15005       assert(isa<CXXRecordDecl>(Lookup[0]) &&
15006              "cannot have other non-field member with same name");
15007       for (auto L : Lookup)
15008         if (isa<FieldDecl>(L)) {
15009           Pattern = cast<FieldDecl>(L);
15010           break;
15011         }
15012       assert(Pattern && "We must have set the Pattern!");
15013     }
15014 
15015     if (!Pattern->hasInClassInitializer() ||
15016         InstantiateInClassInitializer(Loc, Field, Pattern,
15017                                       getTemplateInstantiationArgs(Field))) {
15018       // Don't diagnose this again.
15019       Field->setInvalidDecl();
15020       return ExprError();
15021     }
15022     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15023   }
15024 
15025   // DR1351:
15026   //   If the brace-or-equal-initializer of a non-static data member
15027   //   invokes a defaulted default constructor of its class or of an
15028   //   enclosing class in a potentially evaluated subexpression, the
15029   //   program is ill-formed.
15030   //
15031   // This resolution is unworkable: the exception specification of the
15032   // default constructor can be needed in an unevaluated context, in
15033   // particular, in the operand of a noexcept-expression, and we can be
15034   // unable to compute an exception specification for an enclosed class.
15035   //
15036   // Any attempt to resolve the exception specification of a defaulted default
15037   // constructor before the initializer is lexically complete will ultimately
15038   // come here at which point we can diagnose it.
15039   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15040   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
15041       << OutermostClass << Field;
15042   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
15043   // Recover by marking the field invalid, unless we're in a SFINAE context.
15044   if (!isSFINAEContext())
15045     Field->setInvalidDecl();
15046   return ExprError();
15047 }
15048 
15049 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15050   if (VD->isInvalidDecl()) return;
15051   // If initializing the variable failed, don't also diagnose problems with
15052   // the desctructor, they're likely related.
15053   if (VD->getInit() && VD->getInit()->containsErrors())
15054     return;
15055 
15056   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15057   if (ClassDecl->isInvalidDecl()) return;
15058   if (ClassDecl->hasIrrelevantDestructor()) return;
15059   if (ClassDecl->isDependentContext()) return;
15060 
15061   if (VD->isNoDestroy(getASTContext()))
15062     return;
15063 
15064   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15065 
15066   // If this is an array, we'll require the destructor during initialization, so
15067   // we can skip over this. We still want to emit exit-time destructor warnings
15068   // though.
15069   if (!VD->getType()->isArrayType()) {
15070     MarkFunctionReferenced(VD->getLocation(), Destructor);
15071     CheckDestructorAccess(VD->getLocation(), Destructor,
15072                           PDiag(diag::err_access_dtor_var)
15073                               << VD->getDeclName() << VD->getType());
15074     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15075   }
15076 
15077   if (Destructor->isTrivial()) return;
15078 
15079   // If the destructor is constexpr, check whether the variable has constant
15080   // destruction now.
15081   if (Destructor->isConstexpr()) {
15082     bool HasConstantInit = false;
15083     if (VD->getInit() && !VD->getInit()->isValueDependent())
15084       HasConstantInit = VD->evaluateValue();
15085     SmallVector<PartialDiagnosticAt, 8> Notes;
15086     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15087         HasConstantInit) {
15088       Diag(VD->getLocation(),
15089            diag::err_constexpr_var_requires_const_destruction) << VD;
15090       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15091         Diag(Notes[I].first, Notes[I].second);
15092     }
15093   }
15094 
15095   if (!VD->hasGlobalStorage()) return;
15096 
15097   // Emit warning for non-trivial dtor in global scope (a real global,
15098   // class-static, function-static).
15099   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15100 
15101   // TODO: this should be re-enabled for static locals by !CXAAtExit
15102   if (!VD->isStaticLocal())
15103     Diag(VD->getLocation(), diag::warn_global_destructor);
15104 }
15105 
15106 /// Given a constructor and the set of arguments provided for the
15107 /// constructor, convert the arguments and add any required default arguments
15108 /// to form a proper call to this constructor.
15109 ///
15110 /// \returns true if an error occurred, false otherwise.
15111 bool
15112 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15113                               MultiExprArg ArgsPtr,
15114                               SourceLocation Loc,
15115                               SmallVectorImpl<Expr*> &ConvertedArgs,
15116                               bool AllowExplicit,
15117                               bool IsListInitialization) {
15118   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15119   unsigned NumArgs = ArgsPtr.size();
15120   Expr **Args = ArgsPtr.data();
15121 
15122   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15123   unsigned NumParams = Proto->getNumParams();
15124 
15125   // If too few arguments are available, we'll fill in the rest with defaults.
15126   if (NumArgs < NumParams)
15127     ConvertedArgs.reserve(NumParams);
15128   else
15129     ConvertedArgs.reserve(NumArgs);
15130 
15131   VariadicCallType CallType =
15132     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15133   SmallVector<Expr *, 8> AllArgs;
15134   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15135                                         Proto, 0,
15136                                         llvm::makeArrayRef(Args, NumArgs),
15137                                         AllArgs,
15138                                         CallType, AllowExplicit,
15139                                         IsListInitialization);
15140   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15141 
15142   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15143 
15144   CheckConstructorCall(Constructor,
15145                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15146                        Proto, Loc);
15147 
15148   return Invalid;
15149 }
15150 
15151 static inline bool
15152 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15153                                        const FunctionDecl *FnDecl) {
15154   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15155   if (isa<NamespaceDecl>(DC)) {
15156     return SemaRef.Diag(FnDecl->getLocation(),
15157                         diag::err_operator_new_delete_declared_in_namespace)
15158       << FnDecl->getDeclName();
15159   }
15160 
15161   if (isa<TranslationUnitDecl>(DC) &&
15162       FnDecl->getStorageClass() == SC_Static) {
15163     return SemaRef.Diag(FnDecl->getLocation(),
15164                         diag::err_operator_new_delete_declared_static)
15165       << FnDecl->getDeclName();
15166   }
15167 
15168   return false;
15169 }
15170 
15171 static QualType
15172 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15173   QualType QTy = PtrTy->getPointeeType();
15174   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15175   return SemaRef.Context.getPointerType(QTy);
15176 }
15177 
15178 static inline bool
15179 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15180                             CanQualType ExpectedResultType,
15181                             CanQualType ExpectedFirstParamType,
15182                             unsigned DependentParamTypeDiag,
15183                             unsigned InvalidParamTypeDiag) {
15184   QualType ResultType =
15185       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15186 
15187   // Check that the result type is not dependent.
15188   if (ResultType->isDependentType())
15189     return SemaRef.Diag(FnDecl->getLocation(),
15190                         diag::err_operator_new_delete_dependent_result_type)
15191     << FnDecl->getDeclName() << ExpectedResultType;
15192 
15193   // The operator is valid on any address space for OpenCL.
15194   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15195     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15196       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15197     }
15198   }
15199 
15200   // Check that the result type is what we expect.
15201   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
15202     return SemaRef.Diag(FnDecl->getLocation(),
15203                         diag::err_operator_new_delete_invalid_result_type)
15204     << FnDecl->getDeclName() << ExpectedResultType;
15205 
15206   // A function template must have at least 2 parameters.
15207   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15208     return SemaRef.Diag(FnDecl->getLocation(),
15209                       diag::err_operator_new_delete_template_too_few_parameters)
15210         << FnDecl->getDeclName();
15211 
15212   // The function decl must have at least 1 parameter.
15213   if (FnDecl->getNumParams() == 0)
15214     return SemaRef.Diag(FnDecl->getLocation(),
15215                         diag::err_operator_new_delete_too_few_parameters)
15216       << FnDecl->getDeclName();
15217 
15218   // Check the first parameter type is not dependent.
15219   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15220   if (FirstParamType->isDependentType())
15221     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
15222       << FnDecl->getDeclName() << ExpectedFirstParamType;
15223 
15224   // Check that the first parameter type is what we expect.
15225   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15226     // The operator is valid on any address space for OpenCL.
15227     if (auto *PtrTy =
15228             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15229       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15230     }
15231   }
15232   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15233       ExpectedFirstParamType)
15234     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
15235     << FnDecl->getDeclName() << ExpectedFirstParamType;
15236 
15237   return false;
15238 }
15239 
15240 static bool
15241 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15242   // C++ [basic.stc.dynamic.allocation]p1:
15243   //   A program is ill-formed if an allocation function is declared in a
15244   //   namespace scope other than global scope or declared static in global
15245   //   scope.
15246   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15247     return true;
15248 
15249   CanQualType SizeTy =
15250     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15251 
15252   // C++ [basic.stc.dynamic.allocation]p1:
15253   //  The return type shall be void*. The first parameter shall have type
15254   //  std::size_t.
15255   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15256                                   SizeTy,
15257                                   diag::err_operator_new_dependent_param_type,
15258                                   diag::err_operator_new_param_type))
15259     return true;
15260 
15261   // C++ [basic.stc.dynamic.allocation]p1:
15262   //  The first parameter shall not have an associated default argument.
15263   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15264     return SemaRef.Diag(FnDecl->getLocation(),
15265                         diag::err_operator_new_default_arg)
15266       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15267 
15268   return false;
15269 }
15270 
15271 static bool
15272 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15273   // C++ [basic.stc.dynamic.deallocation]p1:
15274   //   A program is ill-formed if deallocation functions are declared in a
15275   //   namespace scope other than global scope or declared static in global
15276   //   scope.
15277   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15278     return true;
15279 
15280   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15281 
15282   // C++ P0722:
15283   //   Within a class C, the first parameter of a destroying operator delete
15284   //   shall be of type C *. The first parameter of any other deallocation
15285   //   function shall be of type void *.
15286   CanQualType ExpectedFirstParamType =
15287       MD && MD->isDestroyingOperatorDelete()
15288           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15289                 SemaRef.Context.getRecordType(MD->getParent())))
15290           : SemaRef.Context.VoidPtrTy;
15291 
15292   // C++ [basic.stc.dynamic.deallocation]p2:
15293   //   Each deallocation function shall return void
15294   if (CheckOperatorNewDeleteTypes(
15295           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15296           diag::err_operator_delete_dependent_param_type,
15297           diag::err_operator_delete_param_type))
15298     return true;
15299 
15300   // C++ P0722:
15301   //   A destroying operator delete shall be a usual deallocation function.
15302   if (MD && !MD->getParent()->isDependentContext() &&
15303       MD->isDestroyingOperatorDelete() &&
15304       !SemaRef.isUsualDeallocationFunction(MD)) {
15305     SemaRef.Diag(MD->getLocation(),
15306                  diag::err_destroying_operator_delete_not_usual);
15307     return true;
15308   }
15309 
15310   return false;
15311 }
15312 
15313 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15314 /// of this overloaded operator is well-formed. If so, returns false;
15315 /// otherwise, emits appropriate diagnostics and returns true.
15316 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15317   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15318          "Expected an overloaded operator declaration");
15319 
15320   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15321 
15322   // C++ [over.oper]p5:
15323   //   The allocation and deallocation functions, operator new,
15324   //   operator new[], operator delete and operator delete[], are
15325   //   described completely in 3.7.3. The attributes and restrictions
15326   //   found in the rest of this subclause do not apply to them unless
15327   //   explicitly stated in 3.7.3.
15328   if (Op == OO_Delete || Op == OO_Array_Delete)
15329     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15330 
15331   if (Op == OO_New || Op == OO_Array_New)
15332     return CheckOperatorNewDeclaration(*this, FnDecl);
15333 
15334   // C++ [over.oper]p6:
15335   //   An operator function shall either be a non-static member
15336   //   function or be a non-member function and have at least one
15337   //   parameter whose type is a class, a reference to a class, an
15338   //   enumeration, or a reference to an enumeration.
15339   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15340     if (MethodDecl->isStatic())
15341       return Diag(FnDecl->getLocation(),
15342                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15343   } else {
15344     bool ClassOrEnumParam = false;
15345     for (auto Param : FnDecl->parameters()) {
15346       QualType ParamType = Param->getType().getNonReferenceType();
15347       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15348           ParamType->isEnumeralType()) {
15349         ClassOrEnumParam = true;
15350         break;
15351       }
15352     }
15353 
15354     if (!ClassOrEnumParam)
15355       return Diag(FnDecl->getLocation(),
15356                   diag::err_operator_overload_needs_class_or_enum)
15357         << FnDecl->getDeclName();
15358   }
15359 
15360   // C++ [over.oper]p8:
15361   //   An operator function cannot have default arguments (8.3.6),
15362   //   except where explicitly stated below.
15363   //
15364   // Only the function-call operator allows default arguments
15365   // (C++ [over.call]p1).
15366   if (Op != OO_Call) {
15367     for (auto Param : FnDecl->parameters()) {
15368       if (Param->hasDefaultArg())
15369         return Diag(Param->getLocation(),
15370                     diag::err_operator_overload_default_arg)
15371           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15372     }
15373   }
15374 
15375   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15376     { false, false, false }
15377 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15378     , { Unary, Binary, MemberOnly }
15379 #include "clang/Basic/OperatorKinds.def"
15380   };
15381 
15382   bool CanBeUnaryOperator = OperatorUses[Op][0];
15383   bool CanBeBinaryOperator = OperatorUses[Op][1];
15384   bool MustBeMemberOperator = OperatorUses[Op][2];
15385 
15386   // C++ [over.oper]p8:
15387   //   [...] Operator functions cannot have more or fewer parameters
15388   //   than the number required for the corresponding operator, as
15389   //   described in the rest of this subclause.
15390   unsigned NumParams = FnDecl->getNumParams()
15391                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15392   if (Op != OO_Call &&
15393       ((NumParams == 1 && !CanBeUnaryOperator) ||
15394        (NumParams == 2 && !CanBeBinaryOperator) ||
15395        (NumParams < 1) || (NumParams > 2))) {
15396     // We have the wrong number of parameters.
15397     unsigned ErrorKind;
15398     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15399       ErrorKind = 2;  // 2 -> unary or binary.
15400     } else if (CanBeUnaryOperator) {
15401       ErrorKind = 0;  // 0 -> unary
15402     } else {
15403       assert(CanBeBinaryOperator &&
15404              "All non-call overloaded operators are unary or binary!");
15405       ErrorKind = 1;  // 1 -> binary
15406     }
15407 
15408     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15409       << FnDecl->getDeclName() << NumParams << ErrorKind;
15410   }
15411 
15412   // Overloaded operators other than operator() cannot be variadic.
15413   if (Op != OO_Call &&
15414       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15415     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15416       << FnDecl->getDeclName();
15417   }
15418 
15419   // Some operators must be non-static member functions.
15420   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15421     return Diag(FnDecl->getLocation(),
15422                 diag::err_operator_overload_must_be_member)
15423       << FnDecl->getDeclName();
15424   }
15425 
15426   // C++ [over.inc]p1:
15427   //   The user-defined function called operator++ implements the
15428   //   prefix and postfix ++ operator. If this function is a member
15429   //   function with no parameters, or a non-member function with one
15430   //   parameter of class or enumeration type, it defines the prefix
15431   //   increment operator ++ for objects of that type. If the function
15432   //   is a member function with one parameter (which shall be of type
15433   //   int) or a non-member function with two parameters (the second
15434   //   of which shall be of type int), it defines the postfix
15435   //   increment operator ++ for objects of that type.
15436   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15437     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15438     QualType ParamType = LastParam->getType();
15439 
15440     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15441         !ParamType->isDependentType())
15442       return Diag(LastParam->getLocation(),
15443                   diag::err_operator_overload_post_incdec_must_be_int)
15444         << LastParam->getType() << (Op == OO_MinusMinus);
15445   }
15446 
15447   return false;
15448 }
15449 
15450 static bool
15451 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15452                                           FunctionTemplateDecl *TpDecl) {
15453   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15454 
15455   // Must have one or two template parameters.
15456   if (TemplateParams->size() == 1) {
15457     NonTypeTemplateParmDecl *PmDecl =
15458         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15459 
15460     // The template parameter must be a char parameter pack.
15461     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15462         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15463       return false;
15464 
15465   } else if (TemplateParams->size() == 2) {
15466     TemplateTypeParmDecl *PmType =
15467         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15468     NonTypeTemplateParmDecl *PmArgs =
15469         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15470 
15471     // The second template parameter must be a parameter pack with the
15472     // first template parameter as its type.
15473     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15474         PmArgs->isTemplateParameterPack()) {
15475       const TemplateTypeParmType *TArgs =
15476           PmArgs->getType()->getAs<TemplateTypeParmType>();
15477       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15478           TArgs->getIndex() == PmType->getIndex()) {
15479         if (!SemaRef.inTemplateInstantiation())
15480           SemaRef.Diag(TpDecl->getLocation(),
15481                        diag::ext_string_literal_operator_template);
15482         return false;
15483       }
15484     }
15485   }
15486 
15487   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15488                diag::err_literal_operator_template)
15489       << TpDecl->getTemplateParameters()->getSourceRange();
15490   return true;
15491 }
15492 
15493 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15494 /// of this literal operator function is well-formed. If so, returns
15495 /// false; otherwise, emits appropriate diagnostics and returns true.
15496 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15497   if (isa<CXXMethodDecl>(FnDecl)) {
15498     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15499       << FnDecl->getDeclName();
15500     return true;
15501   }
15502 
15503   if (FnDecl->isExternC()) {
15504     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15505     if (const LinkageSpecDecl *LSD =
15506             FnDecl->getDeclContext()->getExternCContext())
15507       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15508     return true;
15509   }
15510 
15511   // This might be the definition of a literal operator template.
15512   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15513 
15514   // This might be a specialization of a literal operator template.
15515   if (!TpDecl)
15516     TpDecl = FnDecl->getPrimaryTemplate();
15517 
15518   // template <char...> type operator "" name() and
15519   // template <class T, T...> type operator "" name() are the only valid
15520   // template signatures, and the only valid signatures with no parameters.
15521   if (TpDecl) {
15522     if (FnDecl->param_size() != 0) {
15523       Diag(FnDecl->getLocation(),
15524            diag::err_literal_operator_template_with_params);
15525       return true;
15526     }
15527 
15528     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15529       return true;
15530 
15531   } else if (FnDecl->param_size() == 1) {
15532     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15533 
15534     QualType ParamType = Param->getType().getUnqualifiedType();
15535 
15536     // Only unsigned long long int, long double, any character type, and const
15537     // char * are allowed as the only parameters.
15538     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15539         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15540         Context.hasSameType(ParamType, Context.CharTy) ||
15541         Context.hasSameType(ParamType, Context.WideCharTy) ||
15542         Context.hasSameType(ParamType, Context.Char8Ty) ||
15543         Context.hasSameType(ParamType, Context.Char16Ty) ||
15544         Context.hasSameType(ParamType, Context.Char32Ty)) {
15545     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15546       QualType InnerType = Ptr->getPointeeType();
15547 
15548       // Pointer parameter must be a const char *.
15549       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15550                                 Context.CharTy) &&
15551             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15552         Diag(Param->getSourceRange().getBegin(),
15553              diag::err_literal_operator_param)
15554             << ParamType << "'const char *'" << Param->getSourceRange();
15555         return true;
15556       }
15557 
15558     } else if (ParamType->isRealFloatingType()) {
15559       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15560           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15561       return true;
15562 
15563     } else if (ParamType->isIntegerType()) {
15564       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15565           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15566       return true;
15567 
15568     } else {
15569       Diag(Param->getSourceRange().getBegin(),
15570            diag::err_literal_operator_invalid_param)
15571           << ParamType << Param->getSourceRange();
15572       return true;
15573     }
15574 
15575   } else if (FnDecl->param_size() == 2) {
15576     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15577 
15578     // First, verify that the first parameter is correct.
15579 
15580     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15581 
15582     // Two parameter function must have a pointer to const as a
15583     // first parameter; let's strip those qualifiers.
15584     const PointerType *PT = FirstParamType->getAs<PointerType>();
15585 
15586     if (!PT) {
15587       Diag((*Param)->getSourceRange().getBegin(),
15588            diag::err_literal_operator_param)
15589           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15590       return true;
15591     }
15592 
15593     QualType PointeeType = PT->getPointeeType();
15594     // First parameter must be const
15595     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15596       Diag((*Param)->getSourceRange().getBegin(),
15597            diag::err_literal_operator_param)
15598           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15599       return true;
15600     }
15601 
15602     QualType InnerType = PointeeType.getUnqualifiedType();
15603     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15604     // const char32_t* are allowed as the first parameter to a two-parameter
15605     // function
15606     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15607           Context.hasSameType(InnerType, Context.WideCharTy) ||
15608           Context.hasSameType(InnerType, Context.Char8Ty) ||
15609           Context.hasSameType(InnerType, Context.Char16Ty) ||
15610           Context.hasSameType(InnerType, Context.Char32Ty))) {
15611       Diag((*Param)->getSourceRange().getBegin(),
15612            diag::err_literal_operator_param)
15613           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15614       return true;
15615     }
15616 
15617     // Move on to the second and final parameter.
15618     ++Param;
15619 
15620     // The second parameter must be a std::size_t.
15621     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15622     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15623       Diag((*Param)->getSourceRange().getBegin(),
15624            diag::err_literal_operator_param)
15625           << SecondParamType << Context.getSizeType()
15626           << (*Param)->getSourceRange();
15627       return true;
15628     }
15629   } else {
15630     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15631     return true;
15632   }
15633 
15634   // Parameters are good.
15635 
15636   // A parameter-declaration-clause containing a default argument is not
15637   // equivalent to any of the permitted forms.
15638   for (auto Param : FnDecl->parameters()) {
15639     if (Param->hasDefaultArg()) {
15640       Diag(Param->getDefaultArgRange().getBegin(),
15641            diag::err_literal_operator_default_argument)
15642         << Param->getDefaultArgRange();
15643       break;
15644     }
15645   }
15646 
15647   StringRef LiteralName
15648     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15649   if (LiteralName[0] != '_' &&
15650       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15651     // C++11 [usrlit.suffix]p1:
15652     //   Literal suffix identifiers that do not start with an underscore
15653     //   are reserved for future standardization.
15654     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15655       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15656   }
15657 
15658   return false;
15659 }
15660 
15661 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15662 /// linkage specification, including the language and (if present)
15663 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15664 /// language string literal. LBraceLoc, if valid, provides the location of
15665 /// the '{' brace. Otherwise, this linkage specification does not
15666 /// have any braces.
15667 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15668                                            Expr *LangStr,
15669                                            SourceLocation LBraceLoc) {
15670   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15671   if (!Lit->isAscii()) {
15672     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15673       << LangStr->getSourceRange();
15674     return nullptr;
15675   }
15676 
15677   StringRef Lang = Lit->getString();
15678   LinkageSpecDecl::LanguageIDs Language;
15679   if (Lang == "C")
15680     Language = LinkageSpecDecl::lang_c;
15681   else if (Lang == "C++")
15682     Language = LinkageSpecDecl::lang_cxx;
15683   else {
15684     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15685       << LangStr->getSourceRange();
15686     return nullptr;
15687   }
15688 
15689   // FIXME: Add all the various semantics of linkage specifications
15690 
15691   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15692                                                LangStr->getExprLoc(), Language,
15693                                                LBraceLoc.isValid());
15694   CurContext->addDecl(D);
15695   PushDeclContext(S, D);
15696   return D;
15697 }
15698 
15699 /// ActOnFinishLinkageSpecification - Complete the definition of
15700 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15701 /// valid, it's the position of the closing '}' brace in a linkage
15702 /// specification that uses braces.
15703 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15704                                             Decl *LinkageSpec,
15705                                             SourceLocation RBraceLoc) {
15706   if (RBraceLoc.isValid()) {
15707     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15708     LSDecl->setRBraceLoc(RBraceLoc);
15709   }
15710   PopDeclContext();
15711   return LinkageSpec;
15712 }
15713 
15714 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15715                                   const ParsedAttributesView &AttrList,
15716                                   SourceLocation SemiLoc) {
15717   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15718   // Attribute declarations appertain to empty declaration so we handle
15719   // them here.
15720   ProcessDeclAttributeList(S, ED, AttrList);
15721 
15722   CurContext->addDecl(ED);
15723   return ED;
15724 }
15725 
15726 /// Perform semantic analysis for the variable declaration that
15727 /// occurs within a C++ catch clause, returning the newly-created
15728 /// variable.
15729 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15730                                          TypeSourceInfo *TInfo,
15731                                          SourceLocation StartLoc,
15732                                          SourceLocation Loc,
15733                                          IdentifierInfo *Name) {
15734   bool Invalid = false;
15735   QualType ExDeclType = TInfo->getType();
15736 
15737   // Arrays and functions decay.
15738   if (ExDeclType->isArrayType())
15739     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15740   else if (ExDeclType->isFunctionType())
15741     ExDeclType = Context.getPointerType(ExDeclType);
15742 
15743   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15744   // The exception-declaration shall not denote a pointer or reference to an
15745   // incomplete type, other than [cv] void*.
15746   // N2844 forbids rvalue references.
15747   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15748     Diag(Loc, diag::err_catch_rvalue_ref);
15749     Invalid = true;
15750   }
15751 
15752   if (ExDeclType->isVariablyModifiedType()) {
15753     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15754     Invalid = true;
15755   }
15756 
15757   QualType BaseType = ExDeclType;
15758   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15759   unsigned DK = diag::err_catch_incomplete;
15760   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15761     BaseType = Ptr->getPointeeType();
15762     Mode = 1;
15763     DK = diag::err_catch_incomplete_ptr;
15764   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15765     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15766     BaseType = Ref->getPointeeType();
15767     Mode = 2;
15768     DK = diag::err_catch_incomplete_ref;
15769   }
15770   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15771       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15772     Invalid = true;
15773 
15774   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15775     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15776     Invalid = true;
15777   }
15778 
15779   if (!Invalid && !ExDeclType->isDependentType() &&
15780       RequireNonAbstractType(Loc, ExDeclType,
15781                              diag::err_abstract_type_in_decl,
15782                              AbstractVariableType))
15783     Invalid = true;
15784 
15785   // Only the non-fragile NeXT runtime currently supports C++ catches
15786   // of ObjC types, and no runtime supports catching ObjC types by value.
15787   if (!Invalid && getLangOpts().ObjC) {
15788     QualType T = ExDeclType;
15789     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15790       T = RT->getPointeeType();
15791 
15792     if (T->isObjCObjectType()) {
15793       Diag(Loc, diag::err_objc_object_catch);
15794       Invalid = true;
15795     } else if (T->isObjCObjectPointerType()) {
15796       // FIXME: should this be a test for macosx-fragile specifically?
15797       if (getLangOpts().ObjCRuntime.isFragile())
15798         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15799     }
15800   }
15801 
15802   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15803                                     ExDeclType, TInfo, SC_None);
15804   ExDecl->setExceptionVariable(true);
15805 
15806   // In ARC, infer 'retaining' for variables of retainable type.
15807   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15808     Invalid = true;
15809 
15810   if (!Invalid && !ExDeclType->isDependentType()) {
15811     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15812       // Insulate this from anything else we might currently be parsing.
15813       EnterExpressionEvaluationContext scope(
15814           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15815 
15816       // C++ [except.handle]p16:
15817       //   The object declared in an exception-declaration or, if the
15818       //   exception-declaration does not specify a name, a temporary (12.2) is
15819       //   copy-initialized (8.5) from the exception object. [...]
15820       //   The object is destroyed when the handler exits, after the destruction
15821       //   of any automatic objects initialized within the handler.
15822       //
15823       // We just pretend to initialize the object with itself, then make sure
15824       // it can be destroyed later.
15825       QualType initType = Context.getExceptionObjectType(ExDeclType);
15826 
15827       InitializedEntity entity =
15828         InitializedEntity::InitializeVariable(ExDecl);
15829       InitializationKind initKind =
15830         InitializationKind::CreateCopy(Loc, SourceLocation());
15831 
15832       Expr *opaqueValue =
15833         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15834       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15835       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15836       if (result.isInvalid())
15837         Invalid = true;
15838       else {
15839         // If the constructor used was non-trivial, set this as the
15840         // "initializer".
15841         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15842         if (!construct->getConstructor()->isTrivial()) {
15843           Expr *init = MaybeCreateExprWithCleanups(construct);
15844           ExDecl->setInit(init);
15845         }
15846 
15847         // And make sure it's destructable.
15848         FinalizeVarWithDestructor(ExDecl, recordType);
15849       }
15850     }
15851   }
15852 
15853   if (Invalid)
15854     ExDecl->setInvalidDecl();
15855 
15856   return ExDecl;
15857 }
15858 
15859 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15860 /// handler.
15861 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15862   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15863   bool Invalid = D.isInvalidType();
15864 
15865   // Check for unexpanded parameter packs.
15866   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15867                                       UPPC_ExceptionType)) {
15868     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15869                                              D.getIdentifierLoc());
15870     Invalid = true;
15871   }
15872 
15873   IdentifierInfo *II = D.getIdentifier();
15874   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15875                                              LookupOrdinaryName,
15876                                              ForVisibleRedeclaration)) {
15877     // The scope should be freshly made just for us. There is just no way
15878     // it contains any previous declaration, except for function parameters in
15879     // a function-try-block's catch statement.
15880     assert(!S->isDeclScope(PrevDecl));
15881     if (isDeclInScope(PrevDecl, CurContext, S)) {
15882       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15883         << D.getIdentifier();
15884       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15885       Invalid = true;
15886     } else if (PrevDecl->isTemplateParameter())
15887       // Maybe we will complain about the shadowed template parameter.
15888       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15889   }
15890 
15891   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15892     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15893       << D.getCXXScopeSpec().getRange();
15894     Invalid = true;
15895   }
15896 
15897   VarDecl *ExDecl = BuildExceptionDeclaration(
15898       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15899   if (Invalid)
15900     ExDecl->setInvalidDecl();
15901 
15902   // Add the exception declaration into this scope.
15903   if (II)
15904     PushOnScopeChains(ExDecl, S);
15905   else
15906     CurContext->addDecl(ExDecl);
15907 
15908   ProcessDeclAttributes(S, ExDecl, D);
15909   return ExDecl;
15910 }
15911 
15912 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15913                                          Expr *AssertExpr,
15914                                          Expr *AssertMessageExpr,
15915                                          SourceLocation RParenLoc) {
15916   StringLiteral *AssertMessage =
15917       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15918 
15919   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15920     return nullptr;
15921 
15922   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15923                                       AssertMessage, RParenLoc, false);
15924 }
15925 
15926 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15927                                          Expr *AssertExpr,
15928                                          StringLiteral *AssertMessage,
15929                                          SourceLocation RParenLoc,
15930                                          bool Failed) {
15931   assert(AssertExpr != nullptr && "Expected non-null condition");
15932   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15933       !Failed) {
15934     // In a static_assert-declaration, the constant-expression shall be a
15935     // constant expression that can be contextually converted to bool.
15936     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15937     if (Converted.isInvalid())
15938       Failed = true;
15939 
15940     ExprResult FullAssertExpr =
15941         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15942                             /*DiscardedValue*/ false,
15943                             /*IsConstexpr*/ true);
15944     if (FullAssertExpr.isInvalid())
15945       Failed = true;
15946     else
15947       AssertExpr = FullAssertExpr.get();
15948 
15949     llvm::APSInt Cond;
15950     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15951           diag::err_static_assert_expression_is_not_constant,
15952           /*AllowFold=*/false).isInvalid())
15953       Failed = true;
15954 
15955     if (!Failed && !Cond) {
15956       SmallString<256> MsgBuffer;
15957       llvm::raw_svector_ostream Msg(MsgBuffer);
15958       if (AssertMessage)
15959         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
15960 
15961       Expr *InnerCond = nullptr;
15962       std::string InnerCondDescription;
15963       std::tie(InnerCond, InnerCondDescription) =
15964         findFailedBooleanCondition(Converted.get());
15965       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
15966         // Drill down into concept specialization expressions to see why they
15967         // weren't satisfied.
15968         Diag(StaticAssertLoc, diag::err_static_assert_failed)
15969           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
15970         ConstraintSatisfaction Satisfaction;
15971         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
15972           DiagnoseUnsatisfiedConstraint(Satisfaction);
15973       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
15974                            && !isa<IntegerLiteral>(InnerCond)) {
15975         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
15976           << InnerCondDescription << !AssertMessage
15977           << Msg.str() << InnerCond->getSourceRange();
15978       } else {
15979         Diag(StaticAssertLoc, diag::err_static_assert_failed)
15980           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
15981       }
15982       Failed = true;
15983     }
15984   } else {
15985     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
15986                                                     /*DiscardedValue*/false,
15987                                                     /*IsConstexpr*/true);
15988     if (FullAssertExpr.isInvalid())
15989       Failed = true;
15990     else
15991       AssertExpr = FullAssertExpr.get();
15992   }
15993 
15994   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
15995                                         AssertExpr, AssertMessage, RParenLoc,
15996                                         Failed);
15997 
15998   CurContext->addDecl(Decl);
15999   return Decl;
16000 }
16001 
16002 /// Perform semantic analysis of the given friend type declaration.
16003 ///
16004 /// \returns A friend declaration that.
16005 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16006                                       SourceLocation FriendLoc,
16007                                       TypeSourceInfo *TSInfo) {
16008   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16009 
16010   QualType T = TSInfo->getType();
16011   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16012 
16013   // C++03 [class.friend]p2:
16014   //   An elaborated-type-specifier shall be used in a friend declaration
16015   //   for a class.*
16016   //
16017   //   * The class-key of the elaborated-type-specifier is required.
16018   if (!CodeSynthesisContexts.empty()) {
16019     // Do not complain about the form of friend template types during any kind
16020     // of code synthesis. For template instantiation, we will have complained
16021     // when the template was defined.
16022   } else {
16023     if (!T->isElaboratedTypeSpecifier()) {
16024       // If we evaluated the type to a record type, suggest putting
16025       // a tag in front.
16026       if (const RecordType *RT = T->getAs<RecordType>()) {
16027         RecordDecl *RD = RT->getDecl();
16028 
16029         SmallString<16> InsertionText(" ");
16030         InsertionText += RD->getKindName();
16031 
16032         Diag(TypeRange.getBegin(),
16033              getLangOpts().CPlusPlus11 ?
16034                diag::warn_cxx98_compat_unelaborated_friend_type :
16035                diag::ext_unelaborated_friend_type)
16036           << (unsigned) RD->getTagKind()
16037           << T
16038           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16039                                         InsertionText);
16040       } else {
16041         Diag(FriendLoc,
16042              getLangOpts().CPlusPlus11 ?
16043                diag::warn_cxx98_compat_nonclass_type_friend :
16044                diag::ext_nonclass_type_friend)
16045           << T
16046           << TypeRange;
16047       }
16048     } else if (T->getAs<EnumType>()) {
16049       Diag(FriendLoc,
16050            getLangOpts().CPlusPlus11 ?
16051              diag::warn_cxx98_compat_enum_friend :
16052              diag::ext_enum_friend)
16053         << T
16054         << TypeRange;
16055     }
16056 
16057     // C++11 [class.friend]p3:
16058     //   A friend declaration that does not declare a function shall have one
16059     //   of the following forms:
16060     //     friend elaborated-type-specifier ;
16061     //     friend simple-type-specifier ;
16062     //     friend typename-specifier ;
16063     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16064       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16065   }
16066 
16067   //   If the type specifier in a friend declaration designates a (possibly
16068   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16069   //   the friend declaration is ignored.
16070   return FriendDecl::Create(Context, CurContext,
16071                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16072                             FriendLoc);
16073 }
16074 
16075 /// Handle a friend tag declaration where the scope specifier was
16076 /// templated.
16077 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16078                                     unsigned TagSpec, SourceLocation TagLoc,
16079                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16080                                     SourceLocation NameLoc,
16081                                     const ParsedAttributesView &Attr,
16082                                     MultiTemplateParamsArg TempParamLists) {
16083   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16084 
16085   bool IsMemberSpecialization = false;
16086   bool Invalid = false;
16087 
16088   if (TemplateParameterList *TemplateParams =
16089           MatchTemplateParametersToScopeSpecifier(
16090               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16091               IsMemberSpecialization, Invalid)) {
16092     if (TemplateParams->size() > 0) {
16093       // This is a declaration of a class template.
16094       if (Invalid)
16095         return nullptr;
16096 
16097       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16098                                 NameLoc, Attr, TemplateParams, AS_public,
16099                                 /*ModulePrivateLoc=*/SourceLocation(),
16100                                 FriendLoc, TempParamLists.size() - 1,
16101                                 TempParamLists.data()).get();
16102     } else {
16103       // The "template<>" header is extraneous.
16104       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16105         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16106       IsMemberSpecialization = true;
16107     }
16108   }
16109 
16110   if (Invalid) return nullptr;
16111 
16112   bool isAllExplicitSpecializations = true;
16113   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16114     if (TempParamLists[I]->size()) {
16115       isAllExplicitSpecializations = false;
16116       break;
16117     }
16118   }
16119 
16120   // FIXME: don't ignore attributes.
16121 
16122   // If it's explicit specializations all the way down, just forget
16123   // about the template header and build an appropriate non-templated
16124   // friend.  TODO: for source fidelity, remember the headers.
16125   if (isAllExplicitSpecializations) {
16126     if (SS.isEmpty()) {
16127       bool Owned = false;
16128       bool IsDependent = false;
16129       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16130                       Attr, AS_public,
16131                       /*ModulePrivateLoc=*/SourceLocation(),
16132                       MultiTemplateParamsArg(), Owned, IsDependent,
16133                       /*ScopedEnumKWLoc=*/SourceLocation(),
16134                       /*ScopedEnumUsesClassTag=*/false,
16135                       /*UnderlyingType=*/TypeResult(),
16136                       /*IsTypeSpecifier=*/false,
16137                       /*IsTemplateParamOrArg=*/false);
16138     }
16139 
16140     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16141     ElaboratedTypeKeyword Keyword
16142       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16143     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16144                                    *Name, NameLoc);
16145     if (T.isNull())
16146       return nullptr;
16147 
16148     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16149     if (isa<DependentNameType>(T)) {
16150       DependentNameTypeLoc TL =
16151           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16152       TL.setElaboratedKeywordLoc(TagLoc);
16153       TL.setQualifierLoc(QualifierLoc);
16154       TL.setNameLoc(NameLoc);
16155     } else {
16156       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16157       TL.setElaboratedKeywordLoc(TagLoc);
16158       TL.setQualifierLoc(QualifierLoc);
16159       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16160     }
16161 
16162     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16163                                             TSI, FriendLoc, TempParamLists);
16164     Friend->setAccess(AS_public);
16165     CurContext->addDecl(Friend);
16166     return Friend;
16167   }
16168 
16169   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16170 
16171 
16172 
16173   // Handle the case of a templated-scope friend class.  e.g.
16174   //   template <class T> class A<T>::B;
16175   // FIXME: we don't support these right now.
16176   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16177     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16178   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16179   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16180   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16181   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16182   TL.setElaboratedKeywordLoc(TagLoc);
16183   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16184   TL.setNameLoc(NameLoc);
16185 
16186   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16187                                           TSI, FriendLoc, TempParamLists);
16188   Friend->setAccess(AS_public);
16189   Friend->setUnsupportedFriend(true);
16190   CurContext->addDecl(Friend);
16191   return Friend;
16192 }
16193 
16194 /// Handle a friend type declaration.  This works in tandem with
16195 /// ActOnTag.
16196 ///
16197 /// Notes on friend class templates:
16198 ///
16199 /// We generally treat friend class declarations as if they were
16200 /// declaring a class.  So, for example, the elaborated type specifier
16201 /// in a friend declaration is required to obey the restrictions of a
16202 /// class-head (i.e. no typedefs in the scope chain), template
16203 /// parameters are required to match up with simple template-ids, &c.
16204 /// However, unlike when declaring a template specialization, it's
16205 /// okay to refer to a template specialization without an empty
16206 /// template parameter declaration, e.g.
16207 ///   friend class A<T>::B<unsigned>;
16208 /// We permit this as a special case; if there are any template
16209 /// parameters present at all, require proper matching, i.e.
16210 ///   template <> template \<class T> friend class A<int>::B;
16211 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16212                                 MultiTemplateParamsArg TempParams) {
16213   SourceLocation Loc = DS.getBeginLoc();
16214 
16215   assert(DS.isFriendSpecified());
16216   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16217 
16218   // C++ [class.friend]p3:
16219   // A friend declaration that does not declare a function shall have one of
16220   // the following forms:
16221   //     friend elaborated-type-specifier ;
16222   //     friend simple-type-specifier ;
16223   //     friend typename-specifier ;
16224   //
16225   // Any declaration with a type qualifier does not have that form. (It's
16226   // legal to specify a qualified type as a friend, you just can't write the
16227   // keywords.)
16228   if (DS.getTypeQualifiers()) {
16229     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16230       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16231     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16232       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16233     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16234       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16235     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16236       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16237     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16238       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16239   }
16240 
16241   // Try to convert the decl specifier to a type.  This works for
16242   // friend templates because ActOnTag never produces a ClassTemplateDecl
16243   // for a TUK_Friend.
16244   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16245   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16246   QualType T = TSI->getType();
16247   if (TheDeclarator.isInvalidType())
16248     return nullptr;
16249 
16250   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16251     return nullptr;
16252 
16253   // This is definitely an error in C++98.  It's probably meant to
16254   // be forbidden in C++0x, too, but the specification is just
16255   // poorly written.
16256   //
16257   // The problem is with declarations like the following:
16258   //   template <T> friend A<T>::foo;
16259   // where deciding whether a class C is a friend or not now hinges
16260   // on whether there exists an instantiation of A that causes
16261   // 'foo' to equal C.  There are restrictions on class-heads
16262   // (which we declare (by fiat) elaborated friend declarations to
16263   // be) that makes this tractable.
16264   //
16265   // FIXME: handle "template <> friend class A<T>;", which
16266   // is possibly well-formed?  Who even knows?
16267   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16268     Diag(Loc, diag::err_tagless_friend_type_template)
16269       << DS.getSourceRange();
16270     return nullptr;
16271   }
16272 
16273   // C++98 [class.friend]p1: A friend of a class is a function
16274   //   or class that is not a member of the class . . .
16275   // This is fixed in DR77, which just barely didn't make the C++03
16276   // deadline.  It's also a very silly restriction that seriously
16277   // affects inner classes and which nobody else seems to implement;
16278   // thus we never diagnose it, not even in -pedantic.
16279   //
16280   // But note that we could warn about it: it's always useless to
16281   // friend one of your own members (it's not, however, worthless to
16282   // friend a member of an arbitrary specialization of your template).
16283 
16284   Decl *D;
16285   if (!TempParams.empty())
16286     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16287                                    TempParams,
16288                                    TSI,
16289                                    DS.getFriendSpecLoc());
16290   else
16291     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16292 
16293   if (!D)
16294     return nullptr;
16295 
16296   D->setAccess(AS_public);
16297   CurContext->addDecl(D);
16298 
16299   return D;
16300 }
16301 
16302 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16303                                         MultiTemplateParamsArg TemplateParams) {
16304   const DeclSpec &DS = D.getDeclSpec();
16305 
16306   assert(DS.isFriendSpecified());
16307   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16308 
16309   SourceLocation Loc = D.getIdentifierLoc();
16310   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16311 
16312   // C++ [class.friend]p1
16313   //   A friend of a class is a function or class....
16314   // Note that this sees through typedefs, which is intended.
16315   // It *doesn't* see through dependent types, which is correct
16316   // according to [temp.arg.type]p3:
16317   //   If a declaration acquires a function type through a
16318   //   type dependent on a template-parameter and this causes
16319   //   a declaration that does not use the syntactic form of a
16320   //   function declarator to have a function type, the program
16321   //   is ill-formed.
16322   if (!TInfo->getType()->isFunctionType()) {
16323     Diag(Loc, diag::err_unexpected_friend);
16324 
16325     // It might be worthwhile to try to recover by creating an
16326     // appropriate declaration.
16327     return nullptr;
16328   }
16329 
16330   // C++ [namespace.memdef]p3
16331   //  - If a friend declaration in a non-local class first declares a
16332   //    class or function, the friend class or function is a member
16333   //    of the innermost enclosing namespace.
16334   //  - The name of the friend is not found by simple name lookup
16335   //    until a matching declaration is provided in that namespace
16336   //    scope (either before or after the class declaration granting
16337   //    friendship).
16338   //  - If a friend function is called, its name may be found by the
16339   //    name lookup that considers functions from namespaces and
16340   //    classes associated with the types of the function arguments.
16341   //  - When looking for a prior declaration of a class or a function
16342   //    declared as a friend, scopes outside the innermost enclosing
16343   //    namespace scope are not considered.
16344 
16345   CXXScopeSpec &SS = D.getCXXScopeSpec();
16346   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16347   assert(NameInfo.getName());
16348 
16349   // Check for unexpanded parameter packs.
16350   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16351       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16352       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16353     return nullptr;
16354 
16355   // The context we found the declaration in, or in which we should
16356   // create the declaration.
16357   DeclContext *DC;
16358   Scope *DCScope = S;
16359   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16360                         ForExternalRedeclaration);
16361 
16362   // There are five cases here.
16363   //   - There's no scope specifier and we're in a local class. Only look
16364   //     for functions declared in the immediately-enclosing block scope.
16365   // We recover from invalid scope qualifiers as if they just weren't there.
16366   FunctionDecl *FunctionContainingLocalClass = nullptr;
16367   if ((SS.isInvalid() || !SS.isSet()) &&
16368       (FunctionContainingLocalClass =
16369            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16370     // C++11 [class.friend]p11:
16371     //   If a friend declaration appears in a local class and the name
16372     //   specified is an unqualified name, a prior declaration is
16373     //   looked up without considering scopes that are outside the
16374     //   innermost enclosing non-class scope. For a friend function
16375     //   declaration, if there is no prior declaration, the program is
16376     //   ill-formed.
16377 
16378     // Find the innermost enclosing non-class scope. This is the block
16379     // scope containing the local class definition (or for a nested class,
16380     // the outer local class).
16381     DCScope = S->getFnParent();
16382 
16383     // Look up the function name in the scope.
16384     Previous.clear(LookupLocalFriendName);
16385     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16386 
16387     if (!Previous.empty()) {
16388       // All possible previous declarations must have the same context:
16389       // either they were declared at block scope or they are members of
16390       // one of the enclosing local classes.
16391       DC = Previous.getRepresentativeDecl()->getDeclContext();
16392     } else {
16393       // This is ill-formed, but provide the context that we would have
16394       // declared the function in, if we were permitted to, for error recovery.
16395       DC = FunctionContainingLocalClass;
16396     }
16397     adjustContextForLocalExternDecl(DC);
16398 
16399     // C++ [class.friend]p6:
16400     //   A function can be defined in a friend declaration of a class if and
16401     //   only if the class is a non-local class (9.8), the function name is
16402     //   unqualified, and the function has namespace scope.
16403     if (D.isFunctionDefinition()) {
16404       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16405     }
16406 
16407   //   - There's no scope specifier, in which case we just go to the
16408   //     appropriate scope and look for a function or function template
16409   //     there as appropriate.
16410   } else if (SS.isInvalid() || !SS.isSet()) {
16411     // C++11 [namespace.memdef]p3:
16412     //   If the name in a friend declaration is neither qualified nor
16413     //   a template-id and the declaration is a function or an
16414     //   elaborated-type-specifier, the lookup to determine whether
16415     //   the entity has been previously declared shall not consider
16416     //   any scopes outside the innermost enclosing namespace.
16417     bool isTemplateId =
16418         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16419 
16420     // Find the appropriate context according to the above.
16421     DC = CurContext;
16422 
16423     // Skip class contexts.  If someone can cite chapter and verse
16424     // for this behavior, that would be nice --- it's what GCC and
16425     // EDG do, and it seems like a reasonable intent, but the spec
16426     // really only says that checks for unqualified existing
16427     // declarations should stop at the nearest enclosing namespace,
16428     // not that they should only consider the nearest enclosing
16429     // namespace.
16430     while (DC->isRecord())
16431       DC = DC->getParent();
16432 
16433     DeclContext *LookupDC = DC;
16434     while (LookupDC->isTransparentContext())
16435       LookupDC = LookupDC->getParent();
16436 
16437     while (true) {
16438       LookupQualifiedName(Previous, LookupDC);
16439 
16440       if (!Previous.empty()) {
16441         DC = LookupDC;
16442         break;
16443       }
16444 
16445       if (isTemplateId) {
16446         if (isa<TranslationUnitDecl>(LookupDC)) break;
16447       } else {
16448         if (LookupDC->isFileContext()) break;
16449       }
16450       LookupDC = LookupDC->getParent();
16451     }
16452 
16453     DCScope = getScopeForDeclContext(S, DC);
16454 
16455   //   - There's a non-dependent scope specifier, in which case we
16456   //     compute it and do a previous lookup there for a function
16457   //     or function template.
16458   } else if (!SS.getScopeRep()->isDependent()) {
16459     DC = computeDeclContext(SS);
16460     if (!DC) return nullptr;
16461 
16462     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16463 
16464     LookupQualifiedName(Previous, DC);
16465 
16466     // C++ [class.friend]p1: A friend of a class is a function or
16467     //   class that is not a member of the class . . .
16468     if (DC->Equals(CurContext))
16469       Diag(DS.getFriendSpecLoc(),
16470            getLangOpts().CPlusPlus11 ?
16471              diag::warn_cxx98_compat_friend_is_member :
16472              diag::err_friend_is_member);
16473 
16474     if (D.isFunctionDefinition()) {
16475       // C++ [class.friend]p6:
16476       //   A function can be defined in a friend declaration of a class if and
16477       //   only if the class is a non-local class (9.8), the function name is
16478       //   unqualified, and the function has namespace scope.
16479       //
16480       // FIXME: We should only do this if the scope specifier names the
16481       // innermost enclosing namespace; otherwise the fixit changes the
16482       // meaning of the code.
16483       SemaDiagnosticBuilder DB
16484         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16485 
16486       DB << SS.getScopeRep();
16487       if (DC->isFileContext())
16488         DB << FixItHint::CreateRemoval(SS.getRange());
16489       SS.clear();
16490     }
16491 
16492   //   - There's a scope specifier that does not match any template
16493   //     parameter lists, in which case we use some arbitrary context,
16494   //     create a method or method template, and wait for instantiation.
16495   //   - There's a scope specifier that does match some template
16496   //     parameter lists, which we don't handle right now.
16497   } else {
16498     if (D.isFunctionDefinition()) {
16499       // C++ [class.friend]p6:
16500       //   A function can be defined in a friend declaration of a class if and
16501       //   only if the class is a non-local class (9.8), the function name is
16502       //   unqualified, and the function has namespace scope.
16503       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16504         << SS.getScopeRep();
16505     }
16506 
16507     DC = CurContext;
16508     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16509   }
16510 
16511   if (!DC->isRecord()) {
16512     int DiagArg = -1;
16513     switch (D.getName().getKind()) {
16514     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16515     case UnqualifiedIdKind::IK_ConstructorName:
16516       DiagArg = 0;
16517       break;
16518     case UnqualifiedIdKind::IK_DestructorName:
16519       DiagArg = 1;
16520       break;
16521     case UnqualifiedIdKind::IK_ConversionFunctionId:
16522       DiagArg = 2;
16523       break;
16524     case UnqualifiedIdKind::IK_DeductionGuideName:
16525       DiagArg = 3;
16526       break;
16527     case UnqualifiedIdKind::IK_Identifier:
16528     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16529     case UnqualifiedIdKind::IK_LiteralOperatorId:
16530     case UnqualifiedIdKind::IK_OperatorFunctionId:
16531     case UnqualifiedIdKind::IK_TemplateId:
16532       break;
16533     }
16534     // This implies that it has to be an operator or function.
16535     if (DiagArg >= 0) {
16536       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16537       return nullptr;
16538     }
16539   }
16540 
16541   // FIXME: This is an egregious hack to cope with cases where the scope stack
16542   // does not contain the declaration context, i.e., in an out-of-line
16543   // definition of a class.
16544   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16545   if (!DCScope) {
16546     FakeDCScope.setEntity(DC);
16547     DCScope = &FakeDCScope;
16548   }
16549 
16550   bool AddToScope = true;
16551   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16552                                           TemplateParams, AddToScope);
16553   if (!ND) return nullptr;
16554 
16555   assert(ND->getLexicalDeclContext() == CurContext);
16556 
16557   // If we performed typo correction, we might have added a scope specifier
16558   // and changed the decl context.
16559   DC = ND->getDeclContext();
16560 
16561   // Add the function declaration to the appropriate lookup tables,
16562   // adjusting the redeclarations list as necessary.  We don't
16563   // want to do this yet if the friending class is dependent.
16564   //
16565   // Also update the scope-based lookup if the target context's
16566   // lookup context is in lexical scope.
16567   if (!CurContext->isDependentContext()) {
16568     DC = DC->getRedeclContext();
16569     DC->makeDeclVisibleInContext(ND);
16570     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16571       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16572   }
16573 
16574   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16575                                        D.getIdentifierLoc(), ND,
16576                                        DS.getFriendSpecLoc());
16577   FrD->setAccess(AS_public);
16578   CurContext->addDecl(FrD);
16579 
16580   if (ND->isInvalidDecl()) {
16581     FrD->setInvalidDecl();
16582   } else {
16583     if (DC->isRecord()) CheckFriendAccess(ND);
16584 
16585     FunctionDecl *FD;
16586     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16587       FD = FTD->getTemplatedDecl();
16588     else
16589       FD = cast<FunctionDecl>(ND);
16590 
16591     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16592     // default argument expression, that declaration shall be a definition
16593     // and shall be the only declaration of the function or function
16594     // template in the translation unit.
16595     if (functionDeclHasDefaultArgument(FD)) {
16596       // We can't look at FD->getPreviousDecl() because it may not have been set
16597       // if we're in a dependent context. If the function is known to be a
16598       // redeclaration, we will have narrowed Previous down to the right decl.
16599       if (D.isRedeclaration()) {
16600         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16601         Diag(Previous.getRepresentativeDecl()->getLocation(),
16602              diag::note_previous_declaration);
16603       } else if (!D.isFunctionDefinition())
16604         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16605     }
16606 
16607     // Mark templated-scope function declarations as unsupported.
16608     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16609       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16610         << SS.getScopeRep() << SS.getRange()
16611         << cast<CXXRecordDecl>(CurContext);
16612       FrD->setUnsupportedFriend(true);
16613     }
16614   }
16615 
16616   return ND;
16617 }
16618 
16619 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16620   AdjustDeclIfTemplate(Dcl);
16621 
16622   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16623   if (!Fn) {
16624     Diag(DelLoc, diag::err_deleted_non_function);
16625     return;
16626   }
16627 
16628   // Deleted function does not have a body.
16629   Fn->setWillHaveBody(false);
16630 
16631   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16632     // Don't consider the implicit declaration we generate for explicit
16633     // specializations. FIXME: Do not generate these implicit declarations.
16634     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16635          Prev->getPreviousDecl()) &&
16636         !Prev->isDefined()) {
16637       Diag(DelLoc, diag::err_deleted_decl_not_first);
16638       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16639            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16640                               : diag::note_previous_declaration);
16641       // We can't recover from this; the declaration might have already
16642       // been used.
16643       Fn->setInvalidDecl();
16644       return;
16645     }
16646 
16647     // To maintain the invariant that functions are only deleted on their first
16648     // declaration, mark the implicitly-instantiated declaration of the
16649     // explicitly-specialized function as deleted instead of marking the
16650     // instantiated redeclaration.
16651     Fn = Fn->getCanonicalDecl();
16652   }
16653 
16654   // dllimport/dllexport cannot be deleted.
16655   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16656     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16657     Fn->setInvalidDecl();
16658   }
16659 
16660   // C++11 [basic.start.main]p3:
16661   //   A program that defines main as deleted [...] is ill-formed.
16662   if (Fn->isMain())
16663     Diag(DelLoc, diag::err_deleted_main);
16664 
16665   // C++11 [dcl.fct.def.delete]p4:
16666   //  A deleted function is implicitly inline.
16667   Fn->setImplicitlyInline();
16668   Fn->setDeletedAsWritten();
16669 }
16670 
16671 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16672   if (!Dcl || Dcl->isInvalidDecl())
16673     return;
16674 
16675   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16676   if (!FD) {
16677     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16678       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16679         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16680         return;
16681       }
16682     }
16683 
16684     Diag(DefaultLoc, diag::err_default_special_members)
16685         << getLangOpts().CPlusPlus20;
16686     return;
16687   }
16688 
16689   // Reject if this can't possibly be a defaultable function.
16690   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16691   if (!DefKind &&
16692       // A dependent function that doesn't locally look defaultable can
16693       // still instantiate to a defaultable function if it's a constructor
16694       // or assignment operator.
16695       (!FD->isDependentContext() ||
16696        (!isa<CXXConstructorDecl>(FD) &&
16697         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16698     Diag(DefaultLoc, diag::err_default_special_members)
16699         << getLangOpts().CPlusPlus20;
16700     return;
16701   }
16702 
16703   if (DefKind.isComparison() &&
16704       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16705     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16706         << (int)DefKind.asComparison();
16707     return;
16708   }
16709 
16710   // Issue compatibility warning. We already warned if the operator is
16711   // 'operator<=>' when parsing the '<=>' token.
16712   if (DefKind.isComparison() &&
16713       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16714     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16715                          ? diag::warn_cxx17_compat_defaulted_comparison
16716                          : diag::ext_defaulted_comparison);
16717   }
16718 
16719   FD->setDefaulted();
16720   FD->setExplicitlyDefaulted();
16721 
16722   // Defer checking functions that are defaulted in a dependent context.
16723   if (FD->isDependentContext())
16724     return;
16725 
16726   // Unset that we will have a body for this function. We might not,
16727   // if it turns out to be trivial, and we don't need this marking now
16728   // that we've marked it as defaulted.
16729   FD->setWillHaveBody(false);
16730 
16731   // If this definition appears within the record, do the checking when
16732   // the record is complete. This is always the case for a defaulted
16733   // comparison.
16734   if (DefKind.isComparison())
16735     return;
16736   auto *MD = cast<CXXMethodDecl>(FD);
16737 
16738   const FunctionDecl *Primary = FD;
16739   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16740     // Ask the template instantiation pattern that actually had the
16741     // '= default' on it.
16742     Primary = Pattern;
16743 
16744   // If the method was defaulted on its first declaration, we will have
16745   // already performed the checking in CheckCompletedCXXClass. Such a
16746   // declaration doesn't trigger an implicit definition.
16747   if (Primary->getCanonicalDecl()->isDefaulted())
16748     return;
16749 
16750   // FIXME: Once we support defining comparisons out of class, check for a
16751   // defaulted comparison here.
16752   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16753     MD->setInvalidDecl();
16754   else
16755     DefineDefaultedFunction(*this, MD, DefaultLoc);
16756 }
16757 
16758 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16759   for (Stmt *SubStmt : S->children()) {
16760     if (!SubStmt)
16761       continue;
16762     if (isa<ReturnStmt>(SubStmt))
16763       Self.Diag(SubStmt->getBeginLoc(),
16764                 diag::err_return_in_constructor_handler);
16765     if (!isa<Expr>(SubStmt))
16766       SearchForReturnInStmt(Self, SubStmt);
16767   }
16768 }
16769 
16770 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16771   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16772     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16773     SearchForReturnInStmt(*this, Handler);
16774   }
16775 }
16776 
16777 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16778                                              const CXXMethodDecl *Old) {
16779   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16780   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16781 
16782   if (OldFT->hasExtParameterInfos()) {
16783     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16784       // A parameter of the overriding method should be annotated with noescape
16785       // if the corresponding parameter of the overridden method is annotated.
16786       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16787           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16788         Diag(New->getParamDecl(I)->getLocation(),
16789              diag::warn_overriding_method_missing_noescape);
16790         Diag(Old->getParamDecl(I)->getLocation(),
16791              diag::note_overridden_marked_noescape);
16792       }
16793   }
16794 
16795   // Virtual overrides must have the same code_seg.
16796   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16797   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16798   if ((NewCSA || OldCSA) &&
16799       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16800     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16801     Diag(Old->getLocation(), diag::note_previous_declaration);
16802     return true;
16803   }
16804 
16805   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16806 
16807   // If the calling conventions match, everything is fine
16808   if (NewCC == OldCC)
16809     return false;
16810 
16811   // If the calling conventions mismatch because the new function is static,
16812   // suppress the calling convention mismatch error; the error about static
16813   // function override (err_static_overrides_virtual from
16814   // Sema::CheckFunctionDeclaration) is more clear.
16815   if (New->getStorageClass() == SC_Static)
16816     return false;
16817 
16818   Diag(New->getLocation(),
16819        diag::err_conflicting_overriding_cc_attributes)
16820     << New->getDeclName() << New->getType() << Old->getType();
16821   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16822   return true;
16823 }
16824 
16825 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16826                                              const CXXMethodDecl *Old) {
16827   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16828   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16829 
16830   if (Context.hasSameType(NewTy, OldTy) ||
16831       NewTy->isDependentType() || OldTy->isDependentType())
16832     return false;
16833 
16834   // Check if the return types are covariant
16835   QualType NewClassTy, OldClassTy;
16836 
16837   /// Both types must be pointers or references to classes.
16838   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16839     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16840       NewClassTy = NewPT->getPointeeType();
16841       OldClassTy = OldPT->getPointeeType();
16842     }
16843   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16844     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16845       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16846         NewClassTy = NewRT->getPointeeType();
16847         OldClassTy = OldRT->getPointeeType();
16848       }
16849     }
16850   }
16851 
16852   // The return types aren't either both pointers or references to a class type.
16853   if (NewClassTy.isNull()) {
16854     Diag(New->getLocation(),
16855          diag::err_different_return_type_for_overriding_virtual_function)
16856         << New->getDeclName() << NewTy << OldTy
16857         << New->getReturnTypeSourceRange();
16858     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16859         << Old->getReturnTypeSourceRange();
16860 
16861     return true;
16862   }
16863 
16864   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16865     // C++14 [class.virtual]p8:
16866     //   If the class type in the covariant return type of D::f differs from
16867     //   that of B::f, the class type in the return type of D::f shall be
16868     //   complete at the point of declaration of D::f or shall be the class
16869     //   type D.
16870     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16871       if (!RT->isBeingDefined() &&
16872           RequireCompleteType(New->getLocation(), NewClassTy,
16873                               diag::err_covariant_return_incomplete,
16874                               New->getDeclName()))
16875         return true;
16876     }
16877 
16878     // Check if the new class derives from the old class.
16879     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16880       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16881           << New->getDeclName() << NewTy << OldTy
16882           << New->getReturnTypeSourceRange();
16883       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16884           << Old->getReturnTypeSourceRange();
16885       return true;
16886     }
16887 
16888     // Check if we the conversion from derived to base is valid.
16889     if (CheckDerivedToBaseConversion(
16890             NewClassTy, OldClassTy,
16891             diag::err_covariant_return_inaccessible_base,
16892             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16893             New->getLocation(), New->getReturnTypeSourceRange(),
16894             New->getDeclName(), nullptr)) {
16895       // FIXME: this note won't trigger for delayed access control
16896       // diagnostics, and it's impossible to get an undelayed error
16897       // here from access control during the original parse because
16898       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16899       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16900           << Old->getReturnTypeSourceRange();
16901       return true;
16902     }
16903   }
16904 
16905   // The qualifiers of the return types must be the same.
16906   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16907     Diag(New->getLocation(),
16908          diag::err_covariant_return_type_different_qualifications)
16909         << New->getDeclName() << NewTy << OldTy
16910         << New->getReturnTypeSourceRange();
16911     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16912         << Old->getReturnTypeSourceRange();
16913     return true;
16914   }
16915 
16916 
16917   // The new class type must have the same or less qualifiers as the old type.
16918   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16919     Diag(New->getLocation(),
16920          diag::err_covariant_return_type_class_type_more_qualified)
16921         << New->getDeclName() << NewTy << OldTy
16922         << New->getReturnTypeSourceRange();
16923     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16924         << Old->getReturnTypeSourceRange();
16925     return true;
16926   }
16927 
16928   return false;
16929 }
16930 
16931 /// Mark the given method pure.
16932 ///
16933 /// \param Method the method to be marked pure.
16934 ///
16935 /// \param InitRange the source range that covers the "0" initializer.
16936 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16937   SourceLocation EndLoc = InitRange.getEnd();
16938   if (EndLoc.isValid())
16939     Method->setRangeEnd(EndLoc);
16940 
16941   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16942     Method->setPure();
16943     return false;
16944   }
16945 
16946   if (!Method->isInvalidDecl())
16947     Diag(Method->getLocation(), diag::err_non_virtual_pure)
16948       << Method->getDeclName() << InitRange;
16949   return true;
16950 }
16951 
16952 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16953   if (D->getFriendObjectKind())
16954     Diag(D->getLocation(), diag::err_pure_friend);
16955   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16956     CheckPureMethod(M, ZeroLoc);
16957   else
16958     Diag(D->getLocation(), diag::err_illegal_initializer);
16959 }
16960 
16961 /// Determine whether the given declaration is a global variable or
16962 /// static data member.
16963 static bool isNonlocalVariable(const Decl *D) {
16964   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
16965     return Var->hasGlobalStorage();
16966 
16967   return false;
16968 }
16969 
16970 /// Invoked when we are about to parse an initializer for the declaration
16971 /// 'Dcl'.
16972 ///
16973 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
16974 /// static data member of class X, names should be looked up in the scope of
16975 /// class X. If the declaration had a scope specifier, a scope will have
16976 /// been created and passed in for this purpose. Otherwise, S will be null.
16977 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
16978   // If there is no declaration, there was an error parsing it.
16979   if (!D || D->isInvalidDecl())
16980     return;
16981 
16982   // We will always have a nested name specifier here, but this declaration
16983   // might not be out of line if the specifier names the current namespace:
16984   //   extern int n;
16985   //   int ::n = 0;
16986   if (S && D->isOutOfLine())
16987     EnterDeclaratorContext(S, D->getDeclContext());
16988 
16989   // If we are parsing the initializer for a static data member, push a
16990   // new expression evaluation context that is associated with this static
16991   // data member.
16992   if (isNonlocalVariable(D))
16993     PushExpressionEvaluationContext(
16994         ExpressionEvaluationContext::PotentiallyEvaluated, D);
16995 }
16996 
16997 /// Invoked after we are finished parsing an initializer for the declaration D.
16998 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
16999   // If there is no declaration, there was an error parsing it.
17000   if (!D || D->isInvalidDecl())
17001     return;
17002 
17003   if (isNonlocalVariable(D))
17004     PopExpressionEvaluationContext();
17005 
17006   if (S && D->isOutOfLine())
17007     ExitDeclaratorContext(S);
17008 }
17009 
17010 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17011 /// C++ if/switch/while/for statement.
17012 /// e.g: "if (int x = f()) {...}"
17013 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17014   // C++ 6.4p2:
17015   // The declarator shall not specify a function or an array.
17016   // The type-specifier-seq shall not contain typedef and shall not declare a
17017   // new class or enumeration.
17018   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17019          "Parser allowed 'typedef' as storage class of condition decl.");
17020 
17021   Decl *Dcl = ActOnDeclarator(S, D);
17022   if (!Dcl)
17023     return true;
17024 
17025   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17026     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17027       << D.getSourceRange();
17028     return true;
17029   }
17030 
17031   return Dcl;
17032 }
17033 
17034 void Sema::LoadExternalVTableUses() {
17035   if (!ExternalSource)
17036     return;
17037 
17038   SmallVector<ExternalVTableUse, 4> VTables;
17039   ExternalSource->ReadUsedVTables(VTables);
17040   SmallVector<VTableUse, 4> NewUses;
17041   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17042     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17043       = VTablesUsed.find(VTables[I].Record);
17044     // Even if a definition wasn't required before, it may be required now.
17045     if (Pos != VTablesUsed.end()) {
17046       if (!Pos->second && VTables[I].DefinitionRequired)
17047         Pos->second = true;
17048       continue;
17049     }
17050 
17051     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17052     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17053   }
17054 
17055   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17056 }
17057 
17058 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17059                           bool DefinitionRequired) {
17060   // Ignore any vtable uses in unevaluated operands or for classes that do
17061   // not have a vtable.
17062   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17063       CurContext->isDependentContext() || isUnevaluatedContext())
17064     return;
17065   // Do not mark as used if compiling for the device outside of the target
17066   // region.
17067   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17068       !isInOpenMPDeclareTargetContext() &&
17069       !isInOpenMPTargetExecutionDirective()) {
17070     if (!DefinitionRequired)
17071       MarkVirtualMembersReferenced(Loc, Class);
17072     return;
17073   }
17074 
17075   // Try to insert this class into the map.
17076   LoadExternalVTableUses();
17077   Class = Class->getCanonicalDecl();
17078   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17079     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17080   if (!Pos.second) {
17081     // If we already had an entry, check to see if we are promoting this vtable
17082     // to require a definition. If so, we need to reappend to the VTableUses
17083     // list, since we may have already processed the first entry.
17084     if (DefinitionRequired && !Pos.first->second) {
17085       Pos.first->second = true;
17086     } else {
17087       // Otherwise, we can early exit.
17088       return;
17089     }
17090   } else {
17091     // The Microsoft ABI requires that we perform the destructor body
17092     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17093     // the deleting destructor is emitted with the vtable, not with the
17094     // destructor definition as in the Itanium ABI.
17095     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17096       CXXDestructorDecl *DD = Class->getDestructor();
17097       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17098         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17099           // If this is an out-of-line declaration, marking it referenced will
17100           // not do anything. Manually call CheckDestructor to look up operator
17101           // delete().
17102           ContextRAII SavedContext(*this, DD);
17103           CheckDestructor(DD);
17104         } else {
17105           MarkFunctionReferenced(Loc, Class->getDestructor());
17106         }
17107       }
17108     }
17109   }
17110 
17111   // Local classes need to have their virtual members marked
17112   // immediately. For all other classes, we mark their virtual members
17113   // at the end of the translation unit.
17114   if (Class->isLocalClass())
17115     MarkVirtualMembersReferenced(Loc, Class);
17116   else
17117     VTableUses.push_back(std::make_pair(Class, Loc));
17118 }
17119 
17120 bool Sema::DefineUsedVTables() {
17121   LoadExternalVTableUses();
17122   if (VTableUses.empty())
17123     return false;
17124 
17125   // Note: The VTableUses vector could grow as a result of marking
17126   // the members of a class as "used", so we check the size each
17127   // time through the loop and prefer indices (which are stable) to
17128   // iterators (which are not).
17129   bool DefinedAnything = false;
17130   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17131     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17132     if (!Class)
17133       continue;
17134     TemplateSpecializationKind ClassTSK =
17135         Class->getTemplateSpecializationKind();
17136 
17137     SourceLocation Loc = VTableUses[I].second;
17138 
17139     bool DefineVTable = true;
17140 
17141     // If this class has a key function, but that key function is
17142     // defined in another translation unit, we don't need to emit the
17143     // vtable even though we're using it.
17144     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17145     if (KeyFunction && !KeyFunction->hasBody()) {
17146       // The key function is in another translation unit.
17147       DefineVTable = false;
17148       TemplateSpecializationKind TSK =
17149           KeyFunction->getTemplateSpecializationKind();
17150       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17151              TSK != TSK_ImplicitInstantiation &&
17152              "Instantiations don't have key functions");
17153       (void)TSK;
17154     } else if (!KeyFunction) {
17155       // If we have a class with no key function that is the subject
17156       // of an explicit instantiation declaration, suppress the
17157       // vtable; it will live with the explicit instantiation
17158       // definition.
17159       bool IsExplicitInstantiationDeclaration =
17160           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17161       for (auto R : Class->redecls()) {
17162         TemplateSpecializationKind TSK
17163           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17164         if (TSK == TSK_ExplicitInstantiationDeclaration)
17165           IsExplicitInstantiationDeclaration = true;
17166         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17167           IsExplicitInstantiationDeclaration = false;
17168           break;
17169         }
17170       }
17171 
17172       if (IsExplicitInstantiationDeclaration)
17173         DefineVTable = false;
17174     }
17175 
17176     // The exception specifications for all virtual members may be needed even
17177     // if we are not providing an authoritative form of the vtable in this TU.
17178     // We may choose to emit it available_externally anyway.
17179     if (!DefineVTable) {
17180       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17181       continue;
17182     }
17183 
17184     // Mark all of the virtual members of this class as referenced, so
17185     // that we can build a vtable. Then, tell the AST consumer that a
17186     // vtable for this class is required.
17187     DefinedAnything = true;
17188     MarkVirtualMembersReferenced(Loc, Class);
17189     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17190     if (VTablesUsed[Canonical])
17191       Consumer.HandleVTable(Class);
17192 
17193     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17194     // no key function or the key function is inlined. Don't warn in C++ ABIs
17195     // that lack key functions, since the user won't be able to make one.
17196     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17197         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17198       const FunctionDecl *KeyFunctionDef = nullptr;
17199       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17200                            KeyFunctionDef->isInlined())) {
17201         Diag(Class->getLocation(),
17202              ClassTSK == TSK_ExplicitInstantiationDefinition
17203                  ? diag::warn_weak_template_vtable
17204                  : diag::warn_weak_vtable)
17205             << Class;
17206       }
17207     }
17208   }
17209   VTableUses.clear();
17210 
17211   return DefinedAnything;
17212 }
17213 
17214 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17215                                                  const CXXRecordDecl *RD) {
17216   for (const auto *I : RD->methods())
17217     if (I->isVirtual() && !I->isPure())
17218       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17219 }
17220 
17221 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17222                                         const CXXRecordDecl *RD,
17223                                         bool ConstexprOnly) {
17224   // Mark all functions which will appear in RD's vtable as used.
17225   CXXFinalOverriderMap FinalOverriders;
17226   RD->getFinalOverriders(FinalOverriders);
17227   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17228                                             E = FinalOverriders.end();
17229        I != E; ++I) {
17230     for (OverridingMethods::const_iterator OI = I->second.begin(),
17231                                            OE = I->second.end();
17232          OI != OE; ++OI) {
17233       assert(OI->second.size() > 0 && "no final overrider");
17234       CXXMethodDecl *Overrider = OI->second.front().Method;
17235 
17236       // C++ [basic.def.odr]p2:
17237       //   [...] A virtual member function is used if it is not pure. [...]
17238       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17239         MarkFunctionReferenced(Loc, Overrider);
17240     }
17241   }
17242 
17243   // Only classes that have virtual bases need a VTT.
17244   if (RD->getNumVBases() == 0)
17245     return;
17246 
17247   for (const auto &I : RD->bases()) {
17248     const auto *Base =
17249         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17250     if (Base->getNumVBases() == 0)
17251       continue;
17252     MarkVirtualMembersReferenced(Loc, Base);
17253   }
17254 }
17255 
17256 /// SetIvarInitializers - This routine builds initialization ASTs for the
17257 /// Objective-C implementation whose ivars need be initialized.
17258 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17259   if (!getLangOpts().CPlusPlus)
17260     return;
17261   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17262     SmallVector<ObjCIvarDecl*, 8> ivars;
17263     CollectIvarsToConstructOrDestruct(OID, ivars);
17264     if (ivars.empty())
17265       return;
17266     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17267     for (unsigned i = 0; i < ivars.size(); i++) {
17268       FieldDecl *Field = ivars[i];
17269       if (Field->isInvalidDecl())
17270         continue;
17271 
17272       CXXCtorInitializer *Member;
17273       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17274       InitializationKind InitKind =
17275         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17276 
17277       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17278       ExprResult MemberInit =
17279         InitSeq.Perform(*this, InitEntity, InitKind, None);
17280       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17281       // Note, MemberInit could actually come back empty if no initialization
17282       // is required (e.g., because it would call a trivial default constructor)
17283       if (!MemberInit.get() || MemberInit.isInvalid())
17284         continue;
17285 
17286       Member =
17287         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17288                                          SourceLocation(),
17289                                          MemberInit.getAs<Expr>(),
17290                                          SourceLocation());
17291       AllToInit.push_back(Member);
17292 
17293       // Be sure that the destructor is accessible and is marked as referenced.
17294       if (const RecordType *RecordTy =
17295               Context.getBaseElementType(Field->getType())
17296                   ->getAs<RecordType>()) {
17297         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17298         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17299           MarkFunctionReferenced(Field->getLocation(), Destructor);
17300           CheckDestructorAccess(Field->getLocation(), Destructor,
17301                             PDiag(diag::err_access_dtor_ivar)
17302                               << Context.getBaseElementType(Field->getType()));
17303         }
17304       }
17305     }
17306     ObjCImplementation->setIvarInitializers(Context,
17307                                             AllToInit.data(), AllToInit.size());
17308   }
17309 }
17310 
17311 static
17312 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17313                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17314                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17315                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17316                            Sema &S) {
17317   if (Ctor->isInvalidDecl())
17318     return;
17319 
17320   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17321 
17322   // Target may not be determinable yet, for instance if this is a dependent
17323   // call in an uninstantiated template.
17324   if (Target) {
17325     const FunctionDecl *FNTarget = nullptr;
17326     (void)Target->hasBody(FNTarget);
17327     Target = const_cast<CXXConstructorDecl*>(
17328       cast_or_null<CXXConstructorDecl>(FNTarget));
17329   }
17330 
17331   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17332                      // Avoid dereferencing a null pointer here.
17333                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17334 
17335   if (!Current.insert(Canonical).second)
17336     return;
17337 
17338   // We know that beyond here, we aren't chaining into a cycle.
17339   if (!Target || !Target->isDelegatingConstructor() ||
17340       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17341     Valid.insert(Current.begin(), Current.end());
17342     Current.clear();
17343   // We've hit a cycle.
17344   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17345              Current.count(TCanonical)) {
17346     // If we haven't diagnosed this cycle yet, do so now.
17347     if (!Invalid.count(TCanonical)) {
17348       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17349              diag::warn_delegating_ctor_cycle)
17350         << Ctor;
17351 
17352       // Don't add a note for a function delegating directly to itself.
17353       if (TCanonical != Canonical)
17354         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17355 
17356       CXXConstructorDecl *C = Target;
17357       while (C->getCanonicalDecl() != Canonical) {
17358         const FunctionDecl *FNTarget = nullptr;
17359         (void)C->getTargetConstructor()->hasBody(FNTarget);
17360         assert(FNTarget && "Ctor cycle through bodiless function");
17361 
17362         C = const_cast<CXXConstructorDecl*>(
17363           cast<CXXConstructorDecl>(FNTarget));
17364         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17365       }
17366     }
17367 
17368     Invalid.insert(Current.begin(), Current.end());
17369     Current.clear();
17370   } else {
17371     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17372   }
17373 }
17374 
17375 
17376 void Sema::CheckDelegatingCtorCycles() {
17377   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17378 
17379   for (DelegatingCtorDeclsType::iterator
17380          I = DelegatingCtorDecls.begin(ExternalSource),
17381          E = DelegatingCtorDecls.end();
17382        I != E; ++I)
17383     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17384 
17385   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17386     (*CI)->setInvalidDecl();
17387 }
17388 
17389 namespace {
17390   /// AST visitor that finds references to the 'this' expression.
17391   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17392     Sema &S;
17393 
17394   public:
17395     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17396 
17397     bool VisitCXXThisExpr(CXXThisExpr *E) {
17398       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17399         << E->isImplicit();
17400       return false;
17401     }
17402   };
17403 }
17404 
17405 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17406   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17407   if (!TSInfo)
17408     return false;
17409 
17410   TypeLoc TL = TSInfo->getTypeLoc();
17411   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17412   if (!ProtoTL)
17413     return false;
17414 
17415   // C++11 [expr.prim.general]p3:
17416   //   [The expression this] shall not appear before the optional
17417   //   cv-qualifier-seq and it shall not appear within the declaration of a
17418   //   static member function (although its type and value category are defined
17419   //   within a static member function as they are within a non-static member
17420   //   function). [ Note: this is because declaration matching does not occur
17421   //  until the complete declarator is known. - end note ]
17422   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17423   FindCXXThisExpr Finder(*this);
17424 
17425   // If the return type came after the cv-qualifier-seq, check it now.
17426   if (Proto->hasTrailingReturn() &&
17427       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17428     return true;
17429 
17430   // Check the exception specification.
17431   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17432     return true;
17433 
17434   // Check the trailing requires clause
17435   if (Expr *E = Method->getTrailingRequiresClause())
17436     if (!Finder.TraverseStmt(E))
17437       return true;
17438 
17439   return checkThisInStaticMemberFunctionAttributes(Method);
17440 }
17441 
17442 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17443   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17444   if (!TSInfo)
17445     return false;
17446 
17447   TypeLoc TL = TSInfo->getTypeLoc();
17448   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17449   if (!ProtoTL)
17450     return false;
17451 
17452   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17453   FindCXXThisExpr Finder(*this);
17454 
17455   switch (Proto->getExceptionSpecType()) {
17456   case EST_Unparsed:
17457   case EST_Uninstantiated:
17458   case EST_Unevaluated:
17459   case EST_BasicNoexcept:
17460   case EST_NoThrow:
17461   case EST_DynamicNone:
17462   case EST_MSAny:
17463   case EST_None:
17464     break;
17465 
17466   case EST_DependentNoexcept:
17467   case EST_NoexceptFalse:
17468   case EST_NoexceptTrue:
17469     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17470       return true;
17471     LLVM_FALLTHROUGH;
17472 
17473   case EST_Dynamic:
17474     for (const auto &E : Proto->exceptions()) {
17475       if (!Finder.TraverseType(E))
17476         return true;
17477     }
17478     break;
17479   }
17480 
17481   return false;
17482 }
17483 
17484 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17485   FindCXXThisExpr Finder(*this);
17486 
17487   // Check attributes.
17488   for (const auto *A : Method->attrs()) {
17489     // FIXME: This should be emitted by tblgen.
17490     Expr *Arg = nullptr;
17491     ArrayRef<Expr *> Args;
17492     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17493       Arg = G->getArg();
17494     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17495       Arg = G->getArg();
17496     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17497       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17498     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17499       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17500     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17501       Arg = ETLF->getSuccessValue();
17502       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17503     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17504       Arg = STLF->getSuccessValue();
17505       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17506     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17507       Arg = LR->getArg();
17508     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17509       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17510     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17511       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17512     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17513       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17514     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17515       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17516     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17517       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17518 
17519     if (Arg && !Finder.TraverseStmt(Arg))
17520       return true;
17521 
17522     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17523       if (!Finder.TraverseStmt(Args[I]))
17524         return true;
17525     }
17526   }
17527 
17528   return false;
17529 }
17530 
17531 void Sema::checkExceptionSpecification(
17532     bool IsTopLevel, ExceptionSpecificationType EST,
17533     ArrayRef<ParsedType> DynamicExceptions,
17534     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17535     SmallVectorImpl<QualType> &Exceptions,
17536     FunctionProtoType::ExceptionSpecInfo &ESI) {
17537   Exceptions.clear();
17538   ESI.Type = EST;
17539   if (EST == EST_Dynamic) {
17540     Exceptions.reserve(DynamicExceptions.size());
17541     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17542       // FIXME: Preserve type source info.
17543       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17544 
17545       if (IsTopLevel) {
17546         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17547         collectUnexpandedParameterPacks(ET, Unexpanded);
17548         if (!Unexpanded.empty()) {
17549           DiagnoseUnexpandedParameterPacks(
17550               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17551               Unexpanded);
17552           continue;
17553         }
17554       }
17555 
17556       // Check that the type is valid for an exception spec, and
17557       // drop it if not.
17558       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17559         Exceptions.push_back(ET);
17560     }
17561     ESI.Exceptions = Exceptions;
17562     return;
17563   }
17564 
17565   if (isComputedNoexcept(EST)) {
17566     assert((NoexceptExpr->isTypeDependent() ||
17567             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17568             Context.BoolTy) &&
17569            "Parser should have made sure that the expression is boolean");
17570     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17571       ESI.Type = EST_BasicNoexcept;
17572       return;
17573     }
17574 
17575     ESI.NoexceptExpr = NoexceptExpr;
17576     return;
17577   }
17578 }
17579 
17580 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17581              ExceptionSpecificationType EST,
17582              SourceRange SpecificationRange,
17583              ArrayRef<ParsedType> DynamicExceptions,
17584              ArrayRef<SourceRange> DynamicExceptionRanges,
17585              Expr *NoexceptExpr) {
17586   if (!MethodD)
17587     return;
17588 
17589   // Dig out the method we're referring to.
17590   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17591     MethodD = FunTmpl->getTemplatedDecl();
17592 
17593   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17594   if (!Method)
17595     return;
17596 
17597   // Check the exception specification.
17598   llvm::SmallVector<QualType, 4> Exceptions;
17599   FunctionProtoType::ExceptionSpecInfo ESI;
17600   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17601                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17602                               ESI);
17603 
17604   // Update the exception specification on the function type.
17605   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17606 
17607   if (Method->isStatic())
17608     checkThisInStaticMemberFunctionExceptionSpec(Method);
17609 
17610   if (Method->isVirtual()) {
17611     // Check overrides, which we previously had to delay.
17612     for (const CXXMethodDecl *O : Method->overridden_methods())
17613       CheckOverridingFunctionExceptionSpec(Method, O);
17614   }
17615 }
17616 
17617 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17618 ///
17619 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17620                                        SourceLocation DeclStart, Declarator &D,
17621                                        Expr *BitWidth,
17622                                        InClassInitStyle InitStyle,
17623                                        AccessSpecifier AS,
17624                                        const ParsedAttr &MSPropertyAttr) {
17625   IdentifierInfo *II = D.getIdentifier();
17626   if (!II) {
17627     Diag(DeclStart, diag::err_anonymous_property);
17628     return nullptr;
17629   }
17630   SourceLocation Loc = D.getIdentifierLoc();
17631 
17632   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17633   QualType T = TInfo->getType();
17634   if (getLangOpts().CPlusPlus) {
17635     CheckExtraCXXDefaultArguments(D);
17636 
17637     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17638                                         UPPC_DataMemberType)) {
17639       D.setInvalidType();
17640       T = Context.IntTy;
17641       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17642     }
17643   }
17644 
17645   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17646 
17647   if (D.getDeclSpec().isInlineSpecified())
17648     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17649         << getLangOpts().CPlusPlus17;
17650   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17651     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17652          diag::err_invalid_thread)
17653       << DeclSpec::getSpecifierName(TSCS);
17654 
17655   // Check to see if this name was declared as a member previously
17656   NamedDecl *PrevDecl = nullptr;
17657   LookupResult Previous(*this, II, Loc, LookupMemberName,
17658                         ForVisibleRedeclaration);
17659   LookupName(Previous, S);
17660   switch (Previous.getResultKind()) {
17661   case LookupResult::Found:
17662   case LookupResult::FoundUnresolvedValue:
17663     PrevDecl = Previous.getAsSingle<NamedDecl>();
17664     break;
17665 
17666   case LookupResult::FoundOverloaded:
17667     PrevDecl = Previous.getRepresentativeDecl();
17668     break;
17669 
17670   case LookupResult::NotFound:
17671   case LookupResult::NotFoundInCurrentInstantiation:
17672   case LookupResult::Ambiguous:
17673     break;
17674   }
17675 
17676   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17677     // Maybe we will complain about the shadowed template parameter.
17678     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17679     // Just pretend that we didn't see the previous declaration.
17680     PrevDecl = nullptr;
17681   }
17682 
17683   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17684     PrevDecl = nullptr;
17685 
17686   SourceLocation TSSL = D.getBeginLoc();
17687   MSPropertyDecl *NewPD =
17688       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17689                              MSPropertyAttr.getPropertyDataGetter(),
17690                              MSPropertyAttr.getPropertyDataSetter());
17691   ProcessDeclAttributes(TUScope, NewPD, D);
17692   NewPD->setAccess(AS);
17693 
17694   if (NewPD->isInvalidDecl())
17695     Record->setInvalidDecl();
17696 
17697   if (D.getDeclSpec().isModulePrivateSpecified())
17698     NewPD->setModulePrivate();
17699 
17700   if (NewPD->isInvalidDecl() && PrevDecl) {
17701     // Don't introduce NewFD into scope; there's already something
17702     // with the same name in the same scope.
17703   } else if (II) {
17704     PushOnScopeChains(NewPD, S);
17705   } else
17706     Record->addDecl(NewPD);
17707 
17708   return NewPD;
17709 }
17710 
17711 void Sema::ActOnStartFunctionDeclarationDeclarator(
17712     Declarator &Declarator, unsigned TemplateParameterDepth) {
17713   auto &Info = InventedParameterInfos.emplace_back();
17714   TemplateParameterList *ExplicitParams = nullptr;
17715   ArrayRef<TemplateParameterList *> ExplicitLists =
17716       Declarator.getTemplateParameterLists();
17717   if (!ExplicitLists.empty()) {
17718     bool IsMemberSpecialization, IsInvalid;
17719     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17720         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17721         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17722         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17723         /*SuppressDiagnostic=*/true);
17724   }
17725   if (ExplicitParams) {
17726     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17727     for (NamedDecl *Param : *ExplicitParams)
17728       Info.TemplateParams.push_back(Param);
17729     Info.NumExplicitTemplateParams = ExplicitParams->size();
17730   } else {
17731     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17732     Info.NumExplicitTemplateParams = 0;
17733   }
17734 }
17735 
17736 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17737   auto &FSI = InventedParameterInfos.back();
17738   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17739     if (FSI.NumExplicitTemplateParams != 0) {
17740       TemplateParameterList *ExplicitParams =
17741           Declarator.getTemplateParameterLists().back();
17742       Declarator.setInventedTemplateParameterList(
17743           TemplateParameterList::Create(
17744               Context, ExplicitParams->getTemplateLoc(),
17745               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17746               ExplicitParams->getRAngleLoc(),
17747               ExplicitParams->getRequiresClause()));
17748     } else {
17749       Declarator.setInventedTemplateParameterList(
17750           TemplateParameterList::Create(
17751               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17752               SourceLocation(), /*RequiresClause=*/nullptr));
17753     }
17754   }
17755   InventedParameterInfos.pop_back();
17756 }
17757